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

143 lines
6.3 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/
* ======================================================================*/
#nullable enable
using Microsoft.Extensions.Options;
using NUnit.Framework;
using Opc.Ua.Configuration;
using Opc.Ua.Tests;
namespace Opc.Ua.Client.Tests.ClientBuilder
{
/// <summary>
/// Directly exercises <see cref="OpcUaClientApplicationConfigurationFeature.ApplyDefaults"/>,
/// covering both outcomes of each <c>??=</c> assignment: the
/// already-set (no-op) branch and the unset (assign-from-client-options)
/// branch, for every <see cref="OpcUaApplicationOptions"/> property.
/// </summary>
[TestFixture]
[Category("Client")]
[Category("ClientBuilder")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
[Parallelizable]
public sealed class OpcUaClientApplicationConfigurationFeatureTests
{
[Test]
public void ApplyDefaultsFillsUnsetPropertiesFromClientOptions()
{
var feature = CreateFeature(new OpcUaClientOptions
{
ApplicationName = "ClientName",
ApplicationUri = "urn:localhost:ClientName",
ProductUri = "uri:opcfoundation.org:ClientName",
SubjectName = "CN=ClientName",
PkiRoot = "pki-root",
AutoAcceptUntrustedCertificates = true,
RejectSHA1SignedCertificates = false,
MinimumCertificateKeySize = 3072
});
var options = new OpcUaApplicationOptions();
feature.ApplyDefaults(options);
Assert.That(options.ApplicationName, Is.EqualTo("ClientName"));
Assert.That(options.ApplicationUri, Is.EqualTo("urn:localhost:ClientName"));
Assert.That(options.ProductUri, Is.EqualTo("uri:opcfoundation.org:ClientName"));
Assert.That(options.SubjectName, Is.EqualTo("CN=ClientName"));
Assert.That(options.PkiRoot, Is.EqualTo("pki-root"));
Assert.That(options.AutoAcceptUntrustedCertificates, Is.True);
Assert.That(options.RejectSHA1SignedCertificates, Is.False);
Assert.That(options.MinimumCertificateKeySize, Is.EqualTo((ushort)3072));
}
[Test]
public void ApplyDefaultsLeavesAlreadySetPropertiesUnchanged()
{
var feature = CreateFeature(new OpcUaClientOptions
{
ApplicationName = "ClientName",
ApplicationUri = "urn:localhost:ClientName",
ProductUri = "uri:opcfoundation.org:ClientName",
SubjectName = "CN=ClientName",
PkiRoot = "client-pki-root",
AutoAcceptUntrustedCertificates = true,
RejectSHA1SignedCertificates = true,
MinimumCertificateKeySize = 3072
});
var options = new OpcUaApplicationOptions
{
ApplicationName = "AlreadySetName",
ApplicationUri = "urn:localhost:AlreadySetName",
ProductUri = "uri:opcfoundation.org:AlreadySetName",
SubjectName = "CN=AlreadySetName",
PkiRoot = "already-set-pki-root",
AutoAcceptUntrustedCertificates = false,
RejectSHA1SignedCertificates = false,
MinimumCertificateKeySize = 2048
};
feature.ApplyDefaults(options);
Assert.That(options.ApplicationName, Is.EqualTo("AlreadySetName"));
Assert.That(options.ApplicationUri, Is.EqualTo("urn:localhost:AlreadySetName"));
Assert.That(options.ProductUri, Is.EqualTo("uri:opcfoundation.org:AlreadySetName"));
Assert.That(options.SubjectName, Is.EqualTo("CN=AlreadySetName"));
Assert.That(options.PkiRoot, Is.EqualTo("already-set-pki-root"));
Assert.That(options.AutoAcceptUntrustedCertificates, Is.False);
Assert.That(options.RejectSHA1SignedCertificates, Is.False);
Assert.That(options.MinimumCertificateKeySize, Is.EqualTo((ushort)2048));
}
[Test]
public void ConfigureReturnsClientSecurityBuilder()
{
var feature = CreateFeature(new OpcUaClientOptions());
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
var appInstance = new ApplicationInstance(telemetry);
IApplicationConfigurationBuilderTypes builder = appInstance.Build(
"urn:localhost:OpcUaClientApplicationConfigurationFeatureTests",
"uri:opcfoundation.org:OpcUaClientApplicationConfigurationFeatureTests");
IApplicationConfigurationBuilderSecurity securityBuilder = feature.Configure(builder);
Assert.That(securityBuilder, Is.Not.Null);
Assert.That(appInstance.ApplicationConfiguration!.ApplicationType, Is.EqualTo(ApplicationType.Client));
}
private static OpcUaClientApplicationConfigurationFeature CreateFeature(OpcUaClientOptions options)
{
return new OpcUaClientApplicationConfigurationFeature(Options.Create(options));
}
}
}