Files
UA-.NETStandard/tests/Opc.Ua.InformationModel.Tests/AliasNameTestHelpers.cs
romanettandClaude Opus 5.5 9b034f8291 Enable nullable reference types centrally; migrate all unset and annotations-only projects (#4700)
# Description

Nullable reference types are now enabled once, in `common.props`, and
every project in the repository builds warning-clean with them.

**Configuration**
- `<Nullable>enable</Nullable>` lives in `common.props`. All per-project
`<Nullable>` settings are removed: 178 project files (enable,
annotations, and the `disable` in the three Aot test projects).
- 419 per-file `#nullable enable`/`restore` directives and the 4
`#nullable disable` directives are removed.
- Kept on purpose:
- The 5 `<auto-generated>` schema files (`UANodeSet.cs`, `UA Type
Dictionary.cs`, `OPCBinarySchema.cs`, `SecuredApplication.cs`,
`PInvokeHelper.cs`) keep `#nullable enable`. The compiler ignores the
project setting in generated code, so the directive is required there.
- `tests/Opc.Ua.Interop.LegacyPeer` keeps `disable`. It builds against
the 1.5.378 packages and does not import the repository props.
- `docs/DeveloperGuide.md` and `.github/copilot-instructions.md` now
describe the central setting.

**Migration** (the 43 unset and 13 annotations-only projects, roughly
10k diagnostics)
- **Production code: annotated at the declarations.** Covers
`tools/Opc.Ua.SourceGeneration.Core`, `src/Opc.Ua.Lds.Server` and the
LDS sample.
- Members, parameters and returns are nullable where null actually
flows.
- Null-check helpers carry `[NotNullWhen]` (`IsNull`, `IsValidXmlName`,
`IsMethodTypeDesign`).
- `CoreUtils.Format`, `Utils.Format`, `ITemplateWriter.WriteLine` take
`params object?[]`. `Template.AddReplacement` takes `string?` (rendering
already skips null replacements).
- `IRegisteredServerStore.RegisterAsync` returns
`Task<RegistrationEntry?>`: it returns null when a registration is
removed.
- Dereferences backed by an invariant (for example, the validated model)
use `!`, so runtime behaviour is unchanged.
- **Behavioural changes in production code** (small, deliberate):
- `NodeSetToModelDesign` throws `InvalidOperationException` when the
file is not a NodeSet. Before, it threw a NullReferenceException on the
next line.
- `ModelDesignValidator` starts its lookup tables empty instead of null.
A redundant `if (m_nodes == null) return;` guard is gone.
- **Test code: minimal annotations.**
  - `?` on values that can be null, `!` where the test asserts non-null.
  - `= null!` for fixture members assigned in SetUp.
- `TryGetStructure<T>(out T? x)` where the inferred `T?` broke the
`IEncodeable` constraint.
- A few redundant `== null` checks on structs (`NodeId`, `ArrayOf<T>`)
folded into the adjacent `IsNull`/`Count` checks.

**Notes for reviewers**
- The diff is large (~1,500 files) but almost entirely mechanical: `?`,
`!` and directive removal. The non-annotation changes are listed above.
- Known follow-up, not done here:
`IModelDesign.Namespaces/TargetNamespace/NamespaceUris` stay
non-nullable even though the validator returns null before it loads a
dictionary. Making them nullable would ripple through every generator
call site.

## Related Issues

- Fixes #4439

## Checklist

- [ ] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [ ] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

The "no new warnings" box covers net10.0 and net48: full non-incremental
builds of `UA.slnx`, `tools/SourceGeneration.slnx`,
`tools/MigrationAnalyzer.slnx` and the Aot test projects finished with 0
warnings and 0 errors under the repository's warnings-as-errors
settings. net9.0 and net8.0 also had no nullable diagnostics, but they
were not rebuilt after the final fixes. Tests have not been run locally
yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 08:48:13 +02:00

401 lines
16 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;
using System.Threading.Tasks;
using NUnit.Framework;
using Opc.Ua.Client;
namespace Opc.Ua.InformationModel.Tests
{
/// <summary>
/// Shared helpers for the AliasName conformance tests. Provides constants
/// for the standard NodeIds defined by OPC UA Part 17 and reusable helper
/// methods for browsing the Aliases hierarchy and invoking the FindAlias
/// method on alias categories.
/// </summary>
internal static class AliasNameTestHelpers
{
public const uint AliasNameTypeId = 23455;
public const uint AliasNameCategoryTypeId = 23456;
public const uint AliasNameDataTypeId = 23468;
public const uint AliasNameDataTypeBinaryEncodingId = 23499;
public const uint AliasForReferenceTypeId = 23469;
public const uint AliasesObjectId = 23470;
public static readonly NodeId AliasNameTypeNodeId = new(AliasNameTypeId);
public static readonly NodeId AliasNameCategoryTypeNodeId = new(AliasNameCategoryTypeId);
public static readonly NodeId AliasNameDataTypeNodeId = new(AliasNameDataTypeId);
public static readonly NodeId AliasForNodeId = new(AliasForReferenceTypeId);
public static readonly NodeId AliasesNodeId = new(AliasesObjectId);
/// <summary>
/// Read a single attribute from a node.
/// </summary>
public static async Task<DataValue> ReadAttributeAsync(
ISession session, NodeId nodeId, uint attributeId)
{
ReadResponse response = await session.ReadAsync(
null, 0, TimestampsToReturn.Both,
new ReadValueId[]
{
new() { NodeId = nodeId, AttributeId = attributeId }
}.ToArrayOf(),
CancellationToken.None).ConfigureAwait(false);
Assert.That(response.Results.Count, Is.EqualTo(1));
return response.Results[0];
}
/// <summary>
/// Forward-browse a node's hierarchical references and return the
/// child references.
/// </summary>
public static Task<IList<ReferenceDescription>> BrowseChildrenAsync(
ISession session, NodeId nodeId)
{
return BrowseChildrenAsync(
session, nodeId, ReferenceTypeIds.HierarchicalReferences);
}
/// <summary>
/// Forward-browse the given reference type from a node and return
/// the child references.
/// </summary>
public static async Task<IList<ReferenceDescription>> BrowseChildrenAsync(
ISession session, NodeId nodeId, NodeId referenceTypeId)
{
BrowseResponse response = await session.BrowseAsync(
null, null, 0,
new BrowseDescription[]
{
new() {
NodeId = nodeId,
BrowseDirection = BrowseDirection.Forward,
ReferenceTypeId = referenceTypeId,
IncludeSubtypes = true,
NodeClassMask = 0,
ResultMask = (uint)BrowseResultMask.All
}
}.ToArrayOf(),
CancellationToken.None).ConfigureAwait(false);
Assert.That(response.Results.Count, Is.EqualTo(1));
Assert.That(StatusCode.IsGood(response.Results[0].StatusCode), Is.True,
$"Browse of {nodeId} failed: {response.Results[0].StatusCode}");
return response.Results[0].References.ToArray()!;
}
/// <summary>
/// Locates the AliasNameCategory child of <see cref="AliasesNodeId"/>
/// with the given browse-name and the FindAlias method declared on it.
/// Skips the calling test (Assert.Ignore) when the server does not
/// expose the category or method.
/// </summary>
public static async Task<(NodeId CategoryId, NodeId FindAliasMethodId)>
FindCategoryAsync(ISession session, string categoryBrowseName)
{
IList<ReferenceDescription> children =
await BrowseChildrenAsync(session, AliasesNodeId).ConfigureAwait(false);
// The standard NodeSet exposes empty placeholder TagVariables /
// Topics objects in namespace 0 with no working FindAlias
// implementation. Prefer a category whose NodeId is NOT in
// namespace 0 (i.e. provided by the server's address space).
NodeId categoryId = NodeId.Null;
NodeId fallbackId = NodeId.Null;
foreach (ReferenceDescription child in children)
{
if (child.BrowseName.Name != categoryBrowseName ||
child.NodeClass != NodeClass.Object)
{
continue;
}
var resolved = ExpandedNodeId.ToNodeId(
child.NodeId, session.NamespaceUris);
if (resolved.NamespaceIndex != 0)
{
categoryId = resolved;
break;
}
if (fallbackId.IsNull)
{
fallbackId = resolved;
}
}
if (categoryId.IsNull)
{
categoryId = fallbackId;
}
if (categoryId.IsNull)
{
Assert.Ignore(
$"Server does not expose an AliasNameCategory '{categoryBrowseName}' under Aliases (i=23470).");
}
NodeId methodId = await FindMethodAsync(
session, categoryId, "FindAlias").ConfigureAwait(false);
if (methodId.IsNull)
{
Assert.Ignore(
$"Server does not expose a FindAlias method on category '{categoryBrowseName}'.");
}
return (categoryId, methodId);
}
/// <summary>
/// Locates a method node with the given browse-name as a child of
/// <paramref name="parent"/>. Returns <see cref="NodeId.Null"/>
/// when no such method exists.
/// </summary>
public static async Task<NodeId> FindMethodAsync(
ISession session, NodeId parent, string methodBrowseName)
{
IList<ReferenceDescription> children =
await BrowseChildrenAsync(session, parent).ConfigureAwait(false);
foreach (ReferenceDescription child in children)
{
if (child.NodeClass == NodeClass.Method &&
child.BrowseName.Name == methodBrowseName)
{
return ExpandedNodeId.ToNodeId(
child.NodeId, session.NamespaceUris);
}
}
return NodeId.Null;
}
/// <summary>
/// Calls <c>FindAlias(pattern, referenceTypeFilter)</c> on the given
/// category and returns the raw <see cref="CallMethodResult"/>.
/// </summary>
public static async Task<CallMethodResult> CallFindAliasAsync(
ISession session,
NodeId categoryId,
NodeId findAliasMethodId,
string pattern,
NodeId referenceTypeFilter)
{
CallResponse response = await session.CallAsync(
null,
new CallMethodRequest[]
{
new() {
ObjectId = categoryId,
MethodId = findAliasMethodId,
InputArguments = new Variant[]
{
new(pattern),
new(referenceTypeFilter)
}.ToArrayOf()
}
}.ToArrayOf(),
CancellationToken.None).ConfigureAwait(false);
Assert.That(response.Results.Count, Is.EqualTo(1));
return response.Results[0];
}
/// <summary>
/// Decodes the AliasNameDataType[] returned by FindAlias from the
/// CallMethodResult's first output argument. The server encodes each
/// record as { QualifiedName AliasName, NodeId[] ReferencedNodes }.
/// </summary>
public static IList<AliasRecord> DecodeAliasResults(
ISession session, CallMethodResult result)
{
var records = new List<AliasRecord>();
if (result == null || result.OutputArguments.Count == 0)
{
return records;
}
if (!result.OutputArguments[0].TryGetValue(out ArrayOf<ExtensionObject> aliasArray))
{
return records;
}
for (int i = 0; i < aliasArray.Count; i++)
{
ExtensionObject ext = aliasArray.Span[i];
if (ext.IsNull)
{
continue;
}
if (ext.TryGetValue(out AliasNameDataType? typed,
session.MessageContext) &&
typed != null)
{
NodeId[] refs;
if (typed.ReferencedNodes.Count > 0)
{
refs = new NodeId[typed.ReferencedNodes.Count];
for (int j = 0; j < typed.ReferencedNodes.Count; j++)
{
refs[j] = ExpandedNodeId.ToNodeId(
typed.ReferencedNodes[j], session.NamespaceUris);
}
}
else
{
refs = [];
}
records.Add(new AliasRecord(typed.AliasName, refs));
continue;
}
if (ext.TryGetAsBinary(out ByteString body) && !body.IsNull)
{
using var decoder = new BinaryDecoder(
body.ToArray(), session.MessageContext);
QualifiedName aliasName = decoder.ReadQualifiedName("AliasName");
ArrayOf<NodeId> referenced =
decoder.ReadNodeIdArray("ReferencedNodes");
records.Add(new AliasRecord(
aliasName,
referenced.ToArray() ?? []));
}
}
return records;
}
/// <summary>
/// Locates a method by BrowseName and fails the test when the server
/// does not expose it. The optional Part 17 methods do have reserved
/// NodeIds (StandardTypes.csv), but no generated <c>MethodIds</c>
/// constants exist for them — the ModelDesign does not declare the
/// children — so tests resolve them by browsing, as a client
/// without prior knowledge would.
/// </summary>
public static async Task<NodeId> RequireMethodAsync(
ISession session, NodeId parent, string methodBrowseName)
{
NodeId methodId = await FindMethodAsync(session, parent, methodBrowseName)
.ConfigureAwait(false);
Assert.That(methodId.IsNull, Is.False,
$"Expected a '{methodBrowseName}' method under {parent}.");
return methodId;
}
/// <summary>
/// Calls a method with the given input arguments and returns the raw
/// <see cref="CallMethodResult"/> without asserting on its status —
/// callers that expect a failure inspect it themselves.
/// </summary>
public static async Task<CallMethodResult> CallMethodAsync(
ISession session,
NodeId objectId,
NodeId methodId,
params Variant[] inputArguments)
{
CallResponse response = await session.CallAsync(
null,
new CallMethodRequest[]
{
new() {
ObjectId = objectId,
MethodId = methodId,
InputArguments = inputArguments.ToArrayOf()
}
}.ToArrayOf(),
CancellationToken.None).ConfigureAwait(false);
Assert.That(response.Results.Count, Is.EqualTo(1));
return response.Results[0];
}
/// <summary>
/// Decodes the AliasNameVerboseDataType[] returned by
/// FindAliasVerbose from the first output argument.
/// </summary>
public static IList<AliasNameVerboseDataType> DecodeVerboseAliasResults(
ISession session, CallMethodResult result)
{
var records = new List<AliasNameVerboseDataType>();
if (result == null || result.OutputArguments.Count == 0)
{
return records;
}
if (!result.OutputArguments[0].TryGetValue(out ArrayOf<ExtensionObject> aliasArray))
{
return records;
}
for (int i = 0; i < aliasArray.Count; i++)
{
ExtensionObject ext = aliasArray.Span[i];
if (!ext.IsNull &&
ext.TryGetValue(out AliasNameVerboseDataType? typed, session.MessageContext) &&
typed != null)
{
records.Add(typed);
}
}
return records;
}
/// <summary>
/// Returns true when the referenced node is an instance of
/// <c>PublishedDataSetType</c> (i=14509) or one of its subtypes —
/// the "is a Dataset" check the Topics conformance unit applies to
/// every alias target.
/// </summary>
public static async Task<bool> IsPublishedDataSetAsync(
ISession session, ReferenceDescription target)
{
if (target.TypeDefinition.IsNull)
{
return false;
}
// The session's node cache walks (and memoizes) the subtype
// chain, so repeated targets of the same type cost one lookup
// instead of one Browse round trip per hierarchy level.
return await session.NodeCache.IsTypeOfAsync(
target.TypeDefinition,
ObjectTypeIds.PublishedDataSetType,
CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
/// Plain record describing a single alias entry returned by FindAlias.
/// </summary>
internal sealed record AliasRecord(QualifiedName AliasName, NodeId[] ReferencedNodes);
}
}