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

+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)
{