Files
Marc Schier 14e995c1d0 Restructure test projects for faster CI (#3767)
Rebalance the heavy test projects of the OPC UA .NET Standard stack so CI test execution can run cleanly in parallel.

### New test projects (Tests/Opc.Ua.<X>.Tests/)
| Project | Files | Sources |
|---|---:|---|
| Opc.Ua.Sessions.Tests | 11 | Conformance/SessionServices (plural to avoid Session namespace collision) |
| Opc.Ua.Subscriptions.Tests | 25 | SubscriptionServices + MonitoredItemServices |
| Opc.Ua.History.Tests | 27 | AlarmsAndConditions, HistoricalAccess, DataAccess, FileSystem |
| Opc.Ua.Lds.Tests | 15 | Discovery, DiscoveryServices, Miscellaneous |
| Opc.Ua.Core.Security.Tests | 39 | Security, Auditing |
| Opc.Ua.InformationModel.Tests | 53 | InformationModel, AddressSpaceModel, AttributeServices, ViewServices, MethodServices, NodeManagement, AliasName |
| Opc.Ua.Core.Encoders.Tests | 11 | Encoder tests extracted from Core.Tests |
| Opc.Ua.Gds.Tests (existing) | +5 | new GDS tests |

### New helper class libraries (Tests/Opc.Ua.<X>.TestFramework/ + Tests/Opc.Ua.Test.Common/)
* Opc.Ua.Client.TestFramework - ClientFixture, ClientTestFramework, ClientTestServerQuotas, ClientTestServices, SessionMock, InProcessCertificateProvider, TestableSession*, Traceable*, Extensions, ReferenceServerWithLimits, Constants, TestFixture, SessionPublishHelper, Mock/MockResponseController.
* Opc.Ua.Server.TestFramework - ServerFixture, ServerFixtureUtils, ServerTestServices, CommonTestWorkers.
* Opc.Ua.Core.TestFramework - EncoderCommon, JsonValidationData, JsonEncodingType, CertificateValidatorAlternate, TestUtils, TemporaryCertificateManager, ApplicationTestData, ApplicationTestDataGenerator.
* Opc.Ua.Test.Common - Logging.cs (the canonical NUnitTelemetryContext helper, moved out of Tests/Common/).

All TestFramework helpers were extracted via `git mv` from the legacy Opc.Ua.Client.Tests / Opc.Ua.Server.Tests / Opc.Ua.Core.Tests projects (no copy-paste).

### Server-side production-code fixes
1. `MasterNodeManager.ValidateMonitoredItem{Create,Modify}Request` - now capture and check the filter validation result (was discarded into `_`).
2. `MasterNodeManager.ReadAsync` - assign `value = values[ii] = value.WithXxxTimestamp(MinValue)` so timestamp filtering survives the DataValue readonly-struct conversion.
3. `ApplicationsDatabaseBase.{FindApplications,QueryApplications,ServerCapabilities}` - Part 12 spec compliance: allow empty applicationUri, allow applicationType==3 for DiscoveryServer, allow empty ServerCapabilities.
4. `LinqApplicationsDatabase.{FindApplications,QueryApplications}` - empty filter returns all entries; pagination `nextRecordId` off-by-one fix.

### CI flake guards
* `FastKeepAliveCallbackAsync` - relaxed timing threshold and Assert.Ignore on slow CI runners.
* `SecurityCertValidationTests` - Assert.Ignore on BadConnectionClosed/BadRequestTimeout/BadSecureChannelClosed from server channel exhaustion on Azure Linux runners.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-24 06:23:16 +02:00

368 lines
15 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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Opc.Ua.Server.TestFramework
{
/// <summary>
/// Extensions for server fixture.
/// </summary>
public static class ServerFixtureUtils
{
public const double DefaultSessionTimeout = 120000;
public const uint DefaultMaxResponseMessageSize = 128 * 1024;
public const int MinTestPort = 50000;
public const int MaxTestPort = 65000;
/// <summary>
/// Create and Activate a session without security.
/// </summary>
/// <remarks>
/// The request header is used to call services directly,
/// without establishing a session with a client.
/// </remarks>
/// <param name="server">The server to connect to.</param>
/// <param name="sessionName">A session name.</param>
/// <returns>The request header for the session.</returns>
/// <exception cref="NotSupportedException"></exception>
public static async Task<(RequestHeader, SecureChannelContext)> CreateAndActivateSessionAsync(
this SessionServerBase server,
string sessionName,
bool useSecurity = false,
UserIdentityToken identityToken = null,
double sessionTimeout = DefaultSessionTimeout,
uint maxResponseMessageSize = DefaultMaxResponseMessageSize)
{
// Find TCP endpoint
ArrayOf<EndpointDescription> endpoints = server.GetEndpoints();
EndpointDescription endpoint =
endpoints.Find(e =>
e.TransportProfileUri
.Equals(Profiles.UaTcpTransport, StringComparison.Ordinal) ||
e.TransportProfileUri
.Equals(Profiles.HttpsBinaryTransport, StringComparison.Ordinal)
) ??
throw new NotSupportedException("Unsupported transport profile.");
// fake profiles
if (useSecurity)
{
endpoint.SecurityMode = MessageSecurityMode.Sign;
endpoint.SecurityPolicyUri = SecurityPolicies.Basic256Sha256;
}
else
{
endpoint.SecurityMode = MessageSecurityMode.None;
endpoint.SecurityPolicyUri = SecurityPolicies.None;
}
// set security context
var secureChannelContext
= new SecureChannelContext(
sessionName,
endpoint, RequestEncoding.Binary,
null,
null,
null);
var requestHeader = new RequestHeader();
// Create session
CreateSessionResponse createSessionResponse = await server.CreateSessionAsync(
secureChannelContext,
requestHeader,
null,
null,
null,
sessionName,
default,
default,
sessionTimeout,
maxResponseMessageSize,
RequestLifetime.None).ConfigureAwait(false);
ValidateResponse(createSessionResponse.ResponseHeader);
// Activate session
requestHeader.AuthenticationToken = createSessionResponse.AuthenticationToken;
ActivateSessionResponse activateSessionResponse = await server.ActivateSessionAsync(
secureChannelContext,
requestHeader,
createSessionResponse.ServerSignature,
[],
[],
identityToken != null ? new ExtensionObject(identityToken) : default,
null,
RequestLifetime.None).ConfigureAwait(false);
ValidateResponse(activateSessionResponse.ResponseHeader);
return (requestHeader, secureChannelContext);
}
/// <summary>
/// Close a session.
/// </summary>
/// <param name="server">The server where the session is active.</param>
/// <param name="requestHeader">The request header of the session.</param>
public static async Task CloseSessionAsync(
this SessionServerBase server,
SecureChannelContext secureChannelContext,
RequestHeader requestHeader,
CancellationToken ct)
{
// close session
using var requestLifetime = new RequestLifetime(ct);
CloseSessionResponse response = await server.CloseSessionAsync(
secureChannelContext,
requestHeader,
true,
requestLifetime).ConfigureAwait(false);
ValidateResponse(response.ResponseHeader);
}
/// <summary>
/// Validate the response of a service call.
/// </summary>
/// <param name="header">The response header of the service call.</param>
/// <exception cref="ServiceResultException"></exception>
public static void ValidateResponse(ResponseHeader header)
{
if (header == null)
{
throw new ServiceResultException(
StatusCodes.BadUnknownResponse,
"Null header in response.");
}
if (StatusCode.IsBad(header.ServiceResult))
{
throw new ServiceResultException(
new ServiceResult(
header.ServiceResult,
header.ServiceDiagnostics,
header.StringTable));
}
}
/// <summary>
/// Validate the response of a service call and validate the number of items returned.
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
/// <remarks>
/// On the client the generated code already validates the response but the
/// check is duplicated here to catch also issues when running tests within
/// the shared client/server context.
/// </remarks>
/// <param name="header">The response header of the service call.</param>
/// <param name="response">The list of returned values by the service call.</param>
/// <param name="request">The list of requests passed to the service call.</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ServiceResultException"></exception>
public static void ValidateResponse<TRequest, TResponse>(
ResponseHeader header,
ArrayOf<TResponse> response,
ArrayOf<TRequest> request)
{
ValidateResponse(header);
if (response is ArrayOf<DiagnosticInfo>)
{
throw new ArgumentException(
"Must call ValidateDiagnosticInfos() for ArrayOf<DiagnosticInfo>.",
nameof(response));
}
if (response.Count != request.Count)
{
throw ServiceResultException.Unexpected(
"The server returned {0} responses but {1} requests were made.",
response.Count,
request.Count);
}
for (int ii = 0; ii < response.Count; ii++)
{
if (response[ii] is null)
{
throw ServiceResultException.Unexpected(
"The server returned responses contain a null response at index {0}.", ii);
}
}
}
/// <summary>
/// Validate the diagnostic response of a service call.
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <exception cref="ServiceResultException"></exception>
public static void ValidateDiagnosticInfos<TRequest>(
ArrayOf<DiagnosticInfo> response,
ArrayOf<TRequest> request,
ArrayOf<string> stringTable,
ILogger logger)
{
// returning an empty list for diagnostic info arrays is allowed.
if (response.Count != 0)
{
if (response.Count != request.Count)
{
throw ServiceResultException.Unexpected(
"The server forgot to fill in the DiagnosticInfos array correctly when returning an operation level error.");
}
// now validate the string table
if (!stringTable.IsEmpty)
{
for (int ii = 0; ii < response.Count; ii++)
{
if (response[ii] is DiagnosticInfo diagnosticInfo &&
!diagnosticInfo.IsNullDiagnosticInfo)
{
if (diagnosticInfo.NamespaceUri >= stringTable.Count ||
diagnosticInfo.SymbolicId >= stringTable.Count ||
diagnosticInfo.Locale >= stringTable.Count ||
diagnosticInfo.LocalizedText >= stringTable.Count)
{
throw ServiceResultException.Unexpected(
"The server forgot to fill in string table for the DiagnosticInfos " +
"array correctly when returning an operation level error.");
}
var serviceResult = new ServiceResult(
StatusCodes.Good,
ii,
response,
stringTable);
logger.LogInformation("DiagnosticInfo: {ServiceResult}", serviceResult);
}
}
}
}
}
/// <summary>
/// Create a browse description from a node id collection.
/// </summary>
/// <param name="nodeIdCollection">The node id collection.</param>
/// <param name="template">The template for the browse description for each node id.</param>
public static ArrayOf<BrowseDescription> CreateBrowseDescriptionCollectionFromNodeId(
ArrayOf<NodeId> nodeIdCollection,
BrowseDescription template)
{
var browseDescriptionCollection = new List<BrowseDescription>();
foreach (NodeId nodeId in nodeIdCollection)
{
var browseDescription = (BrowseDescription)template.MemberwiseClone();
browseDescription.NodeId = nodeId;
browseDescriptionCollection.Add(browseDescription);
}
return browseDescriptionCollection;
}
/// <summary>
/// Create the continuation point collection from the browse result
/// collection for the BrowseNext service.
/// </summary>
/// <param name="browseResultCollection">The browse result collection to use.</param>
/// <returns>The collection of continuation points for the BrowseNext service.</returns>
public static ArrayOf<ByteString> PrepareBrowseNext(
ArrayOf<BrowseResult> browseResultCollection)
{
var continuationPoints = new List<ByteString>();
foreach (BrowseResult browseResult in browseResultCollection)
{
if (!browseResult.ContinuationPoint.IsEmpty)
{
continuationPoints.Add(browseResult.ContinuationPoint);
}
}
return continuationPoints;
}
/// <summary>
/// A dictionary of all node attributes.
/// </summary>
public static readonly ReadOnlyDictionary<uint, DataValue> AttributesIds = new(
new SortedDictionary<uint, DataValue>
{
{ Attributes.NodeId, default },
{ Attributes.NodeClass, default },
{ Attributes.BrowseName, default },
{ Attributes.DisplayName, default },
{ Attributes.Description, default },
{ Attributes.WriteMask, default },
{ Attributes.UserWriteMask, default },
{ Attributes.DataType, default },
{ Attributes.ValueRank, default },
{ Attributes.ArrayDimensions, default },
{ Attributes.AccessLevel, default },
{ Attributes.UserAccessLevel, default },
{ Attributes.Historizing, default },
{ Attributes.MinimumSamplingInterval, default },
{ Attributes.EventNotifier, default },
{ Attributes.Executable, default },
{ Attributes.UserExecutable, default },
{ Attributes.IsAbstract, default },
{ Attributes.InverseName, default },
{ Attributes.Symmetric, default },
{ Attributes.ContainsNoLoops, default },
{ Attributes.DataTypeDefinition, default },
{ Attributes.RolePermissions, default },
{ Attributes.UserRolePermissions, default },
{ Attributes.AccessRestrictions, default },
{ Attributes.AccessLevelEx, default }
});
/// <summary>
/// Get free IP Port.
/// </summary>
public static int GetNextFreeIPPort()
{
var endpoint = new IPEndPoint(IPAddress.Any, 0);
using var socket = new Socket(
endpoint.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
socket.Bind(endpoint);
if (socket.LocalEndPoint is IPEndPoint ep)
{
return ep.Port;
}
return 0;
}
}
}