using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using LeakMonitor.Models; using LeakMonitorManager; using LeakMonitorManager.Interface; using LeakMonitorManager.Models; namespace LeakMonitor.Manager.Tests; public class LeakMonitorInitTests { private readonly Mock _haContextMock; private readonly Mock _notificationServiceMock; private readonly Mock> _loggerMock; private readonly LeakMonitorOptions _options; public LeakMonitorInitTests() { _haContextMock = new Mock(); _notificationServiceMock = new Mock(); _loggerMock = new Mock>(); _options = new LeakMonitorOptions { Enabled = true, SensorEntityIds = ["binary_sensor.aquarium_leak_sensor", "binary_sensor.boiler_moisture"] }; } private LeakMonitorInit CreateSut() { return new LeakMonitorInit( _haContextMock.Object, _notificationServiceMock.Object, _loggerMock.Object, Options.Create(_options)); } #region HandleStateChange [Fact] public void HandleStateChange_WaterDetected_ShouldSendLeakAlert() { var sut = CreateSut(); var change = CreateStateChange("off", LeakMonitorConsts.WaterDetectedState); sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change); _notificationServiceMock.Verify( n => n.SendLeakAlert("binary_sensor.aquarium_leak_sensor"), Times.Once); } [Fact] public void HandleStateChange_WaterCleared_ShouldDismissLeakAlert() { var sut = CreateSut(); var change = CreateStateChange("on", LeakMonitorConsts.WaterClearedState); sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change); _notificationServiceMock.Verify( n => n.DismissLeakAlert("binary_sensor.aquarium_leak_sensor"), Times.Once); } [Fact] public void HandleStateChange_UnknownState_ShouldNotNotify() { var sut = CreateSut(); var change = CreateStateChange("off", "unavailable"); sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change); _notificationServiceMock.Verify( n => n.SendLeakAlert(It.IsAny()), Times.Never); _notificationServiceMock.Verify( n => n.DismissLeakAlert(It.IsAny()), Times.Never); } [Fact] public void HandleStateChange_CaseInsensitive_ShouldDetectWater() { var sut = CreateSut(); var change = CreateStateChange("off", "ON"); sut.HandleStateChange("binary_sensor.boiler_moisture", change); _notificationServiceMock.Verify( n => n.SendLeakAlert("binary_sensor.boiler_moisture"), Times.Once); } #endregion private StateChange CreateStateChange(string? oldState, string? newState) { var entity = new Entity(_haContextMock.Object, "binary_sensor.test"); var oldEntityState = oldState is not null ? new EntityState { State = oldState } : null; var newEntityState = newState is not null ? new EntityState { State = newState } : null; return new StateChange(entity, oldEntityState, newEntityState); } }