Files
UA-.NETStandard/tests/Opc.Ua.Redundancy.Server.Tests/Redundancy/RequestServerStateChangeStartupTaskTests.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

414 lines
19 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/
* ======================================================================*/
// CA2007: tests run without a SynchronizationContext; ConfigureAwait(false)
// adds noise without a behavioural benefit. Disabled file-level for the suite.
#pragma warning disable CA2007
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using NUnit.Framework;
using Opc.Ua.Redundancy.Server;
using Opc.Ua.Tests;
namespace Opc.Ua.Server.Tests.Redundancy
{
/// <summary>
/// Unit tests for <see cref="RequestServerStateChangeStartupTask"/>.
/// </summary>
[TestFixture]
[Category("Distributed")]
[Parallelizable(ParallelScope.All)]
public sealed class RequestServerStateChangeStartupTaskTests
{
[Test]
public void ConstructorThrowsOnNullOptions()
{
Assert.That(
() => new RequestServerStateChangeStartupTask((RequestServerStateChangeOptions)null!),
Throws.ArgumentNullException);
}
[Test]
public void OnServerStartedThrowsOnNullServer()
{
var task = new RequestServerStateChangeStartupTask();
Assert.That(async () => await task.OnServerStartedAsync(null!).ConfigureAwait(false), Throws.ArgumentNullException);
}
[Test]
public async Task RequestShutdownPublishesMaintenanceAndEstimatedReturnTimeAsync()
{
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
Mock<IServiceLevelController> controller = new();
RequestServerStateChangeStartupTask task = CreateTask(controller.Object);
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
RequestServerStateChangeMethodState method =
loaded.Manager.FindPredefinedNode<RequestServerStateChangeMethodState>(
MethodIds.Server_RequestServerStateChange);
DateTimeUtc estimatedReturnTime = DateTimeUtc.Now;
ServiceResult result = method.OnCall!(
loaded.Server.Object.DefaultSystemContext,
method,
ObjectIds.Server,
ServerState.Shutdown,
estimatedReturnTime,
10,
new LocalizedText("maintenance"),
restart: false);
Assert.That(result, Is.EqualTo(ServiceResult.Good));
Assert.That(method.NodeId, Is.EqualTo(MethodIds.Server_RequestServerStateChange));
controller.Verify(c => c.SetServiceLevel(ServiceLevels.Maintenance), Times.Once);
PropertyState<DateTimeUtc> estimatedReturnTimeNode =
loaded.Manager.FindPredefinedNode<PropertyState<DateTimeUtc>>(
VariableIds.Server_EstimatedReturnTime);
Assert.That(estimatedReturnTimeNode.Value, Is.EqualTo(estimatedReturnTime));
}
[Test]
public async Task RequestFailedPublishesNoDataWhenNoControllerIsConfiguredAsync()
{
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
RequestServerStateChangeStartupTask task = CreateTask();
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
RequestServerStateChangeMethodState method =
loaded.Manager.FindPredefinedNode<RequestServerStateChangeMethodState>(
MethodIds.Server_RequestServerStateChange);
ServiceResult result = method.OnCall!(
loaded.Server.Object.DefaultSystemContext,
method,
ObjectIds.Server,
ServerState.Failed,
DateTimeUtc.Now,
0,
new LocalizedText("failed"),
restart: false);
Assert.That(result, Is.EqualTo(ServiceResult.Good));
PropertyState<byte> serviceLevel =
loaded.Manager.FindPredefinedNode<PropertyState<byte>>(VariableIds.Server_ServiceLevel);
Assert.That(serviceLevel.Value, Is.EqualTo(ServiceLevels.NoData));
}
[Test]
public async Task RequestReturnsAccessDeniedWhenAdminValidationFailsAsync()
{
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
var options = new RequestServerStateChangeOptions
{
AdminAccessValidator = _ => throw new ServiceResultException(StatusCodes.BadUserAccessDenied)
};
var task = new RequestServerStateChangeStartupTask(options);
PropertyState<byte> serviceLevel =
loaded.Manager.FindPredefinedNode<PropertyState<byte>>(VariableIds.Server_ServiceLevel);
serviceLevel.Value = ServiceLevels.Maximum;
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
RequestServerStateChangeMethodState method =
loaded.Manager.FindPredefinedNode<RequestServerStateChangeMethodState>(
MethodIds.Server_RequestServerStateChange);
ServiceResult result = method.OnCall!(
loaded.Server.Object.DefaultSystemContext,
method,
ObjectIds.Server,
ServerState.Shutdown,
DateTimeUtc.Now,
0,
LocalizedText.Null,
restart: false);
Assert.That(result.StatusCode.Code, Is.EqualTo(StatusCodes.BadUserAccessDenied));
Assert.That(serviceLevel.Value, Is.EqualTo(ServiceLevels.Maximum));
}
[Test]
public async Task RequestUsesConfigurationNodeManagerWhenAdminValidatorIsNotConfiguredAsync()
{
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
RequestServerStateChangeStartupTask task = new(new RequestServerStateChangeOptions());
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
RequestServerStateChangeMethodState method =
loaded.Manager.FindPredefinedNode<RequestServerStateChangeMethodState>(
MethodIds.Server_RequestServerStateChange);
ServiceResult result = method.OnCall!(
loaded.Server.Object.DefaultSystemContext,
method,
ObjectIds.Server,
ServerState.Shutdown,
DateTimeUtc.Now,
0,
LocalizedText.Null,
restart: false);
Assert.That(result, Is.EqualTo(ServiceResult.Good));
loaded.ConfigurationNodeManager.Verify(
manager => manager.HasApplicationSecureAdminAccess(It.IsAny<ISystemContext>()),
Times.Once);
}
[Test]
public async Task RequestSuspendedPublishesMaintenanceAsync()
{
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
RequestServerStateChangeStartupTask task = CreateTask();
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
RequestServerStateChangeMethodState method =
loaded.Manager.FindPredefinedNode<RequestServerStateChangeMethodState>(
MethodIds.Server_RequestServerStateChange);
ServiceResult result = method.OnCall!(
loaded.Server.Object.DefaultSystemContext,
method,
ObjectIds.Server,
ServerState.Suspended,
DateTimeUtc.Now,
0,
LocalizedText.Null,
restart: false);
Assert.That(result, Is.EqualTo(ServiceResult.Good));
PropertyState<byte> serviceLevel =
loaded.Manager.FindPredefinedNode<PropertyState<byte>>(VariableIds.Server_ServiceLevel);
Assert.That(serviceLevel.Value, Is.EqualTo(ServiceLevels.Maintenance));
}
[Test]
public async Task RequestTestPublishesNoDataAsync()
{
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
RequestServerStateChangeStartupTask task = CreateTask();
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
RequestServerStateChangeMethodState method =
loaded.Manager.FindPredefinedNode<RequestServerStateChangeMethodState>(
MethodIds.Server_RequestServerStateChange);
ServiceResult result = method.OnCall!(
loaded.Server.Object.DefaultSystemContext,
method,
ObjectIds.Server,
ServerState.Test,
DateTimeUtc.Now,
0,
LocalizedText.Null,
restart: false);
Assert.That(result, Is.EqualTo(ServiceResult.Good));
PropertyState<byte> serviceLevel =
loaded.Manager.FindPredefinedNode<PropertyState<byte>>(VariableIds.Server_ServiceLevel);
Assert.That(serviceLevel.Value, Is.EqualTo(ServiceLevels.NoData));
}
[Test]
public async Task RequestUsesCustomServiceLevelSelectorAsync()
{
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
var options = new RequestServerStateChangeOptions
{
AdminAccessValidator = _ => { },
ServiceLevelSelector = state => state == ServerState.Running ? (byte)200 : (byte)100
};
var task = new RequestServerStateChangeStartupTask(options);
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
RequestServerStateChangeMethodState method =
loaded.Manager.FindPredefinedNode<RequestServerStateChangeMethodState>(
MethodIds.Server_RequestServerStateChange);
ServiceResult result = method.OnCall!(
loaded.Server.Object.DefaultSystemContext,
method,
ObjectIds.Server,
ServerState.Running,
DateTimeUtc.Now,
0,
LocalizedText.Null,
restart: false);
Assert.That(result, Is.EqualTo(ServiceResult.Good));
PropertyState<byte> serviceLevel =
loaded.Manager.FindPredefinedNode<PropertyState<byte>>(VariableIds.Server_ServiceLevel);
Assert.That(serviceLevel.Value, Is.EqualTo(200));
}
[Test]
public async Task RequestUpdatesServerStatusFieldsAsync()
{
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
RequestServerStateChangeStartupTask task = CreateTask();
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
RequestServerStateChangeMethodState method =
loaded.Manager.FindPredefinedNode<RequestServerStateChangeMethodState>(
MethodIds.Server_RequestServerStateChange);
var estimatedReturnTime = new DateTimeUtc(638000000000000000);
var reason = new LocalizedText("Planned maintenance");
ServiceResult result = method.OnCall!(
loaded.Server.Object.DefaultSystemContext,
method,
ObjectIds.Server,
ServerState.Shutdown,
estimatedReturnTime,
300,
reason,
restart: false);
Assert.That(result, Is.EqualTo(ServiceResult.Good));
ServerStatusState serverStatus = loaded.Manager.FindPredefinedNode<ServerStatusState>(
VariableIds.Server_ServerStatus);
Assert.That(serverStatus.State!.Value, Is.EqualTo(ServerState.Shutdown));
Assert.That(serverStatus.SecondsTillShutdown!.Value, Is.EqualTo(300));
Assert.That(serverStatus.ShutdownReason!.Value.Text, Is.EqualTo("Planned maintenance"));
}
[Test]
public async Task RequestAcceptsRestartFlagAsync()
{
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
RequestServerStateChangeStartupTask task = CreateTask();
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
RequestServerStateChangeMethodState method =
loaded.Manager.FindPredefinedNode<RequestServerStateChangeMethodState>(
MethodIds.Server_RequestServerStateChange);
ServiceResult result = method.OnCall!(
loaded.Server.Object.DefaultSystemContext,
method,
ObjectIds.Server,
ServerState.Shutdown,
DateTimeUtc.Now,
10,
LocalizedText.Null,
restart: true);
Assert.That(result, Is.EqualTo(ServiceResult.Good));
}
private static RequestServerStateChangeStartupTask CreateTask(
IServiceLevelController? controller = null)
{
return new RequestServerStateChangeStartupTask(
new RequestServerStateChangeOptions
{
AdminAccessValidator = _ => { }
},
controller);
}
private static async Task<LoadedDiagnosticsServer> CreateLoadedServerAsync()
{
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
var namespaceUris = new NamespaceTable();
namespaceUris.Append("http://opcfoundation.org/UA/");
var serverUris = new StringTable();
var typeTree = new TypeTable(namespaceUris);
var messageContext = new ServiceMessageContext(telemetry, EncodeableFactory.Create())
{
NamespaceUris = namespaceUris,
ServerUris = serverUris
};
var server = new Mock<IServerInternal>();
var coreNodeManager = new Mock<ICoreNodeManager>();
coreNodeManager.Setup(m => m.ImportNodesAsync(
It.IsAny<ISystemContext>(),
It.IsAny<IList<NodeState>>(),
It.IsAny<bool>(),
It.IsAny<CancellationToken>()))
.Returns(new ValueTask());
var masterNodeManager = new Mock<IMasterNodeManager>();
masterNodeManager.Setup(m => m.RemoveReferencesAsync(
It.IsAny<List<LocalReference>>(),
It.IsAny<CancellationToken>()))
.Returns(new ValueTask());
var configurationNodeManager = new Mock<IConfigurationNodeManager>();
server.Setup(s => s.Telemetry).Returns(telemetry);
server.Setup(s => s.NamespaceUris).Returns(namespaceUris);
server.Setup(s => s.ServerUris).Returns(serverUris);
server.Setup(s => s.TypeTree).Returns(typeTree);
server.Setup(s => s.MessageContext).Returns(messageContext);
server.Setup(s => s.CoreNodeManager).Returns(coreNodeManager.Object);
server.Setup(s => s.NodeManager).Returns(masterNodeManager.Object);
server.Setup(s => s.Factory).Returns(EncodeableFactory.Create());
server.Setup(s => s.ConfigurationNodeManager).Returns(configurationNodeManager.Object);
var context = new ServerSystemContext(server.Object);
server.Setup(s => s.DefaultSystemContext).Returns(context);
var configuration = new ApplicationConfiguration
{
ServerConfiguration = new ServerConfiguration()
};
var manager = new DiagnosticsNodeManager(server.Object, configuration, NullLogger.Instance);
await manager.CreateAddressSpaceAsync(new Dictionary<NodeId, IList<IReference>>()).ConfigureAwait(false);
ServerObjectState serverObject = manager.FindPredefinedNode<ServerObjectState>(ObjectIds.Server);
server.Setup(s => s.ServerObject).Returns(serverObject);
server.Setup(s => s.DiagnosticsNodeManager).Returns(manager);
server.Setup(s => s.FindNodeManagers<IConfigurationNodeManager>())
.Returns([configurationNodeManager.Object]);
server.Setup(s => s.FindPredefinedNode<RequestServerStateChangeMethodState>(
It.IsAny<NodeId>()))
.Returns((NodeId nodeId) => manager.FindPredefinedNode<RequestServerStateChangeMethodState>(nodeId));
return new LoadedDiagnosticsServer(server, manager, configurationNodeManager);
}
private sealed class LoadedDiagnosticsServer : IDisposable
{
public LoadedDiagnosticsServer(
Mock<IServerInternal> server,
DiagnosticsNodeManager manager,
Mock<IConfigurationNodeManager> configurationNodeManager)
{
Server = server;
Manager = manager;
ConfigurationNodeManager = configurationNodeManager;
}
public Mock<IServerInternal> Server { get; }
public DiagnosticsNodeManager Manager { get; }
public Mock<IConfigurationNodeManager> ConfigurationNodeManager { get; }
public void Dispose()
{
Manager.Dispose();
}
}
}
}