Files
UA-.NETStandard/tests/Opc.Ua.SourceGeneration.Tests/NodesetExtendedNodeIdTests.cs
Copilot 02fb72e2d3 Support guid/opaque nodeids in NodeSet import (#4507)
# Description

`NodeSetToModelDesign.ImportNode` only stored Numeric and String NodeId
identifiers. Guid and Opaque identifiers (both valid per OPC 10000-3
5.2.2) fell through to an `Information` log line, so the node was
registered in `NodesByQName`/`NodesById` with no identifier at all and
code generation continued against a node whose identity had been
discarded.

The `ModelDesign` schema has no representation for Guid/Opaque
identifiers (`NodeDesign` exposes only `NumericId`/`StringId`), so the
import now fails loudly instead of emitting output that looks correct.

- **Importer**: the fall-through branches in `ImportNode` are replaced
with an `InvalidDataException` naming the NodeId, browse name and
identifier type. This matches the existing unsupported-input handling in
the file and surfaces through `ModelCompilation` as a generator
diagnostic.
- **Logger removal**: `m_logger` had no remaining use in
`NodeSetToModelDesign` and was removed along with its
`Microsoft.Extensions.Logging` import.
- **Tests**: `ImportUnsupportedNodeIdTypeThrowsInvalidDataException`
covers Guid, empty Guid and Opaque identifiers via an in-memory NodeSet.
- **Docs**: the source generator readme states the NodeSet2 identifier
restriction.

```csharp
else
{
    // The model design can only carry numeric and string identifiers.
    // Guid and Opaque identifiers (OPC 10000-3 5.2.2) would be dropped
    // and code would be generated for a node without any identity, so
    // the import fails instead of silently producing wrong output.
    throw new InvalidDataException(
        $"NodeId ({input.NodeId}) of node '{input.BrowseName}' uses the " +
        $"{nodeId.IdType} identifier type which is not supported by the model " +
        "design. Only Numeric and String identifiers can be imported.");
}
```

Note on behaviour: a null/unspecified NodeId parses as a Numeric
identifier (`i=0`) and is still handled by the numeric branch, so the
removed `IsNull` branch was only ever reachable for an empty Guid or
Opaque identifier, which is now reported as unsupported.

## Related Issues

## Checklist

_Put an `x` in the boxes that apply. You can complete these step by step
after opening the PR._

- [x] 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.
- [x] 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.

<!-- START COPILOT CODING AGENT SUFFIX -->

- Fixes #4504

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>
Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-09-21 14:52:55 +02:00

155 lines
6.7 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2026 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.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using NUnit.Framework;
namespace Opc.Ua.SourceGeneration
{
/// <summary>
/// A NodeSet2 may identify a node with any of the four identifier types of
/// OPC 10000-3 5.2.2. Guid and Opaque identifiers used to be dropped during
/// the import, leaving a node without any identity in the generated code.
/// </summary>
[TestFixture]
[Category("SourceGeneration")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
public class NodesetExtendedNodeIdTests
{
[Test]
public void NodeSetWithGuidAndOpaqueNodeIdsGeneratesCompilableIdentifiers()
{
CSharpCompilation compilation = OptimizationLevel.Release
.CreateCompilation()
.AddCode(
new Dictionary<string, string>().WithOpcUaGeneratedStack(),
LanguageVersion.CSharp13);
var options = new AnalyzerOptionsProvider(
new Dictionary<string, string>
{
["build_property.ModelSourceGeneratorOmitFluentApi"] = "true"
});
options.TextOptions["ExtendedIds.NodeSet2.xml"] = new Dictionary<string, string>
{
["build_metadata.AdditionalFiles.ModelSourceGeneratorModelUri"] =
"urn:test:extended-ids",
["build_metadata.AdditionalFiles.ModelSourceGeneratorName"] = "TestExtendedIds",
["build_metadata.AdditionalFiles.ModelSourceGeneratorPrefix"] =
"Opc.Ua.TestExtendedIds"
};
var generator = new ModelSourceGenerator();
GeneratorDriver driver = CSharpGeneratorDriver.Create(generator)
.WithUpdatedParseOptions(
new CSharpParseOptions()
.WithKind(SourceCodeKind.Regular)
.WithLanguageVersion(LanguageVersion.CSharp13))
.AddAdditionalTexts(
[
EmbeddedText.Create("ExtendedIds.NodeSet2.xml", NodeSet)
])
.WithUpdatedAnalyzerConfigOptions(options);
driver = driver.RunGeneratorsAndUpdateCompilation(
compilation,
out Compilation outputCompilation,
out ImmutableArray<Diagnostic> diagnostics);
Assert.That(
diagnostics.Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error),
Is.Empty,
string.Join("\n", diagnostics.Select(diagnostic => diagnostic.ToString())));
string generated = string.Join(
"\n",
driver.GetRunResult().Results[0].GeneratedSources
.Select(source => source.SourceText.ToString()));
Assert.Multiple(() =>
{
Assert.That(
generated,
Does.Contain(
"public static readonly global::System.Guid GuidObject = " +
"new global::System.Guid(\"09087e75-8e5e-499b-954f-f2a9603db28a\");"));
Assert.That(
generated,
Does.Contain(
"public static readonly global::Opc.Ua.ByteString OpaqueObject = " +
"global::Opc.Ua.ByteString.FromBase64(\"M/RbKBsRVkePCePcx24oRA==\");"));
});
outputCompilation.GetDiagnostics().Check(
TestContext.Out,
out int errors,
out _);
Assert.That(errors, Is.Zero, $"Compilation produced {errors} errors");
}
private const string NodeSet =
"""
<?xml version="1.0" encoding="utf-8"?>
<UANodeSet xmlns:uax="http://opcfoundation.org/UA/2008/02/Types.xsd"
xmlns="http://opcfoundation.org/UA/2011/03/UANodeSet.xsd">
<NamespaceUris>
<Uri>urn:test:extended-ids</Uri>
</NamespaceUris>
<Models>
<Model ModelUri="urn:test:extended-ids" Version="1.0.0"
PublicationDate="2026-01-01T00:00:00Z">
<RequiredModel ModelUri="http://opcfoundation.org/UA/" />
</Model>
</Models>
<UAObjectType NodeId="ns=1;i=1000" BrowseName="1:PlantType">
<References>
<Reference ReferenceType="i=45" IsForward="false">i=58</Reference>
</References>
</UAObjectType>
<UAObject NodeId="ns=1;g=09087e75-8e5e-499b-954f-f2a9603db28a"
BrowseName="1:GuidObject">
<References>
<Reference ReferenceType="i=40">ns=1;i=1000</Reference>
<Reference ReferenceType="i=35" IsForward="false">i=85</Reference>
</References>
</UAObject>
<UAObject NodeId="ns=1;b=M/RbKBsRVkePCePcx24oRA==" BrowseName="1:OpaqueObject">
<References>
<Reference ReferenceType="i=40">ns=1;i=1000</Reference>
<Reference ReferenceType="i=35" IsForward="false">i=85</Reference>
</References>
</UAObject>
</UANodeSet>
""";
}
}