using System.Text.Json; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using LeakMonitor.Models; using LeakMonitorManager.Models; namespace LeakMonitor.Manager.Tests; /// /// Shared, deterministic builders and datasets used by the LeakMonitor tests. /// Keeping entity/state construction, notification payload capture and generated /// input rows here means the test classes only describe the scenario under test. /// internal static class LeakMonitorTestData { public const string AquariumSensorId = "binary_sensor.aquarium_leak_sensor"; public const string BoilerSensorId = "binary_sensor.boiler_moisture"; public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId]; public static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); /// /// Builds leak monitor options with production-compatible defaults. /// Pass [] for no sensors; omit the argument for the shared sensor set. /// public static LeakMonitorOptions CreateOptions( IEnumerable? sensorEntityIds = null, int notificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes, bool enabled = true) => new() { Enabled = enabled, SensorEntityIds = sensorEntityIds?.ToArray() ?? [.. DefaultSensorIds], NotificationCooldownMinutes = notificationCooldownMinutes }; /// /// Every casing of the "water detected" state, across both configured sensors. /// public static TheoryData WaterDetectedCases { get; } = new() { { AquariumSensorId, LeakMonitorConsts.WaterDetectedState }, { AquariumSensorId, "ON" }, { AquariumSensorId, "On" }, { AquariumSensorId, "oN" }, { BoilerSensorId, LeakMonitorConsts.WaterDetectedState } }; /// /// Every casing of the "water cleared" state, across both configured sensors. /// public static TheoryData WaterClearedCases { get; } = new() { { AquariumSensorId, LeakMonitorConsts.WaterClearedState }, { AquariumSensorId, "OFF" }, { AquariumSensorId, "Off" }, { BoilerSensorId, "oFf" } }; /// /// States that must never send or dismiss a leak notification. Covers unavailable, /// unknown, blank, null and near-miss strings (the comparison is exact apart from casing). /// public static TheoryData NonActionableStateCases { get; } = new() { "unavailable", "UNAVAILABLE", "unknown", "UNKNOWN", string.Empty, " ", "\t", "open", "idle", "detected", "ON ", " off", "1", "true", null }; /// /// Blank but non-null sensor ids. Production does not validate ids, so these are /// subscribed and forwarded verbatim. /// public static TheoryData BlankSensorIds { get; } = new() { string.Empty, " ", "\t" }; /// /// (sensor id, expected notification id) rows for the id sanitising rules: /// dots become underscores, other characters and blanks are preserved. /// public static TheoryData NotificationIdCases { get; } = new() { { AquariumSensorId, "leak_monitor_binary_sensor_aquarium_leak_sensor" }, { BoilerSensorId, "leak_monitor_binary_sensor_boiler_moisture" }, { "sensor.a.b.c", "leak_monitor_sensor_a_b_c" }, { "no_dots", "leak_monitor_no_dots" }, { "binary_sensor.already_snake_case", "leak_monitor_binary_sensor_already_snake_case" }, { "binary_sensor.dash-and-dot.", "leak_monitor_binary_sensor_dash-and-dot_" }, { string.Empty, "leak_monitor_" }, { " ", "leak_monitor_ " } }; /// /// (cooldown minutes, elapsed seconds before the second alert, expected notification count) /// rows straddling the strict elapsed < cooldown boundary, plus zero, negative /// and int-max cooldowns. /// public static TheoryData CooldownBoundaryCases { get; } = new() { { 5, 0, 1 }, { 5, 299, 1 }, { 5, 300, 2 }, { 5, 301, 2 }, { 10, 599, 1 }, { 10, 600, 2 }, { 1, 59, 1 }, { 1, 60, 2 }, { 0, 0, 2 }, { -5, 0, 2 }, { int.MaxValue, 600, 1 } }; /// /// Repetition counts used to exercise duplicate suppression and zero-cooldown behaviour. /// public static TheoryData RepeatedNotificationCounts { get; } = new() { 2, 3, 5, 10 }; /// /// A deterministic detection/recovery sequence. The repeated "on" transition is filtered /// out downstream, so the expected totals are two alerts and two dismissals. /// public static (string? OldState, string? NewState)[] DetectionSequence { get; } = [ ("off", "on"), ("on", "on"), ("on", "off"), ("off", "unavailable"), ("unavailable", "on"), ("on", "off") ]; /// /// Builds an , or null when the entity has no state at all. /// public static EntityState? CreateOptionalState(string? state) => state is null ? null : new EntityState { State = state }; public static StateChange CreateStateChange( IHaContext haContext, string entityId, string? oldState, string? newState) => new(new Entity(haContext, entityId), CreateOptionalState(oldState), CreateOptionalState(newState)); public static IReadOnlyList CreateStateChangeSequence( IHaContext haContext, string entityId, params (string? OldState, string? NewState)[] transitions) => transitions .Select(transition => CreateStateChange(haContext, entityId, transition.OldState, transition.NewState)) .ToList(); /// One captured IHaContext.CallService invocation. public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data); /// /// Wires on the mock and returns the captured calls /// in invocation order. /// public static List CaptureServiceCalls(Mock haContextMock) { var calls = new List(); haContextMock .Setup(h => h.CallService( It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((domain, service, target, data) => calls.Add(new ServiceCall(domain, service, target, data))); return calls; } /// Serialises a captured service-call payload so tests can assert on it. public static JsonElement SerializePayload(object? data) => JsonSerializer.SerializeToElement(data); /// /// Deterministic clock so cooldown boundaries can be crossed without real waiting. /// public sealed class ManualTimeProvider(DateTimeOffset? start = null) : TimeProvider { private DateTimeOffset _utcNow = start ?? DefaultStart; public override DateTimeOffset GetUtcNow() => _utcNow; public void Advance(TimeSpan duration) => _utcNow += duration; public void AdvanceSeconds(int seconds) => Advance(TimeSpan.FromSeconds(seconds)); } /// /// Observable that records subscriptions and lets tests push state changes through the /// same pipeline the NetDaemon runtime uses. /// public sealed class TrackingObservable : IObservable { private readonly List> _observers = []; public int SubscriptionCount => _observers.Count; public IDisposable Subscribe(IObserver observer) { _observers.Add(observer); return new Subscription(_observers, observer); } public void Publish(T value) { foreach (var observer in _observers.ToArray()) { observer.OnNext(value); } } private sealed class Subscription(List> observers, IObserver observer) : IDisposable { public void Dispose() => observers.Remove(observer); } } }