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

495 lines
20 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;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using NUnit.Framework;
using Opc.Ua.Bindings;
using Opc.Ua.Client.Alarms;
using Opc.Ua.Client.AliasNames;
using Opc.Ua.Client.Discovery;
using Opc.Ua.Client.FileSystem;
using Opc.Ua.Client.Historian;
using Opc.Ua.Client.Roles;
using Opc.Ua.Client.WebApi;
using Opc.Ua.Identity;
using Opc.Ua.Tests;
namespace Opc.Ua.Client.Tests.ClientBuilder
{
[TestFixture]
[Category("Client")]
[Category("ClientBuilder")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
[Parallelizable]
public sealed class ClientDiFluentApiTests
{
[Test]
public void AddClientChainsAlarmsAndWebApiTransport()
{
var services = new ServiceCollection();
IOpcUaClientBuilder builder = services.AddOpcUa()
.AddClient(ConfigureValidClient)
.AddAlarms()
.AddWebApiTransportChannel(options => options.Encoding = WebApiEncoding.Verbose);
Assert.That(builder.Services, Is.SameAs(services));
using ServiceProvider sp = services.BuildServiceProvider();
Assert.That(sp.GetService<AlarmClientFactory>(), Is.Not.Null);
Assert.That(sp.GetService<WebApiClientOptions>(), Is.Not.Null);
Assert.That(sp.GetRequiredService<WebApiClientOptions>().Encoding, Is.EqualTo(WebApiEncoding.Verbose));
}
[Test]
public void ClientBuilderFeatureExtensionsRejectNullBuilders()
{
Assert.That(
() => ((IOpcUaClientBuilder)null!).AddAlarms(),
Throws.ArgumentNullException);
Assert.That(
() => ((IOpcUaClientBuilder)null!).AddWebApiTransportChannel(),
Throws.ArgumentNullException);
Assert.That(
() => ((IOpcUaClientBuilder)null!).AddHistorian(),
Throws.ArgumentNullException);
Assert.That(
() => ((IOpcUaClientBuilder)null!).AddRoleManagement(),
Throws.ArgumentNullException);
Assert.That(
() => ((IOpcUaClientBuilder)null!).AddFileTransfer(),
Throws.ArgumentNullException);
Assert.That(
() => ((IOpcUaClientBuilder)null!).AddAliasNames(),
Throws.ArgumentNullException);
}
[Test]
public void AddDiscoveryRegistersDiscoveryServiceAndRejectsNullBuilder()
{
var services = new ServiceCollection();
Assert.That(
() => ((IOpcUaBuilder)null!).AddDiscovery(),
Throws.ArgumentNullException);
services.AddOpcUa()
.AddClient(ConfigureValidClient)
.AddDiscovery();
using ServiceProvider sp = services.BuildServiceProvider();
Assert.That(sp.GetService<IManagedSessionFactory>(), Is.InstanceOf<DefaultManagedSessionFactory>());
Assert.That(sp.GetService<IOpcUaDiscoveryService>(), Is.InstanceOf<OpcUaDiscoveryService>());
Assert.That(sp.GetService<Func<CancellationToken, Task<Client.ManagedSession>>>(), Is.Not.Null);
}
[Test]
public void OptionsValidatorRejectsMissingConfiguration()
{
var services = new ServiceCollection();
services.AddOpcUa().AddClient(_ => { });
using ServiceProvider sp = services.BuildServiceProvider();
IOptions<OpcUaClientOptions> options = sp.GetRequiredService<IOptions<OpcUaClientOptions>>();
Assert.That(
() => _ = options.Value,
Throws.TypeOf<OptionsValidationException>()
.With.Property(nameof(OptionsValidationException.Failures))
.Some.Contains("OpcUaClientOptions.Configuration is required."));
}
[Test]
public void OptionsValidatorPassesWithConfigurationOnly()
{
var services = new ServiceCollection();
services.AddOpcUa().AddClient(options => options.Configuration = CreateConfig());
using ServiceProvider sp = services.BuildServiceProvider();
IOptions<OpcUaClientOptions> options = sp.GetRequiredService<IOptions<OpcUaClientOptions>>();
Assert.That(() => _ = options.Value, Throws.Nothing);
Assert.That(options.Value.Configuration, Is.Not.Null);
Assert.That(options.Value.Session.Endpoint, Is.Null);
}
[Test]
public async Task AddClientResolvesTransportRegistryWithoutExplicitTcpTransportAsync()
{
// Regression: AddOpcUa().AddClient(...) must resolve the transport
// binding registry (and the client channel manager) without an
// explicit AddOpcTcpTransport() call - AddOpcUa() seeds the
// mandatory opc.tcp transport.
var services = new ServiceCollection();
services.AddOpcUa().AddClient(options => options.Configuration = CreateConfig());
// ClientChannelManager is IAsyncDisposable-only, so dispose the
// provider asynchronously once it has been resolved.
await using ServiceProvider sp = services.BuildServiceProvider();
ITransportBindingRegistry registry = sp.GetRequiredService<ITransportBindingRegistry>();
Assert.That(registry, Is.InstanceOf<ITransportChannelBindings>());
Assert.That(registry.HasChannelFactory(Utils.UriSchemeOpcTcp), Is.True);
Assert.That(() => sp.GetRequiredService<IClientChannelManager>(), Throws.Nothing);
}
[Test]
public void OptionsValidatorPassesWithConfigurationAndEndpoint()
{
var services = new ServiceCollection();
services.AddOpcUa().AddClient(ConfigureValidClient);
using ServiceProvider sp = services.BuildServiceProvider();
IOptions<OpcUaClientOptions> options = sp.GetRequiredService<IOptions<OpcUaClientOptions>>();
Assert.That(options.Value.Configuration, Is.Not.Null);
Assert.That(options.Value.Session.Endpoint, Is.Not.Null);
}
[Test]
public void BuildServiceProviderAllowsClientWithoutStaticEndpoint()
{
var services = new ServiceCollection();
services.AddOpcUa()
.AddClient(options => options.Configuration = CreateConfig())
.AddDiscovery();
using ServiceProvider sp = services.BuildServiceProvider();
IOptions<OpcUaClientOptions> options = sp.GetRequiredService<IOptions<OpcUaClientOptions>>();
Assert.That(() => _ = options.Value, Throws.Nothing);
Assert.That(sp.GetService<IManagedSessionFactory>(), Is.Not.Null);
Assert.That(sp.GetService<IOpcUaDiscoveryService>(), Is.Not.Null);
}
[Test]
public void ManagedSessionOptionsLoadComplexTypesDefaultsToFalse()
{
Assert.That(new ManagedSessionOptions().LoadComplexTypes, Is.False);
}
[Test]
public void ManagedSessionBuilderWithLoadComplexTypesSetsOption()
{
ManagedSessionOptions options = new ManagedSessionBuilder(
CreateConfig(),
NUnitTelemetryContext.Create())
.UseEndpoint(CreateEndpoint())
.WithLoadComplexTypes()
.Build();
Assert.That(options.LoadComplexTypes, Is.True);
}
[Test]
public async Task ManagedSessionFactoryUsesSuppliedEndpointsAsync()
{
var connector = new RecordingManagedSessionConnector();
var services = new ServiceCollection();
services.AddSingleton<IManagedSessionConnector>(connector);
services.AddOpcUa().AddClient(options =>
{
options.Configuration = CreateConfig();
options.Session = new ManagedSessionOptions
{
SessionName = "ConfiguredSession",
LoadComplexTypes = true
};
});
using ServiceProvider sp = services.BuildServiceProvider();
IManagedSessionFactory factory = sp.GetRequiredService<IManagedSessionFactory>();
ConfiguredEndpoint firstEndpoint = CreateEndpoint("opc.tcp://first:4840");
ConfiguredEndpoint secondEndpoint = CreateEndpoint("opc.tcp://second:4840");
Client.ManagedSession first = await factory.ConnectAsync(firstEndpoint).ConfigureAwait(false);
Client.ManagedSession second = await factory.ConnectAsync(secondEndpoint).ConfigureAwait(false);
Assert.That(first, Is.Not.SameAs(second));
Assert.That(connector.Options, Has.Count.EqualTo(2));
Assert.That(connector.Options[0].Endpoint, Is.SameAs(firstEndpoint));
Assert.That(connector.Options[1].Endpoint, Is.SameAs(secondEndpoint));
Assert.That(connector.Options[0].SessionName, Is.EqualTo("ConfiguredSession"));
Assert.That(connector.Options[0].LoadComplexTypes, Is.True);
}
[Test]
public async Task ManagedSessionFactoryRuntimeEndpointDoesNotFailOptionsValidationAsync()
{
var services = new ServiceCollection();
services.AddOpcUa().AddClient(options => options.Configuration = CreateConfig());
// ClientChannelManager is IAsyncDisposable-only; once the connect
// attempt below instantiates it as a singleton the provider must be
// disposed asynchronously.
await using ServiceProvider sp = services.BuildServiceProvider();
IManagedSessionFactory factory = sp.GetRequiredService<IManagedSessionFactory>();
using var cts = new CancellationTokenSource();
cts.Cancel();
Exception? ex = Assert.CatchAsync(
async () => await factory
.ConnectAsync(CreateEndpoint("opc.tcp://127.0.0.1:9"), cts.Token)
.ConfigureAwait(false));
Assert.That(
IsEndpointRequiredOptionsException(ex),
Is.False);
}
[Test]
public void CachedSessionAccessorRequiresStaticEndpoint()
{
var services = new ServiceCollection();
services.AddOpcUa().AddClient(options => options.Configuration = CreateConfig());
using ServiceProvider sp = services.BuildServiceProvider();
Func<CancellationToken, Task<Client.ManagedSession>> factory = sp.GetRequiredService<Func<CancellationToken, Task<Client.ManagedSession>>>();
OptionsValidationException ex = Assert.ThrowsAsync<OptionsValidationException>(
() => factory(CancellationToken.None))!;
Assert.That(ex.Failures, Does.Contain("A session endpoint is required."));
}
[Test]
public void AddHistorianRegistersFactoryAndCreatesClient()
{
var services = new ServiceCollection();
services.AddOpcUa().AddHistorian();
using ServiceProvider sp = services.BuildServiceProvider();
ISession session = CreateSession();
HistoryClientFactory factory = sp.GetRequiredService<HistoryClientFactory>();
Assert.That(factory.Create(session).Session, Is.SameAs(session));
}
[Test]
public void AddRoleManagementRegistersFactoryAndCreatesClient()
{
var services = new ServiceCollection();
services.AddOpcUa().AddRoleManagement();
using ServiceProvider sp = services.BuildServiceProvider();
ISession session = CreateSession();
RoleManagementClientFactory factory = sp.GetRequiredService<RoleManagementClientFactory>();
Assert.That(factory.Create(session).Session, Is.SameAs(session));
}
[Test]
public void AddFileTransferRegistersFactoryAndCreatesClients()
{
var services = new ServiceCollection();
services.AddOpcUa().AddFileTransfer();
using ServiceProvider sp = services.BuildServiceProvider();
ISession session = CreateSession();
FileTransferClientFactory factory = sp.GetRequiredService<FileTransferClientFactory>();
Assert.That(factory.OpenServerFileSystem(session).Session, Is.SameAs(session));
Assert.That(
factory.CreateTemporaryFileTransfer(session, ObjectIds.FileSystem).Session,
Is.SameAs(session));
}
[Test]
public void AddAliasNamesRegistersFactoryAndCreatesClient()
{
var services = new ServiceCollection();
services.AddOpcUa().AddAliasNames();
using ServiceProvider sp = services.BuildServiceProvider();
ISession session = CreateSession();
AliasNameClientFactory factory = sp.GetRequiredService<AliasNameClientFactory>();
Assert.That(factory.OpenStandardAliases(session).Session, Is.SameAs(session));
}
[Test]
public void SubClientFactoriesRejectNullSessions()
{
var services = new ServiceCollection();
services.AddOpcUa()
.AddHistorian()
.AddRoleManagement()
.AddFileTransfer()
.AddAliasNames();
using ServiceProvider sp = services.BuildServiceProvider();
Assert.That(
() => sp.GetRequiredService<HistoryClientFactory>().Create(null!),
Throws.ArgumentNullException);
Assert.That(
() => sp.GetRequiredService<RoleManagementClientFactory>().Create(null!),
Throws.ArgumentNullException);
Assert.That(
() => sp.GetRequiredService<FileTransferClientFactory>().OpenServerFileSystem(null!),
Throws.ArgumentNullException);
Assert.That(
() => sp.GetRequiredService<AliasNameClientFactory>().OpenStandardAliases(null!),
Throws.ArgumentNullException);
}
private static void ConfigureValidClient(OpcUaClientOptions options)
{
options.Configuration = CreateConfig();
options.Session = new ManagedSessionOptions
{
Endpoint = CreateEndpoint()
};
}
private static ConfiguredEndpoint CreateEndpoint()
{
return CreateEndpoint("opc.tcp://localhost:4840");
}
private static ConfiguredEndpoint CreateEndpoint(string endpointUrl)
{
return new ConfiguredEndpoint(
null,
new EndpointDescription
{
EndpointUrl = endpointUrl
},
null);
}
private static ApplicationConfiguration CreateConfig()
{
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
return new ApplicationConfiguration(telemetry)
{
ApplicationUri = "urn:test:client-di",
ApplicationName = "client-di",
ClientConfiguration = new ClientConfiguration()
};
}
private static ISession CreateSession()
{
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
var session = new Mock<ISession>(MockBehavior.Loose);
session.SetupGet(s => s.MessageContext)
.Returns(ServiceMessageContext.Create(telemetry));
session.SetupGet(s => s.NamespaceUris)
.Returns(new NamespaceTable());
return session.Object;
}
private static bool IsEndpointRequiredOptionsException(Exception? ex)
{
return ex is OptionsValidationException optionsException &&
optionsException.Failures.Contains("A session endpoint is required.");
}
private static Client.ManagedSession CreateManagedSession(ConfiguredEndpoint endpoint)
{
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
ConstructorInfo constructor = typeof(Client.ManagedSession).GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null,
[
typeof(ApplicationConfiguration),
typeof(ConfiguredEndpoint),
typeof(ISessionFactory),
typeof(IReconnectPolicy),
typeof(IServerRedundancyHandler),
typeof(ILogger),
typeof(IUserIdentity),
typeof(IClientIdentityProvider),
typeof(TimeProvider),
typeof(ArrayOf<string>),
typeof(string),
typeof(uint),
typeof(bool),
typeof(bool),
typeof(bool),
typeof(bool),
typeof(NetworkRedundancyOptions),
typeof(ServerRedundancyOptions),
typeof(IClientChannelManager),
typeof(IClientConnectGate)
],
null)!;
return (Client.ManagedSession)constructor.Invoke(
[
CreateConfig(),
endpoint,
new DefaultSessionFactory(telemetry),
new ReconnectPolicy(new ReconnectPolicyOptions()),
null,
telemetry.CreateLogger<Client.ManagedSession>(),
null,
null,
TimeProvider.System,
default(ArrayOf<string>),
"TestSession",
60000u,
false,
false,
false,
false,
null,
null,
null,
null
]);
}
private sealed class RecordingManagedSessionConnector : IManagedSessionConnector
{
public List<ManagedSessionOptions> Options { get; } = [];
public Task<Client.ManagedSession> ConnectAsync(
IServiceProvider serviceProvider,
ManagedSessionOptions sessionOptions,
Action<ManagedSessionBuilder> configure,
CancellationToken ct)
{
Options.Add(sessionOptions);
return Task.FromResult(CreateManagedSession(sessionOptions.Endpoint!));
}
}
}
}