Files
UA-.NETStandard/tests/Opc.Ua.Client.Tests/ClientBuilder/OpcUaDiscoveryServiceCoverageTests.cs
b76022d13d Add MinimalClient - lightweight OPC UA console client with fluent API (#4006)
# Description

Adds `MinimalClient`, a compact console OPC UA application demonstrating
the unified dependency-injection surface, secure endpoint discovery,
managed sessions, fluent V2 subscriptions, and Alarms & Conditions
support.

## Changes

- Adds `ConfigureApplication(options => ...)` to build and validate one
shared `ApplicationConfiguration` for combined client/server hosts.
- Extends `OpcUaClientOptions` so the existing `AddClient(options =>
...)` callback accepts application identity, PKI, and
certificate-validation settings like `AddServer(...)`.
- Composes root `ConfigureApplication(...)` values with client defaults
in either registration order; shared values take precedence and client
values fill gaps.
- Keeps server samples on their established `AddServer(...)`
configuration pattern.
- Adds `MinimalClient` as a .NET 10 Native AOT console application using
top-level statements and `HostApplicationBuilder`.
- Discovers a `SignAndEncrypt` / `Basic256Sha256` endpoint by default;
`--insecure` and `--auto-accept` are explicit opt-ins with warnings.
- Demonstrates fluent `AddSubscription(...)`,
`TryAddMonitoredItem(...)`, and `AlarmClientFactory` usage.
- Adds targeted configuration, client, and combined client/server tests.

## Example

```csharp
builder.Services
    .AddOpcUa()
    .AddClient(options =>
    {
        options.ApplicationName = "MinimalClient";
        options.ApplicationUri = "urn:localhost:OPCFoundation:MinimalClient";
        options.ProductUri = "uri:opcfoundation.org:MinimalClient";
        options.Session = new ManagedSessionOptions
        {
            SessionName = "MinimalClient",
            SessionTimeout = TimeSpan.FromSeconds(60)
        };
    })
    .AddDiscoveryAndConnect(options =>
    {
        options.DiscoveryUrl = discoveryUrl;
        options.SecurityMode = MessageSecurityMode.SignAndEncrypt;
        options.SecurityPolicyUri = SecurityPolicies.Basic256Sha256;
    })
    .AddSubscriptions()
    .AddAlarms();
```

## Related Issues

_If there is no issue yet, open one and link it here._

## 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.
- [x] 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.
- [ ] I fixed all failing and flaky tests in the CI pipelines and all
CodeQL warnings.
- [x] I have addressed all PR feedback received.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: romanett <romanett98@gmail.com>
Co-authored-by: Marc Schier <marcschier@hotmail.com>
2026-07-17 19:36:53 +02:00

149 lines
5.5 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.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using Opc.Ua.Client.Discovery;
using Opc.Ua.Client.TestFramework;
using Opc.Ua.Configuration;
namespace Opc.Ua.Client.Tests.ClientBuilder
{
/// <summary>
/// Exercises the <see cref="OpcUaDiscoveryService"/> happy paths
/// (FindServersAsync/GetEndpointsAsync succeeding against a real
/// server, and the <c>ConfigurationProvider</c> delegation branch)
/// that are not covered by the constructor/argument-validation tests
/// in <see cref="ClientInfrastructureCoverageTests"/>.
/// </summary>
[TestFixture]
[Category("Client")]
[Category("Discovery")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
public sealed class OpcUaDiscoveryServiceCoverageTests : ClientTestFramework
{
public OpcUaDiscoveryServiceCoverageTests()
: base(Utils.UriSchemeOpcTcp)
{
}
[OneTimeSetUp]
public override Task OneTimeSetUpAsync()
{
return base.OneTimeSetUpAsync();
}
[OneTimeTearDown]
public override Task OneTimeTearDownAsync()
{
return base.OneTimeTearDownAsync();
}
[Test]
public async Task FindServersAsyncReturnsApplicationsFromRealServerAsync()
{
var service = new OpcUaDiscoveryService(
new OpcUaClientOptions { Configuration = ClientFixture.Config },
Telemetry);
ArrayOf<ApplicationDescription> applications = await service
.FindServersAsync(ServerUrl.ToString())
.ConfigureAwait(false);
Assert.That(applications.IsNull, Is.False);
Assert.That(applications.Count, Is.GreaterThan(0));
}
[Test]
public async Task GetEndpointsAsyncReturnsEndpointsFromRealServerAsync()
{
var service = new OpcUaDiscoveryService(
new OpcUaClientOptions { Configuration = ClientFixture.Config },
Telemetry);
ArrayOf<EndpointDescription> endpoints = await service
.GetEndpointsAsync(ServerUrl.ToString())
.ConfigureAwait(false);
Assert.That(endpoints.IsNull, Is.False);
Assert.That(endpoints.Count, Is.GreaterThan(0));
}
[Test]
public async Task FindServersAsyncUsesConfigurationProviderWhenSetAsync()
{
var configurationProvider = new FakeConfigurationProvider(ClientFixture.Config);
var service = new OpcUaDiscoveryService(
new OpcUaClientOptions
{
ConfigurationProvider = configurationProvider,
Configuration = ClientFixture.Config
},
Telemetry);
ArrayOf<ApplicationDescription> applications = await service
.FindServersAsync(ServerUrl.ToString())
.ConfigureAwait(false);
Assert.That(applications.IsNull, Is.False);
Assert.That(configurationProvider.GetAsyncCallCount, Is.EqualTo(1));
}
/// <summary>
/// Minimal <see cref="IOpcUaApplicationConfigurationProvider"/> fake
/// that hands back a pre-built configuration, so the
/// <c>ConfigurationProvider != null</c> delegation branch in
/// <see cref="OpcUaDiscoveryService"/> can be exercised without a
/// second real application instance.
/// </summary>
private sealed class FakeConfigurationProvider(ApplicationConfiguration configuration)
: IOpcUaApplicationConfigurationProvider
{
public int GetAsyncCallCount { get; private set; }
public IApplicationInstance Application => null!;
public ApplicationConfiguration Configuration => configuration;
public Task<ApplicationConfiguration> GetAsync(CancellationToken ct = default)
{
GetAsyncCallCount++;
return Task.FromResult(configuration);
}
public ValueTask DisposeAsync()
{
return default;
}
}
}
}