Files
UA-.NETStandard/tests/Opc.Ua.Client.Tests/ClientBuilder/OpcUaClientBuilderExtensionsCoverageTests.cs
Marc Schier 9bfc780e14 Update NuGet dependencies and migrate tests to NUnit 5 (#4840)
# Description

Update 55 NuGet dependencies to the latest stable releases available on
2026-10-19, preserving documented compatibility pins and
framework-specific version bands. Existing OpenUSD prereleases remain
unchanged because no newer releases are available.

Migrate existing tests to NUnit 5: await asynchronous assertions,
propagate async through helpers, handle nullable predicates, and replace
obsolete `Order` attributes with sequencing dependencies. Sequencing
dependencies use `AllowFailure = true`; filtering a dependent test also
runs prerequisites. Adjust fixture-level parallelism where NUnit
dependency scheduling requires it.

Keep Roslyn API/runtime pins intact; select newer Immutable/Metadata
runtime packages only for test and profiling hosts requiring them.
Update the approved SDK pin to 10.0.402 across local, CI, and container
builds. Document NUnit 5 conventions.
2026-10-19 15:23:29 +00:00

544 lines
23 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.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using NUnit.Framework;
using Opc.Ua.Client.Discovery;
using Opc.Ua.Identity;
using Opc.Ua.Tests;
namespace Opc.Ua.Client.Tests.ClientBuilder
{
/// <summary>
/// Patch-coverage tests for <see cref="OpcUaClientBuilderExtensions"/>.
/// Covers null guards, newly registered DI services, and the conditional
/// branches in <c>ApplyManagedSessionOptions</c> that are exercised via
/// <see cref="IManagedSessionFactory.ConnectAsync"/> with a pre-cancelled
/// token to avoid live network calls.
/// </summary>
[TestFixture]
[Category("Client")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
[Parallelizable]
public sealed class OpcUaClientBuilderExtensionsCoverageTests
{
[Test]
public void AddDiscoveryOnClientBuilderNullBuilderThrows()
{
Assert.That(
() => ((IOpcUaClientBuilder)null!).AddDiscovery(),
Throws.ArgumentNullException);
}
[Test]
public void AddSubscriptionsNullBuilderThrows()
{
Assert.That(
() => OpcUaClientBuilderExtensions.AddSubscriptions(null!),
Throws.ArgumentNullException);
}
[Test]
public void AddManagedClientPoolNullBuilderThrows()
{
Assert.That(
() => OpcUaClientBuilderExtensions.AddManagedClientPool(null!),
Throws.ArgumentNullException);
}
[Test]
public void AddReverseConnectClientNullBuilderThrows()
{
Assert.That(
() => OpcUaClientBuilderExtensions.AddReverseConnectClient(
null!,
_ => { },
new Uri("urn:test")),
Throws.ArgumentNullException);
}
[Test]
public void AddReverseConnectClientNullConfigureThrows()
{
var services = new ServiceCollection();
IOpcUaBuilder builder = services.AddOpcUa();
Assert.That(
() => builder.AddReverseConnectClient(null!, new Uri("urn:test")),
Throws.ArgumentNullException);
}
[Test]
public void AddReverseConnectClientNullUriThrows()
{
var services = new ServiceCollection();
IOpcUaBuilder builder = services.AddOpcUa();
Assert.That(
() => builder.AddReverseConnectClient(_ => { }, null!),
Throws.ArgumentNullException);
}
[Test]
public void AddDiscoveryAndConnectNullBuilderThrows()
{
Assert.That(
() => OpcUaClientBuilderExtensions.AddDiscoveryAndConnect(null!, _ => { }),
Throws.ArgumentNullException);
}
[Test]
public void AddDiscoveryAndConnectNullConfigureThrows()
{
var services = new ServiceCollection();
IOpcUaClientBuilder builder = services.AddOpcUa().AddClient(_ => { });
Assert.That(
() => builder.AddDiscoveryAndConnect(null!),
Throws.ArgumentNullException);
}
[Test]
public async Task SelectDiscoveredEndpointNoMatchThrowsAsync()
{
var services = new ServiceCollection();
services.AddOpcUa()
.AddClient(opts => opts.Configuration = CreateConfig())
.AddDiscoveryAndConnect(opts =>
{
opts.DiscoveryUrl = "opc.tcp://test:4840";
opts.SecurityMode = MessageSecurityMode.SignAndEncrypt;
opts.SecurityPolicyUri = SecurityPolicies.Basic256Sha256;
});
// Override discovery service: returns endpoints that do NOT match configured criteria.
services.AddSingleton<IOpcUaDiscoveryService>(new EmptyDiscoveryStub());
using ServiceProvider sp = services.BuildServiceProvider();
Func<CancellationToken, Task<Client.ManagedSession>> factory =
sp.GetRequiredService<Func<CancellationToken, Task<Client.ManagedSession>>>();
InvalidOperationException? ex = await Assert.ThrowsAsync<InvalidOperationException>(
() => factory(CancellationToken.None));
Assert.That(ex, Is.Not.Null);
Assert.That(ex!.Message, Does.Contain("No discovered endpoint matched"));
await Task.CompletedTask.ConfigureAwait(false);
}
[Test]
public void RegisterCoreServicesRegistersManagedSessionFactoryAndConnector()
{
var services = new ServiceCollection();
services.AddOpcUa().AddClient(opts => opts.Configuration = CreateConfig());
using ServiceProvider sp = services.BuildServiceProvider();
Assert.That(sp.GetService<IManagedSessionFactory>(),
Is.InstanceOf<DefaultManagedSessionFactory>());
Assert.That(sp.GetService<IManagedSessionConnector>(), Is.Not.Null);
}
[Test]
public async Task ApplyManagedSessionOptionsPreferredLocalesAsync()
{
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services => services.AddOpcUa().AddClient(opts =>
{
opts.Configuration = CreateConfig();
opts.Session = new ManagedSessionOptions
{
PreferredLocales = new List<string> { "en-US", "de-DE" }
};
})).ConfigureAwait(false);
Assert.That(captured.PreferredLocales, Has.Count.EqualTo(2));
Assert.That(captured.PreferredLocales[0], Is.EqualTo("en-US"));
Assert.That(captured.PreferredLocales[1], Is.EqualTo("de-DE"));
}
[Test]
public async Task ApplyManagedSessionOptionsSubscriptionEngineFactoryAsync()
{
ISubscriptionEngineFactory engineFactory = new DefaultSubscriptionEngineFactory();
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services => services.AddOpcUa().AddClient(opts =>
{
opts.Configuration = CreateConfig();
opts.Session = new ManagedSessionOptions
{
SubscriptionEngineFactory = engineFactory
};
})).ConfigureAwait(false);
Assert.That(captured.SubscriptionEngineFactory, Is.SameAs(engineFactory));
}
[Test]
public async Task ApplyManagedSessionOptionsFlagsAsync()
{
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services => services.AddOpcUa().AddClient(opts =>
{
opts.Configuration = CreateConfig();
opts.Session = new ManagedSessionOptions
{
EnableServerRedundancy = true,
EnableTokenReuseFailover = true,
TransferSubscriptionsOnRecreate = false,
PoolNotifications = true,
ModelChangeTracking = true
};
})).ConfigureAwait(false);
Assert.That(captured.EnableServerRedundancy, Is.True);
Assert.That(captured.EnableTokenReuseFailover, Is.True);
Assert.That(captured.TransferSubscriptionsOnRecreate, Is.False);
Assert.That(captured.PoolNotifications, Is.True);
Assert.That(captured.ModelChangeTracking, Is.True);
}
[Test]
public async Task ApplyManagedSessionOptionsServerRedundancyOptionsAsync()
{
var redundancy = new ServerRedundancyOptions();
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services => services.AddOpcUa().AddClient(opts =>
{
opts.Configuration = CreateConfig();
opts.Session = new ManagedSessionOptions
{
EnableServerRedundancy = true,
ServerRedundancy = redundancy
};
})).ConfigureAwait(false);
Assert.That(captured.ServerRedundancy, Is.SameAs(redundancy));
}
[Test]
public async Task AddDiscoveryAndConnectRewritesAdvertisedHostToDiscoveryHost()
{
var services = new ServiceCollection();
services.AddOpcUa()
.AddClient(opts => opts.Configuration = CreateConfig())
.AddDiscoveryAndConnect(opts =>
{
opts.DiscoveryUrl = "opc.tcp://public-name:4841";
opts.SecurityMode = MessageSecurityMode.None;
opts.SecurityPolicyUri = SecurityPolicies.None;
});
services.AddSingleton<IOpcUaDiscoveryService>(new EndpointDiscoveryStub(
[
new EndpointDescription
{
EndpointUrl = "https://internal-host:4843",
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None
},
new EndpointDescription
{
EndpointUrl = "opc.tcp://internal-host:4840/path",
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None
}
]));
ConfiguredEndpoint? connected = null;
var factory = new Mock<IManagedSessionFactory>();
factory.Setup(f => f.ConnectAsync(It.IsAny<ConfiguredEndpoint>(), It.IsAny<CancellationToken>()))
.Callback<ConfiguredEndpoint, CancellationToken>((endpoint, _) => connected = endpoint)
.ThrowsAsync(new OperationCanceledException());
services.AddSingleton(factory.Object);
using ServiceProvider sp = services.BuildServiceProvider();
Func<CancellationToken, Task<Client.ManagedSession>> connect =
sp.GetRequiredService<Func<CancellationToken, Task<Client.ManagedSession>>>();
await Assert.CatchAsync<OperationCanceledException>(() => connect(CancellationToken.None));
Assert.That(connected, Is.Not.Null);
Uri url = connected!.EndpointUrl!;
Assert.That(url.Scheme, Is.EqualTo("opc.tcp"));
Assert.That(url.Host, Is.EqualTo("public-name"));
Assert.That(url.Port, Is.EqualTo(4841));
Assert.That(url.AbsolutePath, Is.EqualTo("/path"));
}
/// <summary>
/// Discovered endpoints inherit explicitly bounded application quotas instead of the 2 MiB defaults.
/// </summary>
[Test]
public async Task AddDiscoveryAndConnectPreservesApplicationTransportQuotas()
{
ApplicationConfiguration configuration = CreateConfig();
configuration.TransportQuotas = new TransportQuotas
{
MaxMessageSize = 16 * 1024 * 1024,
MaxByteStringLength = 16 * 1024 * 1024,
MaxArrayLength = 100_000
};
var services = new ServiceCollection();
services.AddOpcUa().AddClient(options => options.Configuration = configuration)
.AddDiscoveryAndConnect(options =>
{
options.DiscoveryUrl = "opc.tcp://localhost:4840";
options.SecurityMode = MessageSecurityMode.None;
options.SecurityPolicyUri = SecurityPolicies.None;
});
services.AddSingleton<IOpcUaDiscoveryService>(new EndpointDiscoveryStub(
[
new EndpointDescription
{
EndpointUrl = "opc.tcp://localhost:4840",
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None
}
]));
ConfiguredEndpoint? connected = null;
var factory = new Mock<IManagedSessionFactory>();
factory.Setup(value => value.ConnectAsync(It.IsAny<ConfiguredEndpoint>(), It.IsAny<CancellationToken>()))
.Callback<ConfiguredEndpoint, CancellationToken>((endpoint, _) => connected = endpoint)
.ThrowsAsync(new OperationCanceledException());
services.AddSingleton(factory.Object);
using ServiceProvider provider = services.BuildServiceProvider();
Func<CancellationToken, Task<Client.ManagedSession>> connect =
provider.GetRequiredService<Func<CancellationToken, Task<Client.ManagedSession>>>();
await Assert.CatchAsync<OperationCanceledException>(() => connect(CancellationToken.None));
Assert.That(connected, Is.Not.Null);
EndpointConfiguration quotas = connected!.Configuration ??
throw new InvalidOperationException("Endpoint quotas are required.");
Assert.That(quotas.MaxMessageSize, Is.EqualTo(16 * 1024 * 1024));
Assert.That(quotas.MaxByteStringLength, Is.EqualTo(16 * 1024 * 1024));
Assert.That(quotas.MaxArrayLength, Is.EqualTo(100_000));
}
[Test]
public async Task ApplyManagedSessionOptionsTimeProviderAsync()
{
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services => services.AddOpcUa().AddClient(opts =>
{
opts.Configuration = CreateConfig();
opts.Session = new ManagedSessionOptions
{
TimeProvider = TimeProvider.System
};
})).ConfigureAwait(false);
Assert.That(captured.TimeProvider, Is.SameAs(TimeProvider.System));
}
[Test]
public async Task ApplyManagedSessionOptionsWithRegisteredIdentityProviderAsync()
{
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services => services.AddOpcUa()
.AddClient(opts => opts.Configuration = CreateConfig())
.AddIdentityProvider<AnonymousIdentityProvider>()).ConfigureAwait(false);
Assert.That(captured.IdentityProvider, Is.InstanceOf<AnonymousIdentityProvider>());
}
[Test]
public async Task ApplyManagedSessionOptionsWithMultipleIdentityProvidersAsync()
{
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services =>
{
services.AddOpcUa()
.AddClient(opts => opts.Configuration = CreateConfig());
services.AddSingleton<IClientIdentityProvider, AnonymousIdentityProvider>();
services.AddSingleton<IClientIdentityProvider, AnonymousIdentityProvider>();
}).ConfigureAwait(false);
Assert.That(captured.IdentityProvider, Is.InstanceOf<CompositeClientIdentityProvider>());
}
[Test]
public async Task ApplyManagedSessionOptionsWithIdentityProviderInSessionOptionsAsync()
{
IClientIdentityProvider provider = new AnonymousIdentityProvider();
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services => services.AddOpcUa().AddClient(opts =>
{
opts.Configuration = CreateConfig();
opts.Session = new ManagedSessionOptions
{
IdentityProvider = provider
};
})).ConfigureAwait(false);
Assert.That(captured.IdentityProvider, Is.SameAs(provider));
}
[Test]
public async Task ApplyManagedSessionOptionsRediscoveredEndpointValidatorFromSessionOptionsAsync()
{
RediscoveredEndpointValidator validator = (_, _, _) => new ValueTask<ServiceResult>(ServiceResult.Good);
RediscoveredEndpointValidator registered = (_, _, _) => new ValueTask<ServiceResult>(ServiceResult.Good);
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services =>
{
services.AddOpcUa().AddClient(opts =>
{
opts.Configuration = CreateConfig();
opts.Session = new ManagedSessionOptions
{
ValidateRediscoveredEndpoint = validator
};
});
services.AddSingleton(registered);
}).ConfigureAwait(false);
Assert.That(captured.ValidateRediscoveredEndpoint, Is.SameAs(validator));
}
[Test]
public async Task ApplyManagedSessionOptionsRediscoveredEndpointValidatorFromServicesAsync()
{
RediscoveredEndpointValidator registered = (_, _, _) => new ValueTask<ServiceResult>(ServiceResult.Good);
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services =>
{
services.AddOpcUa().AddClient(opts => opts.Configuration = CreateConfig());
services.AddSingleton(registered);
}).ConfigureAwait(false);
Assert.That(captured.ValidateRediscoveredEndpoint, Is.SameAs(registered));
}
[Test]
public async Task ApplyManagedSessionOptionsWithoutRediscoveredEndpointValidatorAsync()
{
ManagedSessionOptions captured = await CaptureAppliedSessionOptionsAsync(services =>
services.AddOpcUa().AddClient(opts => opts.Configuration = CreateConfig()))
.ConfigureAwait(false);
Assert.That(captured.ValidateRediscoveredEndpoint, Is.Null);
}
private static async Task<ManagedSessionOptions> CaptureAppliedSessionOptionsAsync(
Action<ServiceCollection> configureServices)
{
var services = new ServiceCollection();
services.AddSingleton(Mock.Of<IClientChannelManager>());
configureServices(services);
using ServiceProvider sp = services.BuildServiceProvider();
IManagedSessionFactory factory = sp.GetRequiredService<IManagedSessionFactory>();
ManagedSessionOptions? captured = null;
OperationCanceledException? ex = await Assert.CatchAsync<OperationCanceledException>(async () =>
await factory.ConnectAsync(
CreateEndpoint(),
builder =>
{
captured = builder.Build();
throw new OperationCanceledException();
},
CancellationToken.None).ConfigureAwait(false));
Assert.That(ex, Is.Not.Null);
Assert.That(captured, Is.Not.Null);
return captured!;
}
private static ApplicationConfiguration CreateConfig()
{
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
return new ApplicationConfiguration(telemetry)
{
ApplicationUri = "urn:test:client-cov",
ApplicationName = "client-cov",
ClientConfiguration = new ClientConfiguration()
};
}
private static ConfiguredEndpoint CreateEndpoint()
{
return new ConfiguredEndpoint(null, new EndpointDescription
{
EndpointUrl = "opc.tcp://127.0.0.1:62000"
}, null);
}
/// <summary>
/// Minimal discovery stub that returns an empty endpoint list so that
/// <c>SelectDiscoveredEndpointAsync</c> always reaches the "no match" throw.
/// </summary>
private sealed class EndpointDiscoveryStub : IOpcUaDiscoveryService
{
public EndpointDiscoveryStub(EndpointDescription[] endpoints)
{
m_endpoints = endpoints;
}
public ValueTask<ArrayOf<ApplicationDescription>> FindServersAsync(
string discoveryUrl,
ArrayOf<string> serverUris = default,
CancellationToken ct = default)
{
return new ValueTask<ArrayOf<ApplicationDescription>>([]);
}
public ValueTask<ArrayOf<EndpointDescription>> GetEndpointsAsync(
string discoveryUrl,
ArrayOf<string> profileUris = default,
CancellationToken ct = default)
{
return new ValueTask<ArrayOf<EndpointDescription>>(m_endpoints.ToArrayOf());
}
private readonly EndpointDescription[] m_endpoints;
}
private sealed class EmptyDiscoveryStub : IOpcUaDiscoveryService
{
public ValueTask<ArrayOf<ApplicationDescription>> FindServersAsync(
string discoveryUrl,
ArrayOf<string> serverUris = default,
CancellationToken ct = default)
{
return new ValueTask<ArrayOf<ApplicationDescription>>(
[]);
}
public ValueTask<ArrayOf<EndpointDescription>> GetEndpointsAsync(
string discoveryUrl,
ArrayOf<string> profileUris = default,
CancellationToken ct = default)
{
return new ValueTask<ArrayOf<EndpointDescription>>(
[]);
}
}
}
}