Files
UA-.NETStandard/tests/Opc.Ua.Client.Tests/Session/SessionReconnectHandlerTests.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

521 lines
21 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.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Opc.Ua.Tests;
namespace Opc.Ua.Client.Tests
{
/// <summary>
/// Unit tests for SessionReconnectHandler, focusing on endpoint fallback behavior
/// when the server's endpoint configuration changes.
/// </summary>
[TestFixture]
[Category("Client")]
[Category("SessionReconnectHandler")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
public sealed class SessionReconnectHandlerTests
{
private ITelemetryContext m_telemetry;
[SetUp]
public void SetUp()
{
m_telemetry = NUnitTelemetryContext.Create();
}
/// <summary>
/// Verifies that the reconnect handler calls UpdateEndpointFromServerAsync
/// when m_updateFromServer is set and session recreation succeeds.
/// </summary>
[Test]
public async Task DoReconnectAsync_WhenUpdateFromServerIsSet_CallsUpdateEndpointFromServerAsync()
{
// Arrange
int updateCallCount = 0;
var mockNewSession = new Mock<ISession>();
var mockFactory = new Mock<ISessionFactory>();
ConfiguredEndpoint configuredEndpoint = CreateConfiguredEndpoint(
MessageSecurityMode.SignAndEncrypt,
SecurityPolicies.Basic256Sha256);
Mock<ISession> mockSession = CreateMockSession(configuredEndpoint, mockFactory);
mockFactory.Setup(f => f.RecreateAsync(mockSession.Object, It.IsAny<CancellationToken>()))
.ReturnsAsync(mockNewSession.Object);
using var handler = new TestableSessionReconnectHandler(
m_telemetry,
(endpoint, connection) =>
{
updateCallCount++;
return Task.CompletedTask;
});
SetSessionHandlerField(handler, "m_reconnectFailed", true);
SetSessionHandlerField(handler, "m_updateFromServer", true);
SetHandlerSession(handler, mockSession.Object);
// Act
bool result = await InvokeDoReconnectAsync(handler).ConfigureAwait(false);
// Assert
Assert.That(result, Is.True);
Assert.That(updateCallCount, Is.EqualTo(1));
Assert.That(handler.Session, Is.SameAs(mockNewSession.Object));
}
/// <summary>
/// Verifies that DoReconnectAsync does not call UpdateEndpointFromServerAsync
/// when m_updateFromServer is false.
/// </summary>
[Test]
public async Task DoReconnectAsync_WhenUpdateFromServerIsFalse_SkipsEndpointUpdate()
{
// Arrange
int updateCallCount = 0;
var mockNewSession = new Mock<ISession>();
var mockFactory = new Mock<ISessionFactory>();
ConfiguredEndpoint configuredEndpoint = CreateConfiguredEndpoint(
MessageSecurityMode.None,
SecurityPolicies.None);
Mock<ISession> mockSession = CreateMockSession(configuredEndpoint, mockFactory);
mockFactory.Setup(f => f.RecreateAsync(mockSession.Object, It.IsAny<CancellationToken>()))
.ReturnsAsync(mockNewSession.Object);
using var handler = new TestableSessionReconnectHandler(
m_telemetry,
(endpoint, connection) =>
{
updateCallCount++;
return Task.CompletedTask;
});
SetSessionHandlerField(handler, "m_reconnectFailed", true);
SetSessionHandlerField(handler, "m_updateFromServer", false);
SetHandlerSession(handler, mockSession.Object);
// Act
bool result = await InvokeDoReconnectAsync(handler).ConfigureAwait(false);
// Assert
Assert.That(result, Is.True);
Assert.That(updateCallCount, Is.Zero);
}
/// <summary>
/// Verifies that when UpdateEndpointFromServerAsync fails with a ServiceResultException,
/// the session recreation is skipped, m_updateFromServer is set for the next attempt,
/// and false is returned.
/// </summary>
[Test]
public async Task DoReconnectAsync_WhenUpdateEndpointFails_SetsUpdateFromServerAndReturnsFalse()
{
// Arrange
var mockFactory = new Mock<ISessionFactory>();
ConfiguredEndpoint configuredEndpoint = CreateConfiguredEndpoint(
MessageSecurityMode.SignAndEncrypt,
SecurityPolicies.Aes256_Sha256_RsaPss);
Mock<ISession> mockSession = CreateMockSession(configuredEndpoint, mockFactory);
using var handler = new TestableSessionReconnectHandler(
m_telemetry,
(endpoint, connection) =>
throw new ServiceResultException(StatusCodes.BadNoCommunication));
SetSessionHandlerField(handler, "m_reconnectFailed", true);
SetSessionHandlerField(handler, "m_updateFromServer", true);
SetHandlerSession(handler, mockSession.Object);
// Act
bool result = await InvokeDoReconnectAsync(handler).ConfigureAwait(false);
// Assert
Assert.That(result, Is.False);
bool updateFromServer = GetSessionHandlerField<bool>(handler, "m_updateFromServer");
Assert.That(updateFromServer, Is.True);
}
/// <summary>
/// Verifies that UpdateEndpointFromServerAsync is a protected virtual method
/// that can be overridden to customize the endpoint update behavior.
/// </summary>
[Test]
public void UpdateEndpointFromServerAsync_IsProtectedVirtual()
{
MethodInfo method = typeof(SessionReconnectHandler).GetMethod(
"UpdateEndpointFromServerAsync",
BindingFlags.NonPublic | BindingFlags.Instance)!;
Assert.That(method, Is.Not.Null);
Assert.That(method.IsVirtual, Is.True);
Assert.That(method.IsFamily, Is.True); // protected
}
/// <summary>
/// Verifies that UpdateEndpointFromServerAsync accepts a ConfiguredEndpoint
/// and a nullable ITransportWaitingConnection parameter (for reverse connect support).
/// </summary>
[Test]
public void UpdateEndpointFromServerAsync_HasCorrectSignature()
{
MethodInfo method = typeof(SessionReconnectHandler).GetMethod(
"UpdateEndpointFromServerAsync",
BindingFlags.NonPublic | BindingFlags.Instance)!;
Assert.That(method, Is.Not.Null);
ParameterInfo[] parameters = method.GetParameters();
Assert.That(parameters, Has.Length.EqualTo(2));
Assert.That(parameters[0].ParameterType, Is.EqualTo(typeof(ConfiguredEndpoint)));
Assert.That(parameters[1].ParameterType, Is.EqualTo(typeof(ITransportWaitingConnection)));
}
/// <summary>
/// Verifies that <see cref="SessionReconnectHandler.BeginReconnect(ISession,int,EventHandler)"/>
/// throws <see cref="NotSupportedException"/> when given an
/// <see cref="ISession"/> that is not a <see cref="Session"/>
/// (or a derived type). The handler drives
/// <see cref="ISessionFactory.RecreateAsync(ISession,CancellationToken)"/>
/// and the underlying transport channel directly, which only
/// makes sense for the legacy <see cref="Session"/> class.
/// Facade implementations (e.g. <see cref="ManagedSession"/>)
/// run their own reconnect state machine and must not be
/// passed in.
/// </summary>
[Test]
public void BeginReconnect_WithNonSessionImplementation_ThrowsNotSupportedException()
{
var mockSession = new Mock<ISession>();
mockSession.SetupGet(s => s.SessionId).Returns(NodeId.Null);
using var handler = new SessionReconnectHandler(m_telemetry);
Assert.That(
() => handler.BeginReconnect(
mockSession.Object,
1000,
(_, _) => { }),
Throws.TypeOf<NotSupportedException>());
}
/// <summary>
/// Verifies that the reverse-connect overload also rejects
/// non-<see cref="Session"/> implementations of
/// <see cref="ISession"/> with <see cref="NotSupportedException"/>.
/// </summary>
[Test]
public void BeginReconnect_ReverseConnect_WithNonSessionImplementation_ThrowsNotSupportedException()
{
var mockSession = new Mock<ISession>();
mockSession.SetupGet(s => s.SessionId).Returns(NodeId.Null);
using var handler = new SessionReconnectHandler(m_telemetry);
Assert.That(
() => handler.BeginReconnect(
mockSession.Object,
null,
1000,
(_, _) => { }),
Throws.TypeOf<NotSupportedException>());
}
/// <summary>
/// Verifies that passing <see langword="null"/> as the session
/// remains supported as a cancellation signal and does not
/// trigger the type check.
/// </summary>
[Test]
public void BeginReconnect_WithNullSession_DoesNotThrowAndStaysReady()
{
using var handler = new SessionReconnectHandler(m_telemetry);
SessionReconnectHandler.ReconnectState state = handler.BeginReconnect(
null!,
1000,
(_, _) => { });
Assert.That(state, Is.EqualTo(SessionReconnectHandler.ReconnectState.Ready));
}
/// <summary>
/// Verifies that when the endpoint update succeeds after a simulated
/// BadSecurityPolicyRejected fallback (modeled via TestableSessionReconnectHandler),
/// the session is recreated and the reconnect succeeds.
/// This simulates a server restarting with a different endpoint configuration where
/// the fallback selects the best available endpoint.
/// </summary>
[Test]
public async Task DoReconnectAsync_WhenEndpointUpdateSucceedsAfterFallback_SessionIsRecreated()
{
// Arrange
var mockNewSession = new Mock<ISession>();
var mockFactory = new Mock<ISessionFactory>();
ConfiguredEndpoint configuredEndpoint = CreateConfiguredEndpoint(
MessageSecurityMode.SignAndEncrypt,
SecurityPolicies.Aes256_Sha256_RsaPss);
Mock<ISession> mockSession = CreateMockSession(configuredEndpoint, mockFactory);
mockFactory.Setup(f => f.RecreateAsync(mockSession.Object, It.IsAny<CancellationToken>()))
.ReturnsAsync(mockNewSession.Object);
// Simulate: the handler successfully updates the endpoint
// (the base class would have fallen back to best available endpoint here)
using var handler = new TestableSessionReconnectHandler(
m_telemetry,
(endpoint, connection) => Task.CompletedTask);
SetSessionHandlerField(handler, "m_reconnectFailed", true);
SetSessionHandlerField(handler, "m_updateFromServer", true);
SetHandlerSession(handler, mockSession.Object);
// Act
bool result = await InvokeDoReconnectAsync(handler).ConfigureAwait(false);
// Assert
Assert.That(result, Is.True);
Assert.That(handler.Session, Is.SameAs(mockNewSession.Object));
}
/// <summary>
/// The fallback must never downgrade a secured endpoint, even if the
/// (unauthenticated) discovery reply advertises a weaker endpoint with a
/// high SecurityLevel.
/// </summary>
[Test]
public void SelectFallbackEndpoint_OnlyWeakerEndpoints_ReturnsNull()
{
var original = new EndpointDescription
{
SecurityMode = MessageSecurityMode.SignAndEncrypt,
SecurityPolicyUri = SecurityPolicies.Basic256Sha256
};
ArrayOf<EndpointDescription> discovered =
[
new EndpointDescription
{
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None,
SecurityLevel = 255
},
new EndpointDescription
{
SecurityMode = MessageSecurityMode.Sign,
SecurityPolicyUri = SecurityPolicies.Aes256_Sha256_RsaPss,
SecurityLevel = 255
},
new EndpointDescription
{
SecurityMode = MessageSecurityMode.SignAndEncrypt,
SecurityPolicyUri = SecurityPolicies.Basic128Rsa15,
SecurityLevel = 255
}
];
EndpointDescription fallback = SessionReconnectHandler.SelectFallbackEndpoint(
original,
discovered,
m_telemetry.CreateLogger<SessionReconnectHandlerTests>())!;
Assert.That(fallback, Is.Null);
}
/// <summary>
/// The fallback picks the strongest endpoint by the locally computed
/// security level, ignoring the server advertised SecurityLevel.
/// </summary>
[Test]
public void SelectFallbackEndpoint_PicksStrongestByLocalSecurityLevel()
{
var original = new EndpointDescription
{
SecurityMode = MessageSecurityMode.SignAndEncrypt,
SecurityPolicyUri = SecurityPolicies.Basic256Sha256
};
var weakerAdvertisedHigh = new EndpointDescription
{
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None,
SecurityLevel = 255
};
var aes128 = new EndpointDescription
{
SecurityMode = MessageSecurityMode.SignAndEncrypt,
SecurityPolicyUri = SecurityPolicies.Aes128_Sha256_RsaOaep,
SecurityLevel = 200
};
var aes256 = new EndpointDescription
{
SecurityMode = MessageSecurityMode.SignAndEncrypt,
SecurityPolicyUri = SecurityPolicies.Aes256_Sha256_RsaPss,
SecurityLevel = 1
};
EndpointDescription fallback = SessionReconnectHandler.SelectFallbackEndpoint(
original,
[weakerAdvertisedHigh, aes128, aes256],
m_telemetry.CreateLogger<SessionReconnectHandlerTests>())!;
Assert.That(fallback, Is.SameAs(aes256));
}
/// <summary>
/// Even an unsecured original endpoint only falls back to a secured one.
/// </summary>
[Test]
public void SelectFallbackEndpoint_NoneOriginal_NeverSelectsNone()
{
var original = new EndpointDescription
{
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None
};
var none = new EndpointDescription
{
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None
};
var signed = new EndpointDescription
{
SecurityMode = MessageSecurityMode.Sign,
SecurityPolicyUri = SecurityPolicies.Basic256Sha256
};
Assert.That(
SessionReconnectHandler.SelectFallbackEndpoint(
original,
[none],
m_telemetry.CreateLogger<SessionReconnectHandlerTests>()),
Is.Null);
Assert.That(
SessionReconnectHandler.SelectFallbackEndpoint(
original,
[none, signed],
m_telemetry.CreateLogger<SessionReconnectHandlerTests>()),
Is.SameAs(signed));
}
private static ConfiguredEndpoint CreateConfiguredEndpoint(
MessageSecurityMode securityMode,
string securityPolicyUri)
{
return new ConfiguredEndpoint(null!, new EndpointDescription
{
EndpointUrl = "opc.tcp://localhost:4840",
SecurityMode = securityMode,
SecurityPolicyUri = securityPolicyUri
});
}
private static Mock<ISession> CreateMockSession(
ConfiguredEndpoint configuredEndpoint,
Mock<ISessionFactory> mockFactory)
{
var mockSession = new Mock<ISession>();
mockSession.SetupGet(s => s.ConfiguredEndpoint).Returns(configuredEndpoint);
mockSession.SetupGet(s => s.SessionFactory).Returns(mockFactory.Object);
mockSession.SetupGet(s => s.SessionId).Returns(NodeId.Null);
return mockSession;
}
private static Task<bool> InvokeDoReconnectAsync(SessionReconnectHandler handler)
{
MethodInfo method = typeof(SessionReconnectHandler)
.GetMethod("DoReconnectAsync", BindingFlags.NonPublic | BindingFlags.Instance)
?? throw new InvalidOperationException("DoReconnectAsync method not found");
return (Task<bool>)method.Invoke(handler, null)!;
}
private static void SetSessionHandlerField(
SessionReconnectHandler handler,
string fieldName,
object value)
{
FieldInfo field = typeof(SessionReconnectHandler)
.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance)
?? throw new InvalidOperationException($"Field {fieldName} not found");
field.SetValue(handler, value);
}
private static void SetHandlerSession(SessionReconnectHandler handler, ISession session)
{
PropertyInfo prop = typeof(SessionReconnectHandler)
.GetProperty("Session", BindingFlags.Public | BindingFlags.Instance)
?? throw new InvalidOperationException("Session property not found");
MethodInfo setter = prop.GetSetMethod(nonPublic: true)
?? throw new InvalidOperationException("Session property setter not found");
setter.Invoke(handler, [session]);
}
private static T GetSessionHandlerField<T>(SessionReconnectHandler handler, string fieldName)
{
FieldInfo field = typeof(SessionReconnectHandler)
.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance)
?? throw new InvalidOperationException($"Field {fieldName} not found");
return (T)field.GetValue(handler)!;
}
/// <summary>
/// A testable subclass of SessionReconnectHandler that replaces the
/// UpdateEndpointFromServerAsync with a user-supplied delegate, enabling
/// unit tests to control the behavior without requiring network access.
/// </summary>
private sealed class TestableSessionReconnectHandler : SessionReconnectHandler
{
private readonly Func<ConfiguredEndpoint, ITransportWaitingConnection, Task> _updateDelegate;
public TestableSessionReconnectHandler(
ITelemetryContext telemetry,
Func<ConfiguredEndpoint, ITransportWaitingConnection, Task> updateDelegate)
: base(telemetry)
{
_updateDelegate = updateDelegate;
}
protected override Task UpdateEndpointFromServerAsync(
ConfiguredEndpoint endpoint,
ITransportWaitingConnection? connection = null)
{
return _updateDelegate(endpoint, connection!);
}
}
}
}