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:
jhartworks committed 2026-11-19 16:06:54 +01:00
1 parent d9165a60ff
commit 98c48d9d78
80 files changed
+11120 -315

No files matched your search

@@ -0,0 +1,37 @@
using System.Text.Json;
using Gateway.Api.Domain;
using Gateway.Api.Services;
using Microsoft.Extensions.Logging.Abstractions;
internal static class BacnetBridgeTests
{
public static async Task RunAsync(GatewayStore store, GatewayDatabase database)
{
var point = store.CreatePoint(new CreatePointRequest("Native priority bridge AV", PointProtocol.Bacnet, PointScope.Gateway, "Real", true, true, null, JsonSerializer.SerializeToElement(new { }), BacnetObjectKind.AnalogValue));
var trend = store.CreateTrendLog(new CreateTrendLogRequest(point.Id, "Native observed trend", 902, 1, 100, true));
store.SetPointValue(point.Id, JsonSerializer.SerializeToElement(22), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good", bacnetPriority: 16);
Check(store.ListPointValues().All(value => value.PointId != point.Id), "A BACnet command must not become an effective value before native arbitration.");
Check(store.ListTrendRecords(trend.Id, 100).Count == 0, "Commands must not be trended as actual values.");
using var connection = database.OpenConnection();
using var command = connection.CreateCommand();
command.CommandText = "SELECT priority FROM bacnet_commands WHERE point_id=$id";
command.Parameters.AddWithValue("$id", point.Id.ToString());
Check((long)command.ExecuteScalar()! == 16, "BACnet priority must reach the native queue.");
command.CommandText = "INSERT OR REPLACE INTO bacnet_runtime VALUES(1,$time,'Test'); INSERT INTO bacnet_observations(point_id,value_json,status,observed_ms) VALUES($id,'30','Good',$time)";
command.Parameters.AddWithValue("$time", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); command.ExecuteNonQuery();
using var bridge = new BacnetNativeBridgeService(database, store, NullLogger<BacnetNativeBridgeService>.Instance);
await bridge.StartAsync(CancellationToken.None);
try
{
var deadline = DateTime.UtcNow.AddSeconds(3);
while (store.ListPointValues().All(value => value.PointId != point.Id)) { if (DateTime.UtcNow > deadline) throw new InvalidOperationException("Native observation timed out."); await Task.Delay(25); }
Check(store.ListPointValues().Single(value => value.PointId == point.Id).Value.GetInt32() == 30, "Native arbitration must determine the effective value.");
Check(store.ListTrendRecords(trend.Id, 100).Count == 1, "Native observations must feed the trend once.");
command.CommandText = "SELECT COUNT(*) FROM bacnet_commands WHERE point_id=$id";
Check((long)command.ExecuteScalar()! == 1, "Native feedback must not enqueue another write.");
}
finally { await bridge.StopAsync(CancellationToken.None); }
Console.WriteLine("BACnet bridge tests passed: command/observation separation, priority transport, effective-value trend, no echo.");
}
private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
}
+137
View File
@@ -0,0 +1,137 @@
using System.Net;
using System.Text.Json;
using Gateway.Api.Contracts;
using Gateway.Api.Domain;
using Gateway.Api.Options;
using Gateway.Api.Services;
using Microsoft.Extensions.Options;
internal static class LtdFeatureTests
{
private static readonly string[] WhatsAppFieldNames = ["api_key", "message", "number", "pn", "template"];
public static async Task RunAsync(GatewayStore store, GatewayDatabase database, IOptions<GatewayOptions> options, AuthenticatedGatewayUser admin)
{
var source = store.CreatePoint(new CreatePointRequest("Vorlauftemperatur", PointProtocol.Bacnet, PointScope.Gateway,
"Real", true, true, null, JsonSerializer.SerializeToElement(new { }), BacnetObjectKind.AnalogValue, 601));
var opc = store.CreatePoint(new CreatePointRequest("OPC-UA Betriebszustand", PointProtocol.OpcUa, PointScope.Gateway,
"Boolean", true, true, null, JsonSerializer.SerializeToElement(new { })));
var bacnetLog = store.CreateTrendLog(new CreateTrendLogRequest(source.Id, "Vorlauftemperatur", 601, 1, 1000, true));
var opcLog = store.CreateTrendLog(new CreateTrendLogRequest(opc.Id, "Betriebszustand", 602, 1, 1000, true));
var start = DateTimeOffset.UtcNow.AddHours(-2);
for (var index = 0; index < 120; index++)
{
store.SetPointValue(source.Id, JsonSerializer.SerializeToElement(25 + Math.Sin(index / 15d) * 3), PointProtocol.Bacnet, start.AddMinutes(index));
store.SetPointValue(opc.Id, JsonSerializer.SerializeToElement(index % 20 < 10), PointProtocol.OpcUa, start.AddMinutes(index));
}
Check(store.ListTrendRecords(bacnetLog.Id, 200).Count == 120 && store.ListTrendRecords(opcLog.Id, 200).Count == 120,
"Gateway-owned BACnet and OPC UA point updates must feed their internal trends.");
store.SaveDisplayUnit(new DisplayUnit("bar", "Bar"));
store.SaveDisplayUnit(new DisplayUnit("°C", "Grad Celsius", false));
Check(store.ListDisplayUnits().Single(unit => unit.Symbol == "°C").IsSystem, "System units must retain their identity.");
store.SavePointPresentations([new(source.Id, "Vorlauf Anlage 1", "°C", 1, "analog", "#12d0d3"), new(opc.Id, "Betrieb Anlage 1", "bool", 1, "digital", "#27e72e")]);
store.SavePointPresentations([new(source.Id, "Vorlauf Anlage 1", "°C", 1, "analog", "#c9dc1e")]);
Check(store.ListPointPresentations().Count == 2, "Partial alias updates must not delete other aliases.");
var export = store.ListTrendExportRows([bacnetLog.Id], start);
Check(export.Count == 120 && export.All(row => row.PointName == "Vorlauf Anlage 1" && row.Unit == "°C"), "CSV exports must use the configured aliases and units.");
Reject(() => store.SavePointPresentations([new(source.Id, "Bad", "missing", 1, "analog", "#ffffff")]), "Unknown units must be rejected.");
Reject(() => store.SavePointPresentations([new(source.Id, "Bad", "°C", 1, "analog", "red;display:none")]), "CSS injection must be rejected.");
var selection = store.CreateTrendSelection(new CreateTrendSelectionRequest("Heizkreis", null, false, [bacnetLog.Id]), admin.User.Id);
store.SaveDashboard(admin.User.Id, true, [new(Guid.NewGuid(), "Heizkreis – Vorlauf", selection.Id, 24, "Graph")]);
Check(store.GetDashboard(admin.User.Id).Count == 1, "Widgets must persist per user.");
var viewer = store.CreateUser(new CreateUserRequest("ltd.viewer", "LTD Viewer", null, "safe testing password", "viewer"));
Reject(() => store.SaveDashboard(viewer.Id, false, [new(Guid.NewGuid(), "Private", selection.Id, 24, "Graph")]), "Other users' private selections must not be added to dashboards.");
store.UpdateKomariEnrollmentToken("test-komari-enrollment");
var tokenPath = Path.Combine(options.Value.DataDirectory, "token-test");
Check(store.MaterializeKomariEnrollmentToken(tokenPath) && File.ReadAllText(tokenPath) == "test-komari-enrollment", "Encrypted Komari token must materialize for the agent.");
foreach (var channel in Enum.GetValues<NotificationChannel>()) store.UpdateNotificationKey(channel, new("test-secret-" + channel));
using (var connection = database.OpenConnection())
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT value FROM settings WHERE key LIKE 'integration.%.api-key' OR key = 'komari.enrollment-token';";
using var reader = command.ExecuteReader();
while (reader.Read()) Check(!reader.GetString(0).Contains("test-", StringComparison.Ordinal), "Keys must not be stored in plaintext.");
}
Check(store.GetNotificationKey(NotificationChannel.Mail) == "test-secret-Mail", "Saved keys must roundtrip.");
store.UpdateNotificationKey(NotificationChannel.Mail, new(null));
Check(store.GetNotificationKey(NotificationChannel.Mail) == "test-secret-Mail", "Empty key edit must retain an existing key.");
Check(NotificationTransport.NormalizeTemplateText(" Störung\r\n\t Küche 21 °C 😀 ") == "Störung Küche 21 °C 😀", "WhatsApp must normalize whitespace and preserve Unicode.");
Reject(() => NotificationTransport.NormalizeTemplateText(new string('a', 1025)), "Overlong template parameters must not be truncated or sent.");
var destination = new AlarmDestination(NotificationChannel.WhatsApp, "+491234567890", "stoerung", "Prüfung");
var rule = store.SaveAlarmRule(new AlarmRule(Guid.Empty, "Vorlauf hoch", source.Id, AlarmCondition.Above, 30, 2, true, true, "Temperatur prüfen\nHeizkreis 1", [destination]));
var alarmTime = DateTimeOffset.UtcNow;
void Observe(double value, int seconds, string? status = null) => store.SetPointValue(source.Id, JsonSerializer.SerializeToElement(value), PointProtocol.Bacnet, alarmTime.AddSeconds(seconds), status);
Observe(29, 1); Check(store.ListNotificationDeliveries().Count == 0, "Initial normal state must not send a recovery.");
Observe(31, 2); Observe(31, 3); Observe(29, 4);
Check(store.ListNotificationDeliveries().Count == 1, "Unchanged and hysteresis-band values must not repeat an alarm.");
var delivery = store.ClaimNotification()!;
Check(delivery.State == "Sending" && store.ClaimNotification() is null, "A notification can be claimed only once.");
using (var form = NotificationTransport.BuildAlarmForm("mock-key", delivery))
{
var fields = new Dictionary<string, string>();
foreach (var part in form) fields[part.Headers.ContentDisposition!.Name!.Trim('"')] = await part.ReadAsStringAsync();
Check(fields.Keys.Order().SequenceEqual(WhatsAppFieldNames.Order()), "WhatsApp form fields must match the supplied PHP API.");
Check(!fields["message"].Contains('\n') && fields["message"].Contains("prüfen", StringComparison.Ordinal), "Sent template variables must be normalized Unicode text.");
}
store.RecoverInterruptedNotifications();
Check(store.ListNotificationDeliveries().Single().State == "Unknown", "Uncertain sends must not be automatically duplicated after restart.");
Observe(27, 5); Observe(32, 4); Observe(33, 6, "bad");
Check(store.ListNotificationDeliveries().Count == 2, "Recovery should send once; stale or invalid-quality observations must not alarm.");
store.SaveAlarmRule(rule with { Message = "Neue Beschreibung" });
Observe(27, 7);
Check(store.ListNotificationDeliveries().Count == 2, "Editing descriptions must preserve alarm edge state.");
Observe(31, 8);
Check(store.ListNotificationDeliveries().Count == 3, "A new rising edge must send again.");
store.DeleteAlarmRule(rule.Id);
Check(store.ClaimNotification() is null, "Deleting a rule must cancel pending sends.");
store.UpdateNotificationKey(NotificationChannel.WhatsApp, new(null, true));
Reject(() => store.SaveAlarmRule(rule with { Id = Guid.Empty }), "A channel without a key must not activate an alarm.");
var handler = new FakeNotificationHandler();
var transport = new NotificationTransport(new FakeClientFactory(handler));
await transport.SendAlarmAsync("mock-key", delivery, CancellationToken.None);
Check(handler.Address == "https://whatsappapi.se-inno.de/" && handler.Multipart, "Notifications must use the fixed endpoint and multipart forms.");
handler.ResponseBody = "{\"success\":false,\"error\":\"secret raw response\"}";
try { await transport.SendAlarmAsync("mock-key", delivery, CancellationToken.None); throw new InvalidOperationException("API error should fail."); }
catch (DomainValidationException exception) { Check(!exception.Message.Contains("secret raw", StringComparison.Ordinal), "Remote response must not leak into logs or UI."); }
handler.ResponseBody = "{}"; handler.Status = HttpStatusCode.BadRequest;
try { await transport.SendAlarmAsync("mock-key", delivery, CancellationToken.None); throw new InvalidOperationException("HTTP error should fail."); }
catch (DomainValidationException) { }
var sessions = new SessionService(store);
var session = "Bearer " + sessions.Create(store.Authenticate(viewer.Username, "safe testing password")!);
Check(sessions.IsValid(session), "Viewer session must initially authenticate.");
store.UpdateUser(viewer.Id, new(null, null, null, null, null, false), admin.User.Id);
Check(!sessions.IsValid(session), "Disabling users must revoke existing sessions immediately.");
// Leave preview fixtures inert: no credentials or active alarm rules can send messages.
foreach (var channel in Enum.GetValues<NotificationChannel>()) store.UpdateNotificationKey(channel, new(null, true));
var configuration = store.GetGatewayConfiguration();
store.UpdateGatewayConfiguration(configuration with { OpcUa = configuration.OpcUa with { ServerEnabled = false }, Mqtt = (configuration.Mqtt ?? MqttConfiguration.CreateDefault()) with { Enabled = false }, ModbusServers = [] });
Console.WriteLine("LTD presentation, notifications, encryption and session tests passed (no real API messages).");
}
private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
private static void Reject(Action action, string message)
{
try { action(); } catch (DomainValidationException) { return; }
throw new InvalidOperationException(message);
}
private sealed class FakeClientFactory(FakeNotificationHandler handler) : IHttpClientFactory
{
public HttpClient CreateClient(string name) => new(handler, disposeHandler: false);
}
private sealed class FakeNotificationHandler : HttpMessageHandler
{
public string? Address { get; private set; }
public bool Multipart { get; private set; }
public string ResponseBody { get; set; } = "{\"success\":true}";
public HttpStatusCode Status { get; set; } = HttpStatusCode.OK;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Address = request.RequestUri!.AbsoluteUri;
Multipart = request.Content is MultipartFormDataContent;
return Task.FromResult(new HttpResponseMessage(Status) { Content = new StringContent(ResponseBody) });
}
}
}
@@ -0,0 +1,89 @@
using System.Text.Json;
using Gateway.Api.Domain;
using Gateway.Api.Options;
using Gateway.Api.Services;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Opc.Ua;
#pragma warning disable CS0618
internal static class OpcUaClientTests
{
public static async Task RunAsync(GatewayStore remote, GatewayOpcUaServer server, string url, GatewayPoint remotePoint,
ApplicationConfiguration serverConfiguration)
{
var options = Options.Create(new GatewayOptions { DataDirectory = Path.Combine(Path.GetTempPath(), "seiugw-ua-client-" + Guid.NewGuid().ToString("N")),
Bacnet = new BacnetBootstrapOptions { Interface = "lo", DeviceInstance = 24, IpPort = 47829 } });
var database = new GatewayDatabase(options);
var store = new GatewayStore(database, new PasswordService(), new MappingValidator(), new SecretProtector(options), options);
store.Initialize();
var applications = new OpcUaApplicationFactory(database);
var config = await applications.CreateClientConfigurationAsync();
using (var trust = config.SecurityConfiguration.TrustedPeerCertificates.OpenStore()) await trust.AddAsync(serverConfiguration.SecurityConfiguration.ApplicationCertificate.Certificate);
using (var trust = serverConfiguration.SecurityConfiguration.TrustedPeerCertificates.OpenStore()) await trust.AddAsync(config.SecurityConfiguration.ApplicationCertificate.Certificate);
await serverConfiguration.CertificateValidator.UpdateAsync(serverConfiguration.SecurityConfiguration);
var client = store.SaveOpcUaClient(new SaveOpcUaClientRequest(new OpcUaClientConfiguration(Guid.NewGuid(), "Wire client", url,
OpcUaAuthenticationMode.Username, "admin", PublishingIntervalMilliseconds: 100), "correct horse battery staple")).Configuration;
store.SaveOpcUaClient(new SaveOpcUaClientRequest(client)); // Blank edit retains the encrypted password.
Check(store.GetOpcUaClientCredentials(client.Id).Password == "correct horse battery staple", "Saved password must survive edits.");
using (var connection = database.OpenConnection())
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT value FROM settings WHERE key LIKE 'opcua.password.%'";
Check(!((string)command.ExecuteScalar()!).Contains("correct horse", StringComparison.Ordinal), "OPC UA password must be encrypted at rest.");
}
var browser = new OpcUaBrowserService(applications, store);
var browsed = await browser.BrowseAsync(new OpcUaBrowseRequest("", "nsu=" + GatewayOpcUaServer.PointsNamespace + ";s=Gateway", ClientId: client.Id));
var item = browsed.Single(item => item.DisplayName == remotePoint.DisplayName);
Check(item.ValueType == "Float" && item.Writable && item.StableNodeId!.Contains("nsu=", StringComparison.Ordinal), "Import needs scalar type, access and a stable namespace URI.");
var imported = store.ImportOpcUaPoints(new OpcUaImportRequest(client.Id, [new(item.StableNodeId!, item.DisplayName, item.ValueType!, item.Readable, item.Writable)]));
var point = imported.Single();
Check(store.ImportOpcUaPoints(new OpcUaImportRequest(client.Id, [new(item.StableNodeId!, item.DisplayName, item.ValueType!, item.Readable, item.Writable)])).Count == 0, "Duplicate import must not create duplicate writers.");
var local = store.CreatePoint(new CreatePointRequest("Local setpoint", PointProtocol.Internal, PointScope.Internal, "Float", true, true, null, JsonSerializer.SerializeToElement(new { })));
store.CreateMapping(new CreateMappingRequest(local.Id, point.Id, MappingDirection.Bidirectional, true, null, false, JsonSerializer.SerializeToElement(new { })));
using var mappings = new MappingRuntimeService(store, new WriteJournal());
using var runtime = new OpcUaClientService(store, applications, NullLogger<OpcUaClientService>.Instance);
await mappings.StartAsync(CancellationToken.None);
await runtime.StartAsync(CancellationToken.None);
var writes = 0;
void Count(object? sender, PointValue update) { if (update.PointId == remotePoint.Id) Interlocked.Increment(ref writes); }
remote.PointValueUpdated += Count;
try
{
await Until(() => store.ListPointValues().Any(value => value.PointId == point.Id && value.Status == "Good"));
Check(writes == 0, "Initial synchronization must never write to the remote device.");
store.SetPointValue(local.Id, JsonSerializer.SerializeToElement(37.25), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good");
await Until(() => remote.ListPointValues().Any(value => value.PointId == remotePoint.Id && value.Value.GetSingle() == 37.25f));
server.RefreshPoints(false);
await Task.Delay(700);
Check(writes == 1, "A mapped command and its subscription echo must produce exactly one remote write.");
remote.SetPointValue(remotePoint.Id, JsonSerializer.SerializeToElement(38.5), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good");
server.RefreshPoints(false);
await Until(() => store.ListPointValues().Any(value => value.PointId == local.Id && value.Value.ValueKind == JsonValueKind.Number && value.Value.GetDouble() == 38.5));
Check(writes == 2, "A remote update must reach the reverse mapping without being written back.");
store.SetPointValue(local.Id, JsonSerializer.SerializeToElement(99), PointProtocol.Internal, DateTimeOffset.UtcNow, "BadNotConnected");
await Task.Delay(350);
Check(writes == 2, "Bad quality must never actuate an external point.");
var active = server.CurrentInstance.SessionManager.GetSessions().Single(session => session.SessionDiagnostics.SessionName == "SE-UGW Wire client");
server.CurrentInstance.CloseSession(null, active.Id, true);
await Until(() => server.CurrentInstance.SessionManager.GetSessions().Any(session => session.SessionDiagnostics.SessionName == "SE-UGW Wire client" && session.Id != active.Id), 25000);
await Until(() => store.ListPointValues().Any(value => value.PointId == point.Id && value.Status == "Good"));
Check(writes == 2, "Reconnect must rebuild subscriptions, read current values and never replay commands.");
Console.WriteLine("OPC UA client tests passed: encrypted credentials, typed import, subscription, bidirectional mapping, no echo, bad quality, reconnect.");
}
finally
{
remote.PointValueUpdated -= Count;
await runtime.StopAsync(CancellationToken.None);
await mappings.StopAsync(CancellationToken.None);
}
}
private static async Task Until(Func<bool> predicate, int timeout = 12000)
{
var limit = DateTime.UtcNow.AddMilliseconds(timeout);
while (!predicate()) { if (DateTime.UtcNow > limit) throw new InvalidOperationException("OPC UA client condition timed out."); await Task.Delay(50); }
}
private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
}
#pragma warning restore CS0618
@@ -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
+153 -1
View File
@@ -4,6 +4,8 @@ using Gateway.Api.Domain;
using Gateway.Api.Options;
using Gateway.Api.Services;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging.Abstractions;
using System.Net.Sockets;
var validator = new MappingValidator();
var sourceOne = CreatePoint(PointProtocol.Internal, PointScope.Internal, null);
@@ -45,9 +47,133 @@ store.Initialize();
Assert(!store.HasAdmin(), "A new database must not contain an admin password.");
store.CreateInitialAdmin(new SetInitialAdminRequest("correct horse battery staple", "P190726", 1));
Assert(store.HasAdmin() && store.VerifyAdminPassword("correct horse battery staple"), "The configured admin must authenticate.");
var authenticatedAdmin = store.Authenticate("admin", "correct horse battery staple");
Assert(authenticatedAdmin is not null && authenticatedAdmin.Permissions.Contains(GatewayPermissions.ManageUsers), "The migrated administrator must receive the complete admin role.");
var viewer = store.CreateUser(new CreateUserRequest("trend.viewer", "Trend Viewer", null, "another secure password", "viewer"));
Assert(store.Authenticate(viewer.Username, "another secure password")?.Permissions.SequenceEqual([GatewayPermissions.ViewDashboard, GatewayPermissions.ViewTrends]) == true, "Viewer accounts must receive only viewer permissions.");
Assert(store.GetGatewayConfiguration().VendorId == 815 && store.GetGatewayConfiguration().DeviceInstance == 23, "BACnet bootstrap defaults must be persisted.");
Assert(store.GetGatewayConfiguration().Installation?.HostName == "SE-UGW-P190726-ISP01", "First commissioning must create the requested Komari-visible hostname.");
Assert(File.Exists(Path.Combine(dataDirectory, "provisioning", "host.json")), "The NixOS hostname helper must receive an identity-only provisioning request.");
var oldConfiguration = store.GetGatewayConfiguration();
var installation = store.UpdateInstallationIdentity(new InstallationIdentity(" p260123 ", 3));
store.UpdateGatewayConfiguration(oldConfiguration);
Assert(installation.HostName == "SE-UGW-P260123-ISP03" && store.GetGatewayConfiguration().Installation == installation &&
File.ReadAllText(Path.Combine(dataDirectory, "provisioning", "host.json")).Contains("P260123", StringComparison.Ordinal),
"Changing installation identity must provision the new name and survive updates from an older protocol form.");
var etsXml = "<Project><GroupAddresses><GroupAddress Name=\"Room temperature\" Address=\"1/2/3\" DatapointType=\"DPT-9-001\" /></GroupAddresses></Project>";
var knxImport = KnxEtsImporter.Import(new KnxEtsImportRequest("sample.xml", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(etsXml))), store);
Assert(knxImport.Imported == 1 && store.ListPoints().Any(point => point.Protocol == PointProtocol.Knx && point.ExternalIdentity == "knx:1/2/3"), "ETS group addresses must be imported with their KNX identity.");
var mappingSource = store.CreatePoint(new CreatePointRequest(
"Mapped internal source", PointProtocol.Internal, PointScope.Internal, "Real", true, true, null, JsonElementFor("{}")));
var mappedTarget = store.CreatePoint(new CreatePointRequest(
"Mapped internal target", PointProtocol.Internal, PointScope.Internal, "Real", true, true, null, JsonElementFor("{}")));
var mappingRuntime = new MappingRuntimeService(store, journal);
await mappingRuntime.StartAsync(CancellationToken.None);
var mappingRequest = new CreateMappingRequest(mappingSource.Id, mappedTarget.Id, MappingDirection.OneWay, true, null, false, JsonElementFor("{}"));
var editableMapping = store.CreateMapping(mappingRequest).Mapping;
store.SetPointValue(mappingSource.Id, JsonElementFor("42.5"), PointProtocol.Internal, DateTimeOffset.UtcNow);
Assert(store.ListPointValues().Any(value => value.PointId == mappedTarget.Id && value.Value.GetDouble() == 42.5), "The active mapping graph must forward a point value exactly once.");
var nextTarget = store.CreatePoint(new CreatePointRequest(
"New mapping target", PointProtocol.Internal, PointScope.Internal, "Real", true, true, null, JsonElementFor("{}")));
var updatedMapping = store.UpdateMapping(editableMapping.Id, mappingRequest with { TargetPointId = nextTarget.Id })?.Mapping;
Assert(updatedMapping?.Id == editableMapping.Id && updatedMapping.CreatedAtUtc == editableMapping.CreatedAtUtc, "Editing must retain mapping identity.");
store.SetPointValue(mappingSource.Id, JsonElementFor("43"), PointProtocol.Internal, DateTimeOffset.UtcNow);
Assert(store.ListPointValues().Single(value => value.PointId == mappedTarget.Id).Value.GetDouble() == 42.5 &&
store.ListPointValues().Single(value => value.PointId == nextTarget.Id).Value.GetDouble() == 43, "Edited mappings must switch targets live.");
Assert(store.DeleteMapping(editableMapping.Id) && !store.DeleteMapping(editableMapping.Id), "Mapping deletion must distinguish missing mappings.");
store.SetPointValue(mappingSource.Id, JsonElementFor("44"), PointProtocol.Internal, DateTimeOffset.UtcNow);
Assert(store.ListPointValues().Single(value => value.PointId == nextTarget.Id).Value.GetDouble() == 43 &&
store.GetPointDependencies(mappingSource.Id)?.Mappings == 0 && store.ListPoints().Any(point => point.Id == nextTarget.Id),
"Removing a mapping must stop forwarding and preserve both points.");
await mappingRuntime.StopAsync(CancellationToken.None);
var modbusServerId = Guid.NewGuid();
store.UpdateGatewayConfiguration(store.GetGatewayConfiguration() with
{
ModbusServers = [new ModbusServerConfiguration(modbusServerId, "Smoke", "127.0.0.1", 15022, 1, 0, 100, [])]
});
var modbusGatewayPoint = store.CreatePoint(new CreatePointRequest(
"Modbus server value", PointProtocol.Modbus, PointScope.Gateway, "UInt16", true, true, null,
JsonElementFor($"{{\"serverId\":\"{modbusServerId}\",\"area\":\"HoldingRegister\",\"address\":12,\"dataType\":\"UInt16\"}}")));
store.CreatePoint(new CreatePointRequest(
"Reserved input register", PointProtocol.Modbus, PointScope.Gateway, "UInt16", true, false, null,
JsonElementFor($"{{\"serverId\":\"{modbusServerId}\",\"area\":\"InputRegister\",\"address\":1,\"dataType\":\"UInt16\"}}")));
var csvSource = store.CreatePoint(new CreatePointRequest(
"=\"Zuluft; Vorlauf\"", PointProtocol.Internal, PointScope.Internal, "UInt16", true, false, null, JsonElementFor("{}")));
store.SetPointValue(csvSource.Id, JsonElementFor("73"), PointProtocol.Internal, DateTimeOffset.UtcNow, "Good");
var batch = new BulkMappingRequest([mappingSource.Id, csvSource.Id], BulkMappingTarget.Modbus, modbusServerId);
Assert(store.CreateBulkMappings(batch) is { Created: 2, Existing: 0 }, "Bulk Modbus mapping must create both routes.");
var targets = store.ListMappings().Where(mapping => batch.SourcePointIds.Contains(mapping.SourcePointId)).ToDictionary(
mapping => mapping.SourcePointId, mapping => store.ListPoints().Single(point => point.Id == mapping.TargetPointId));
Assert(targets[mappingSource.Id].Address.GetProperty("address").GetInt32() == 2 &&
targets[csvSource.Id].Address.GetProperty("address").GetInt32() == 4 &&
store.ListPointValues().Single(value => value.PointId == targets[csvSource.Id].Id).Value.GetInt32() == 73 &&
store.CreateBulkMappings(batch) is { Created: 0, Existing: 2 }, "Register allocation must skip conflicts, preserve widths and seed current values.");
var batchMqtt = store.CreateBulkMappings(new BulkMappingRequest([mappingSource.Id, csvSource.Id], BulkMappingTarget.Mqtt, MqttTopicPrefix: "test/batch"));
Assert(batchMqtt.Created == 2 && batchMqtt.Assignments.Distinct().Count() == 2, "Bulk MQTT requires a unique topic for each point.");
var statePoint = store.CreatePoint(new("Pumpe läuft", PointProtocol.Internal, PointScope.Internal, "Bool", true, false, null, JsonElementFor("{}")));
var alarmPoint = store.CreatePoint(new("Pumpe Störung", PointProtocol.Internal, PointScope.Internal, "Boolean", true, false, null, JsonElementFor("{}")));
store.UpdateNotificationKey(NotificationChannel.Mail, new("local-smoke-key"));
var rule = store.SaveAlarmRule(new(Guid.NewGuid(), "Smoke alarm", alarmPoint.Id, AlarmCondition.Active, 0, 0, true, false, "",
[new(NotificationChannel.Mail, "alarm@example.invalid")]));
var mqttDefaults = store.GetMqttMappingDefaults();
Assert(mqttDefaults.Site == new MqttMonitoringSite(2026, "P260123", "ISP3") &&
mqttDefaults.Points.Single(point => point.PointId == csvSource.Id).Category == SeMonitoringCategory.Analog &&
mqttDefaults.Points.Single(point => point.PointId == statePoint.Id).Category == SeMonitoringCategory.Notify &&
mqttDefaults.Points.Single(point => point.PointId == alarmPoint.Id).Category == SeMonitoringCategory.Alarms,
"The MQTT default must use commissioning data and distinguish numerics, digital states and active alarm points.");
var monitoringBatch = store.CreateBulkMappings(new([csvSource.Id, statePoint.Id, alarmPoint.Id], BulkMappingTarget.Mqtt));
Assert(monitoringBatch.Created == 3 && monitoringBatch.Assignments.Any(item => item.Contains("/Alarms/", StringComparison.Ordinal)) &&
monitoringBatch.Assignments.Any(item => item.Contains("/Notify/", StringComparison.Ordinal)), "Bulk MQTT should use SE-Monitoring by default.");
var rawMqtt = store.CreateMqttMapping(new(csvSource.Id, MqttMappingFormat.SingleTopic, MqttDirection.Publish, MqttQualityOfService.AtLeastOnce,
false, null, null, null, null, null, "plant/temperature", null));
Assert(GatewayStore.GetMqttTopic(rawMqtt) == "plant/temperature", "A numeric single-topic mapping must use the specified topic exactly.");
store.DeleteAlarmRule(rule.Id);
store.UpdateNotificationKey(NotificationChannel.Mail, new(null, true));
foreach (var kind in Enum.GetValues<ConfigurationCsvKind>())
{
var csv = store.ExportConfigurationCsv(kind);
Assert(store.ImportConfigurationCsv(kind, csv) is { Created: 0, Updated: > 0 } &&
store.ExportConfigurationCsv(kind) == csv, $"CSV round-trip must preserve IDs and escaping for {kind}.");
}
var exportedPoints = store.ExportConfigurationCsv(ConfigurationCsvKind.Points);
var editedPoints = exportedPoints.Replace("Modbus server value", "Modbus renamed", StringComparison.Ordinal);
try
{
store.ImportConfigurationCsv(ConfigurationCsvKind.Points, editedPoints + "invalid\r\n");
throw new InvalidOperationException("A malformed row should fail the whole CSV import.");
}
catch (DomainValidationException exception)
{
Assert(exception.Message.Contains("CSV-Zeile", StringComparison.Ordinal) &&
store.ListPoints().Single(point => point.Id == modbusGatewayPoint.Id).DisplayName == "Modbus server value",
"A failed CSV import must report the row and roll back earlier changes.");
}
store.ImportConfigurationCsv(ConfigurationCsvKind.Points, editedPoints);
Assert(store.ListPoints().Single(point => point.Id == modbusGatewayPoint.Id).DisplayName == "Modbus renamed", "A CSV edit must update the existing point.");
var modbusService = new ModbusProtocolService(store, journal, NullLogger<ModbusProtocolService>.Instance);
await modbusService.StartAsync(CancellationToken.None);
await Task.Delay(350);
store.SetPointValue(modbusGatewayPoint.Id, JsonElementFor("42"), PointProtocol.Internal, DateTimeOffset.UtcNow);
using (var modbusClient = new TcpClient())
{
await modbusClient.ConnectAsync("127.0.0.1", 15022);
var request = new byte[] { 0, 1, 0, 0, 0, 6, 1, 3, 0, 12, 0, 1 };
await modbusClient.GetStream().WriteAsync(request);
var response = new byte[11];
await modbusClient.GetStream().ReadExactlyAsync(response);
Assert(response.SequenceEqual(new byte[] { 0, 1, 0, 0, 0, 5, 1, 3, 2, 0, 42 }), "The Modbus TCP server must expose mapped holding registers.");
}
await modbusService.StopAsync(CancellationToken.None);
modbusService.Dispose();
var opcFactory = new OpcUaApplicationFactory(database);
var opcClientConfiguration = await opcFactory.CreateClientConfigurationAsync();
Assert(opcClientConfiguration.SecurityConfiguration.ApplicationCertificate.Certificate is not null, "The OPC UA browser must create a persistent application certificate.");
try { await OpcUaFeatureTests.RunAsync(store, database); }
catch (Exception exception) { Console.Error.WriteLine(exception); Environment.ExitCode = 1; return; }
await BacnetBridgeTests.RunAsync(store, database);
var sourcePoint = store.CreatePoint(new CreatePointRequest(
"Internal temperature",
@@ -82,6 +208,12 @@ var analogMqttMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
Assert(
GatewayStore.GetMqttTopic(analogMqttMapping) == "Projekte2019/P1909015/ISP1/Analog/iVlTempFuehler4Speicher_Wert",
"SE Monitoring topics must match the requested hierarchy.");
var editedMqtt = store.UpdateMqttMapping(analogMqttMapping.Id, new CreateMqttMappingRequest(
sourcePoint.Id, MqttMappingFormat.Json, MqttDirection.Publish, MqttQualityOfService.AtMostOnce, false,
null, null, null, null, null, "test/updated-topic", "value"));
Assert(editedMqtt?.Id == analogMqttMapping.Id && GatewayStore.GetMqttTopic(editedMqtt) == "test/updated-topic", "MQTT edits must replace the mapped topic.");
Assert(store.DeleteMqttMapping(analogMqttMapping.Id) && store.GetPointDependencies(sourcePoint.Id)?.MqttMappings == 0,
"Deleting an MQTT mapping must unlink its source point.");
var invalidNotifyMappingRejected = false;
try
@@ -156,7 +288,8 @@ var scheduleJsonMapping = store.CreateMqttMapping(new CreateMqttMappingRequest(
"plant/schedule",
"weekProgram"));
Assert(GatewayStore.GetMqttTopic(scheduleJsonMapping) == "plant/schedule", "Structured BACnet values must be mappable through JSON MQTT.");
var trendLog = store.CreateTrendLog(new CreateTrendLogRequest(sourcePoint.Id, "Temperature history", 101, 60, 2, true));
var trendLog = store.CreateTrendLog(new CreateTrendLogRequest(sourcePoint.Id, "Temperature history", 101, 60, 2, true, true));
Assert(store.IsPublicTrendLog(trendLog.Id) && store.ListPublicTrendLogs().Single().Id == trendLog.Id, "Only explicitly marked trend logs may be exposed publicly.");
var historyStart = new DateTimeOffset(2026, 10, 7, 8, 0, 0, TimeSpan.Zero);
store.AppendTrendRecord(trendLog.Id, new AppendTrendRecordRequest(JsonElementFor("21.5"), PointProtocol.Internal, null, historyStart));
store.AppendTrendRecord(trendLog.Id, new AppendTrendRecordRequest(JsonElementFor("22.0"), PointProtocol.Internal, null, historyStart.AddMinutes(1)));
@@ -180,7 +313,26 @@ Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.1"
Assert(store.RecordPointObservation(sampledSourcePoint.Id, JsonElementFor("20.2"), PointProtocol.Internal, null, sampleTime.AddSeconds(60)).Count == 1, "Observations at the configured interval must be recorded.");
Assert(store.ListTrendRecords(sampledLog.Id, 10).Count == 2, "The sampled trend log must contain two records.");
var renamedPoint = store.UpdatePoint(sampledSourcePoint.Id, new CreatePointRequest(
"Humidity renamed", sampledSourcePoint.Protocol, sampledSourcePoint.Scope, sampledSourcePoint.ValueType,
sampledSourcePoint.Readable, sampledSourcePoint.Writable, null, JsonElementFor("{}")));
Assert(renamedPoint?.Id == sampledSourcePoint.Id && renamedPoint.DisplayName == "Humidity renamed", "Point editing must keep the point identity.");
var usage = store.GetPointDependencies(sampledSourcePoint.Id);
Assert(usage?.TrendLogs == 1, "The delete preview must include linked trend logs.");
try
{
store.DeletePoint(sampledSourcePoint.Id, null);
throw new InvalidOperationException("Deleting a linked point must require confirmation.");
}
catch (DomainValidationException) { }
Assert(store.DeletePoint(sampledSourcePoint.Id, usage!.Confirmation), "A confirmed point must be removable.");
Assert(store.ListPoints().All(point => point.Id != sampledSourcePoint.Id) &&
!store.ListTrendLogs().Single(log => log.Id == sampledLog.Id).Enabled &&
store.ListTrendRecords(sampledLog.Id, 10).Count == 2, "Removing a point must stop logging and preserve the history.");
await LtdFeatureTests.RunAsync(store, database, options, authenticatedAdmin!);
Console.WriteLine("Gateway smoke tests passed.");
if (args.Contains("--preview", StringComparer.Ordinal)) Console.WriteLine($"Preview data: {dataDirectory}");
static GatewayPoint CreatePoint(PointProtocol protocol, PointScope scope, string? externalIdentity)
{