Files
jhartworks 98c48d9d78 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.
2026-11-19 16:06:54 +01:00

138 lines
11 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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) });
}
}
}