Add comprehensive smoke and feature tests for Gateway API
- Introduced LtdFeatureTests to validate BACnet and OPC UA point updates, trend logging, and alarm rule functionality. - Added OpcUaClientTests to ensure proper OPC UA client configuration, point value synchronization, and session management. - Created OpcUaFeatureTests to test OPC UA server capabilities, including browsing, reading, writing, and subscription notifications. - Implemented native_bacnet_test.py for isolated BACnet wire testing, covering discovery, read/write operations, and command processing. - Added ui-theme-tabs.test.cjs to verify theme switching, tab interactions, and protocol form accessibility in the UI.
This commit is contained in:
1 parent
d9165a60ff
commit
98c48d9d78
80 files changed
+11120
-315
No files matched your search
@@ -0,0 +1,128 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Gateway.Api.Domain;
|
||||
using Gateway.Api.Contracts;
|
||||
using Gateway.Api.Services;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Opc.Ua.Configuration;
|
||||
|
||||
#pragma warning disable CS0618 // Exercise the same pinned SDK API as production.
|
||||
|
||||
internal static class OpcUaFeatureTests
|
||||
{
|
||||
public static async Task RunAsync(GatewayStore store, GatewayDatabase database)
|
||||
{
|
||||
var previous = store.GetGatewayConfiguration();
|
||||
using var portReservation = new TcpListener(IPAddress.Loopback, 0);
|
||||
portReservation.Start();
|
||||
var port = ((IPEndPoint)portReservation.LocalEndpoint).Port;
|
||||
portReservation.Stop();
|
||||
store.UpdateGatewayConfiguration(previous with { OpcUa = previous.OpcUa with { Port = port, ServerEnabled = true, AllowAnonymous = true } });
|
||||
var point = store.CreatePoint(new CreatePointRequest("UA Sollwert", PointProtocol.OpcUa, PointScope.Gateway, "Real", true, true, null, JsonSerializer.SerializeToElement(new { })));
|
||||
var readOnly = store.CreatePoint(new CreatePointRequest("UA Eingang", PointProtocol.OpcUa, PointScope.Gateway, "Boolean", true, false, null, JsonSerializer.SerializeToElement(new { })));
|
||||
var history = store.CreateTrendLog(new CreateTrendLogRequest(point.Id, "UA Drahttest", 901, 1, 100, true));
|
||||
var applications = new OpcUaApplicationFactory(database);
|
||||
var configuration = await applications.CreateServerConfigurationAsync(port, true);
|
||||
configuration.ServerConfiguration.MaxBrowseContinuationPoints = 20;
|
||||
var application = new ApplicationInstance(configuration);
|
||||
var server = new GatewayOpcUaServer(store);
|
||||
var updates = 0;
|
||||
store.PointValueUpdated += Count;
|
||||
void Count(object? sender, PointValue value) { if (value.PointId == point.Id) Interlocked.Increment(ref updates); }
|
||||
try
|
||||
{
|
||||
await application.StartAsync(server);
|
||||
var clientConfiguration = await applications.CreateClientConfigurationAsync();
|
||||
// Explicitly trust this exact local test server; never bypass arbitrary certificate errors.
|
||||
using (var trust = clientConfiguration.SecurityConfiguration.TrustedPeerCertificates.OpenStore())
|
||||
{
|
||||
var certificate = configuration.SecurityConfiguration.ApplicationCertificate.Certificate;
|
||||
if ((await trust.FindByThumbprintAsync(certificate.Thumbprint)).Count == 0) await trust.AddAsync(certificate);
|
||||
}
|
||||
await clientConfiguration.CertificateValidator.UpdateAsync(clientConfiguration.SecurityConfiguration);
|
||||
var url = $"opc.tcp://127.0.0.1:{port}";
|
||||
var selected = await CoreClientUtils.SelectEndpointAsync(clientConfiguration, url, true, 15_000, CancellationToken.None);
|
||||
var endpoint = new ConfiguredEndpoint(null, selected, EndpointConfiguration.Create(clientConfiguration));
|
||||
using var session = await Session.Create(clientConfiguration, endpoint, false, true, "Gateway wire test", 60_000,
|
||||
new UserIdentity("admin", Encoding.UTF8.GetBytes("correct horse battery staple")), null);
|
||||
var index = (ushort)session.NamespaceUris.GetIndex(GatewayOpcUaServer.PointsNamespace);
|
||||
var node = new NodeId(point.Id, index);
|
||||
session.Browse(null, null, new NodeId("Gateway", index), 100, BrowseDirection.Forward, ReferenceTypeIds.Organizes, true, (uint)NodeClass.Variable, out _, out var references);
|
||||
Check(references.Any(reference => reference.NodeId == node), "Gateway variable must be browsable with a stable GUID node id.");
|
||||
session.Read(null, 0, TimestampsToReturn.Both, [new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], out var initial, out _);
|
||||
Check(initial[0].StatusCode == StatusCodes.BadWaitingForInitialData, "Missing values must not appear as good zeroes.");
|
||||
|
||||
var notified = new TaskCompletionSource<float>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 };
|
||||
var item = new MonitoredItem(subscription.DefaultItem) { StartNodeId = node, AttributeId = Attributes.Value, SamplingInterval = 100, QueueSize = 10, DiscardOldest = true };
|
||||
item.Notification += (_, _) =>
|
||||
{
|
||||
foreach (var data in item.DequeueValues())
|
||||
if (data.StatusCode == StatusCodes.Good && data.Value is float number && number == 24.5f) notified.TrySetResult(number);
|
||||
};
|
||||
subscription.AddItem(item);
|
||||
session.AddSubscription(subscription);
|
||||
subscription.Create();
|
||||
Check(Write(session, node, 21.5f) == StatusCodes.Good, "Authenticated scalar writes must be accepted.");
|
||||
Check(updates == 1 && store.ListPointValues().Single(value => value.PointId == point.Id).Value.GetSingle() == 21.5f, "UA write must enter the common store exactly once.");
|
||||
Check(store.ListTrendRecords(history.Id, 10).Count == 1, "UA write must feed the configured trend.");
|
||||
Check(Write(session, node, true) == StatusCodes.BadTypeMismatch, "Boolean must not overwrite a Real point.");
|
||||
Check(Write(session, new NodeId(readOnly.Id, index), true) == StatusCodes.BadNotWritable, "Read-only input must reject writes.");
|
||||
Check(updates == 1, "Rejected writes must not enter the point store.");
|
||||
store.SetPointValue(point.Id, JsonSerializer.SerializeToElement(24.5), PointProtocol.Internal, DateTimeOffset.UtcNow.AddSeconds(2), "Good");
|
||||
server.RefreshPoints(false);
|
||||
await notified.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
Check(updates == 2 && store.ListTrendRecords(history.Id, 10).Count == 2, "Subscription notifications must not echo into the store or trend.");
|
||||
var late = store.CreatePoint(new CreatePointRequest("UA später angelegt", PointProtocol.OpcUa, PointScope.Gateway, "String", true, true, null, JsonSerializer.SerializeToElement(new { })));
|
||||
server.RefreshPoints(true);
|
||||
Check(Write(session, new NodeId(late.Id, index), "ÄÖÜ ✓") == StatusCodes.Good, "New nodes must appear without a server restart and support Unicode.");
|
||||
var browsed = await new OpcUaBrowserService(applications).BrowseAsync(new OpcUaBrowseRequest(url, new NodeId("Gateway", index).ToString(), true, OpcUaAuthenticationMode.Username, "admin", "correct horse battery staple"));
|
||||
Check(browsed.Any(value => value.NodeId == new NodeId(late.Id, index).ToString() && value.Value?.GetString() == "ÄÖÜ ✓"), "The web browser service must authenticate, browse and read real server variables.");
|
||||
using var anonymous = await Session.Create(clientConfiguration, endpoint, false, "Anonymous read-only test", 60_000, new UserIdentity(), null);
|
||||
Check(StatusCode.IsBad(Write(anonymous, node, 31f)), "Anonymous sessions must not write process values.");
|
||||
using var viewer = await Session.Create(clientConfiguration, endpoint, false, "Viewer read-only test", 60_000, new UserIdentity("trend.viewer", Encoding.UTF8.GetBytes("another secure password")), null);
|
||||
Check(StatusCode.IsBad(Write(viewer, node, 31f)), "Viewer accounts must not write process values.");
|
||||
try
|
||||
{
|
||||
using var invalid = await Session.Create(clientConfiguration, endpoint, false, "Wrong password test", 60_000, new UserIdentity("admin", Encoding.UTF8.GetBytes("wrong password")), null);
|
||||
throw new InvalidOperationException("Invalid password was accepted.");
|
||||
}
|
||||
catch (ServiceResultException exception) when (exception.StatusCode == StatusCodes.BadUserAccessDenied) { }
|
||||
var viewerAccount = store.ListUsers().Single(user => user.Username == "trend.viewer");
|
||||
var admin = store.ListUsers().Single(user => user.Username == "admin");
|
||||
store.UpdateUser(viewerAccount.Id, new UpdateUserRequest(null, null, null, null, null, false), admin.Id);
|
||||
server.RefreshPoints(true);
|
||||
Check(server.CurrentInstance.SessionManager.GetSessions().All(active => active.Id != viewer.SessionId), "Revoking a user must close its existing OPC UA session and subscriptions.");
|
||||
store.UpdateUser(viewerAccount.Id, new UpdateUserRequest(null, null, null, null, null, true), admin.Id);
|
||||
await viewer.CloseAsync();
|
||||
await anonymous.CloseAsync();
|
||||
subscription.Delete(true);
|
||||
await session.CloseAsync();
|
||||
await OpcUaClientTests.RunAsync(store, server, url, point, configuration);
|
||||
Console.WriteLine("OPC UA wire tests passed: browse, authentication, read/write, subscription, live nodes, trend, no echo.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
store.PointValueUpdated -= Count;
|
||||
await application.StopAsync();
|
||||
server.Dispose();
|
||||
store.UpdateGatewayConfiguration(previous);
|
||||
}
|
||||
}
|
||||
|
||||
private static StatusCode Write(Session session, NodeId node, object value)
|
||||
{
|
||||
session.Write(null, [new WriteValue { NodeId = node, AttributeId = Attributes.Value, Value = new DataValue(new Variant(value)) }], out var results, out _);
|
||||
return results[0];
|
||||
}
|
||||
|
||||
private static void Check(bool condition, string message)
|
||||
{
|
||||
if (!condition) throw new InvalidOperationException(message);
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning restore CS0618
|
||||
Reference in new issue
Block a user