Files
UA-.NETStandard/tests/Opc.Ua.Server.Tests/Fluent/FluentHandlerRegressionTests.cs
romanett 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

300 lines
14 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;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Opc.Ua.Server.Fluent;
using Opc.Ua.Tests;
namespace Opc.Ua.Server.Tests.Fluent
{
/// <summary>
/// Verifies fluent handler registration boundaries and dispatch for dynamically authored nodes.
/// </summary>
[TestFixture]
[Category("Fluent")]
public sealed class FluentHandlerRegressionTests
{
/// <summary>
/// Verifies that a retained builder rejects every handler registration after sealing without mutating
/// callbacks.
/// </summary>
[Test]
public void RetainedNodeBuilderCannotRegisterHandlersAfterSealing(
[Values("historyRead", "historyUpdate", "created", "creating", "modified", "deleted", "mode",
"added", "removed", "refresh", "event", "read", "write", "call")] string handler)
{
var harness = new HandlerHarness();
INodeBuilder node = harness.Builder.Node(handler == "call" ? harness.Method.NodeId : harness.Variable.NodeId);
harness.Builder.SealGraphAuthoring();
ServiceResultException exception = Assert.Throws<ServiceResultException>(() => Wire(node, handler));
Assert.That(exception.StatusCode, Is.EqualTo(StatusCodes.BadInvalidState));
foreach (string name in s_handlerMaps)
{
var handlers = (IDictionary)typeof(NodeManagerBuilder)
.GetField(name, BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(harness.Builder)!;
Assert.That(handlers, Is.Empty);
}
Assert.That(harness.Variable.OnConditionRefresh, Is.Null);
Assert.That(harness.Variable.OnReportEvent, Is.Null);
Assert.That(harness.Variable.OnSimpleReadValue, Is.Null);
Assert.That(harness.Variable.OnSimpleWriteValue, Is.Null);
Assert.That(harness.Method.OnCallMethod2Async, Is.Null);
}
/// <summary>
/// Verifies that ad hoc objects dispatch history, removal, and condition-refresh handlers for their own node.
/// </summary>
[TestCase("reference")]
[TestCase("instance")]
[TestCase("rootInstance")]
public void AdHocNodesDispatchHistoryRemovalAndConditionRefreshHandlers(string form)
{
var harness = new HandlerHarness();
INodeBuilder parent = harness.Builder.Node(harness.Root.NodeId);
INodeBuilder created = form switch
{
"reference" => parent.AddObject(new QualifiedName("Child", 1)),
"instance" => parent.CreateInstance(new QualifiedName("Child", 1), node => new BaseObjectState(node)).AsNode(),
_ => harness.Builder.CreateInstance(new QualifiedName("Child", 1), node => new BaseObjectState(node)).AsNode()
};
int removed = 0;
IFilterTarget expectedEvent = Mock.Of<IFilterTarget>();
created.OnHistoryRead((_, node, _, _, _, _, result) =>
{
Assert.That(node, Is.SameAs(created.Node));
result.ContinuationPoint = ByteString.From([3, 7]);
return StatusCodes.GoodMoreData;
})
.OnHistoryUpdate((_, node, _, result) =>
{
Assert.That(node, Is.SameAs(created.Node));
result.OperationResults = [StatusCodes.GoodClamped];
return ServiceResult.Good;
})
.OnNodeRemoved((_, node) =>
{
Assert.That(node, Is.SameAs(created.Node));
removed++;
})
.OnConditionRefresh((_, _, events) => events.Add(expectedEvent));
harness.Builder.SealGraphAuthoring();
var read = new HistoryReadResult();
Assert.That(harness.Builder.Dispatcher.TryHandleHistoryRead(
harness.Context, created.Node, new ReadRawModifiedDetails(), TimestampsToReturn.Both, false,
new HistoryReadValueId(), read, out ServiceResult readStatus), Is.True);
Assert.That(readStatus.StatusCode, Is.EqualTo(StatusCodes.GoodMoreData));
Assert.That(read.ContinuationPoint.ToArray(), Is.EqualTo(s_continuation));
var update = new HistoryUpdateResult();
Assert.That(harness.Builder.Dispatcher.TryHandleHistoryUpdate(
harness.Context, created.Node, new UpdateDataDetails(), update, out ServiceResult updateStatus), Is.True);
Assert.That(updateStatus.StatusCode, Is.EqualTo(StatusCodes.Good));
Assert.That(update.OperationResults[0], Is.EqualTo(StatusCodes.GoodClamped));
harness.Builder.Dispatcher.NotifyNodeRemoved(harness.Context, harness.Root);
Assert.That(removed, Is.Zero);
harness.Builder.Dispatcher.NotifyNodeRemoved(harness.Context, created.Node);
Assert.That(removed, Is.EqualTo(1));
var events = new List<IFilterTarget>();
Assert.That(created.Node.OnConditionRefresh, Is.Not.Null);
created.Node.OnConditionRefresh(harness.Context, created.Node, events);
Assert.That(events, Has.Count.EqualTo(1));
Assert.That(events[0], Is.SameAs(expectedEvent));
}
/// <summary>
/// Verifies that an ad hoc builder without dispatcher support reports a configuration error instead of ignoring
/// handlers.
/// </summary>
[TestCase("historyRead")]
[TestCase("historyUpdate")]
[TestCase("removed")]
public void UnsupportedAdHocManagerRejectsHandlersInsteadOfSilentlyIgnoringThem(string handler)
{
var node = new BaseObjectState(null) { NodeId = new NodeId(1, 1) };
var builder = new AdHocInstanceNodeBuilder<BaseObjectState>(Mock.Of<INodeManagerBuilder>(), node);
ServiceResultException exception = Assert.Throws<ServiceResultException>(() => Wire(builder, handler));
Assert.That(exception.StatusCode, Is.EqualTo(StatusCodes.BadConfigurationError));
}
/// <summary>
/// Registers the selected handler kind to exercise authoring and dispatcher capability checks.
/// </summary>
private static void Wire(INodeBuilder node, string handler)
{
switch (handler)
{
case "historyRead":
node.OnHistoryRead((_, _, _, _, _, _, _) => ServiceResult.Good);
break;
case "historyUpdate":
node.OnHistoryUpdate((_, _, _, _) => ServiceResult.Good);
break;
case "created":
node.OnMonitoredItemCreated((_, _, _) => { });
break;
case "creating":
node.OnCreateMonitoredItem((_, _) => default);
break;
case "modified":
node.OnMonitoredItemModified((_, _, _, _) => default);
break;
case "deleted":
node.OnMonitoredItemDeleted((_, _, _, _) => default);
break;
case "mode":
node.OnMonitoringModeChanged((_, _, _, _, _, _) => default);
break;
case "added":
node.OnNodeAdded((_, _) => { });
break;
case "removed":
node.OnNodeRemoved((_, _) => { });
break;
case "refresh":
node.OnConditionRefresh((_, _, _) => { });
break;
case "event":
node.OnEvent((_, _, _) => { });
break;
case "read":
node.OnRead(ReadOrWrite);
break;
case "write":
node.OnWrite(ReadOrWrite);
break;
default:
node.OnCall((_, _, _, _, _, _) => new ValueTask<ServiceResult>(ServiceResult.Good));
break;
}
}
/// <summary>
/// Supplies a successful value callback for read and write handler-registration checks.
/// </summary>
private static ServiceResult ReadOrWrite(ISystemContext context, NodeState node, ref Variant value)
{
return ServiceResult.Good;
}
/// <summary>
/// Builds a small indexed object graph with variable and method nodes for handler-registration tests.
/// </summary>
private sealed class HandlerHarness
{
/// <summary>
/// Creates the namespace, node identifier factory, and root graph used by the fluent builder.
/// </summary>
public HandlerHarness()
{
var namespaces = new NamespaceTable();
namespaces.Append("urn:fluent-handler-regression");
var factory = new DefaultNodeIdFactory(NodeIdAssignmentMode.String, 1);
Context = new SystemContext(NUnitTelemetryContext.Create())
{
NamespaceUris = namespaces,
NodeIdFactory = factory,
TypeTable = new TypeTable(namespaces),
ServerUris = new StringTable()
};
Root = new BaseObjectState(null)
{
NodeId = new NodeId("Root", 1),
BrowseName = new QualifiedName("Root", 1)
};
Variable = new BaseDataVariableState(Root)
{
NodeId = new NodeId("Root.Variable", 1),
BrowseName = new QualifiedName("Variable", 1),
DataType = DataTypeIds.Int32
};
Method = new MethodState(Root)
{
NodeId = new NodeId("Root.Method", 1),
BrowseName = new QualifiedName("Method", 1)
};
Root.AddChild(Variable);
Root.AddChild(Method);
var nodes = new Dictionary<NodeId, NodeState>
{
[Root.NodeId] = Root,
[Variable.NodeId] = Variable,
[Method.NodeId] = Method
};
Builder = new NodeManagerBuilder(Context, FluentTestNodeManager.Create(factory), 1,
_ => Root, id => (nodes.TryGetValue(id, out NodeState? node) ? node : null)!, _ => []);
}
/// <summary>
/// Gets the namespace and type context supplied to dispatched handlers.
/// </summary>
public SystemContext Context { get; }
/// <summary>
/// Gets the parent object used to author ad hoc children.
/// </summary>
public BaseObjectState Root { get; }
/// <summary>
/// Gets the variable used to observe read, write, event, and monitored-item callbacks.
/// </summary>
public BaseDataVariableState Variable { get; }
/// <summary>
/// Gets the method used to observe registration of call callbacks.
/// </summary>
public MethodState Method { get; }
/// <summary>
/// Gets the graph builder whose sealing and dispatcher behavior are under test.
/// </summary>
public NodeManagerBuilder Builder { get; }
}
/// <summary>
/// Defines the continuation payload expected from the dispatched history-read handler.
/// </summary>
private static readonly byte[] s_continuation = [3, 7];
/// <summary>
/// Identifies handler registries that must remain empty after rejected post-seal registrations.
/// </summary>
private static readonly string[] s_handlerMaps =
[
"m_historyRead", "m_historyUpdate", "m_monitoredItemCreated", "m_monitoredItemCreating",
"m_monitoredItemModified", "m_monitoredItemDeleted", "m_monitoringModeChanged", "m_nodeAdded", "m_nodeRemoved"
];
}
}