using FluentAssertions; using LeakMonitor.Models; using LeakMonitorManager; using LeakMonitorManager.Interface; using LeakMonitorManager.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; namespace LeakMonitor.Manager.Tests; public class LeakMonitorInitTests { private readonly Mock _haContextMock = new(); private readonly Mock> _loggerMock = new(); private readonly Mock _notificationServiceMock = new(); private readonly LeakMonitorTestData.TrackingObservable _stateChanges = new(); public LeakMonitorInitTests() { _haContextMock.Setup(h => h.StateAllChanges()).Returns(_stateChanges); _loggerMock.Setup(l => l.IsEnabled(It.IsAny())).Returns(true); } private LeakMonitorInit CreateSut(LeakMonitorOptions? options = null) { return new LeakMonitorInit( _haContextMock.Object, _notificationServiceMock.Object, _loggerMock.Object, Options.Create(options ?? LeakMonitorTestData.CreateOptions())); } private void VerifyNotifications(Times expected) { _notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny()), expected); _notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny()), expected); } private void VerifyLogged(LogLevel level, Times times) { var logCount = _loggerMock.Invocations.Count(invocation => invocation.Method.Name == nameof(ILogger.Log) && invocation.Arguments[0] is LogLevel loggedLevel && loggedLevel == level); times.Validate(logCount); } #region HandleStateChange [Theory] [MemberData(nameof(LeakMonitorTestData.WaterDetectedCases), MemberType = typeof(LeakMonitorTestData))] public void HandleStateChange_WhenWaterDetected_ShouldSendLeakAlert(string sensorEntityId, string? newState) { var sut = CreateSut(); var change = LeakMonitorTestData.CreateStateChange( _haContextMock.Object, sensorEntityId, LeakMonitorConsts.WaterClearedState, newState); sut.HandleStateChange(sensorEntityId, change); _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); _notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny()), Times.Never()); } [Theory] [MemberData(nameof(LeakMonitorTestData.WaterClearedCases), MemberType = typeof(LeakMonitorTestData))] public void HandleStateChange_WhenWaterCleared_ShouldDismissLeakAlert(string sensorEntityId, string? newState) { var sut = CreateSut(); var change = LeakMonitorTestData.CreateStateChange( _haContextMock.Object, sensorEntityId, LeakMonitorConsts.WaterDetectedState, newState); sut.HandleStateChange(sensorEntityId, change); _notificationServiceMock.Verify(n => n.DismissLeakAlert(sensorEntityId), Times.Once()); _notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny()), Times.Never()); } [Theory] [MemberData(nameof(LeakMonitorTestData.NonActionableStateCases), MemberType = typeof(LeakMonitorTestData))] public void HandleStateChange_WhenStateIsNotActionable_ShouldNotNotify(string? newState) { var sut = CreateSut(); var change = LeakMonitorTestData.CreateStateChange( _haContextMock.Object, LeakMonitorTestData.AquariumSensorId, LeakMonitorConsts.WaterDetectedState, newState); sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change); VerifyNotifications(Times.Never()); } [Fact] public void HandleStateChange_WhenDetectionRepeats_ShouldForwardEveryDetection() { // Deduplication is the notification service's job (cooldown); the init handler // forwards each "on" event it receives. var sut = CreateSut(); var change = LeakMonitorTestData.CreateStateChange( _haContextMock.Object, LeakMonitorTestData.AquariumSensorId, LeakMonitorConsts.WaterDetectedState, LeakMonitorConsts.WaterDetectedState); sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change); sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change); _notificationServiceMock.Verify( n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), Times.Exactly(2)); _notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny()), Times.Never()); } [Theory] [MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))] public void HandleStateChange_WithBlankSensorId_ShouldForwardTheIdVerbatim(string sensorEntityId) { var sut = CreateSut(); var change = LeakMonitorTestData.CreateStateChange( _haContextMock.Object, sensorEntityId, LeakMonitorConsts.WaterClearedState, LeakMonitorConsts.WaterDetectedState); sut.HandleStateChange(sensorEntityId, change); _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); } #endregion #region InitializeAsync [Fact] public void InitializeAsync_WhenNoSensorsConfigured_ShouldNotSubscribeAndLogWarning() { var sut = CreateSut(LeakMonitorTestData.CreateOptions([])); sut.Should().NotBeNull(); _stateChanges.SubscriptionCount.Should().Be(0); _haContextMock.Verify(h => h.StateAllChanges(), Times.Never()); VerifyNotifications(Times.Never()); VerifyLogged(LogLevel.Warning, Times.Once()); } [Fact] public void InitializeAsync_WhenSensorsConfigured_ShouldSubscribeToEachSensor() { CreateSut(); _stateChanges.SubscriptionCount.Should().Be(LeakMonitorTestData.DefaultSensorIds.Length); _haContextMock.Verify( h => h.StateAllChanges(), Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); } [Theory] [MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))] public void InitializeAsync_WithBlankSensorId_ShouldStillSubscribeAndForward(string sensorEntityId) { CreateSut(LeakMonitorTestData.CreateOptions([sensorEntityId])); _stateChanges.SubscriptionCount.Should().Be(1); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( _haContextMock.Object, sensorEntityId, LeakMonitorConsts.WaterClearedState, LeakMonitorConsts.WaterDetectedState)); _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); } [Fact] public void InitializeAsync_WithNullSensorEntry_ShouldStillSubscribeRemainingSensors() { CreateSut(LeakMonitorTestData.CreateOptions( [null!, LeakMonitorTestData.BoilerSensorId])); _stateChanges.SubscriptionCount.Should().Be(2); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( _haContextMock.Object, LeakMonitorTestData.BoilerSensorId, LeakMonitorConsts.WaterClearedState, LeakMonitorConsts.WaterDetectedState)); _notificationServiceMock.Verify( n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId), Times.Once()); _notificationServiceMock.Verify( n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), Times.Never()); } [Theory] [MemberData(nameof(LeakMonitorTestData.WaterDetectedCases), MemberType = typeof(LeakMonitorTestData))] public void InitializeAsync_WhenSubscribedSensorDetectsWater_ShouldSendLeakAlert( string sensorEntityId, string? newState) { CreateSut(); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( _haContextMock.Object, sensorEntityId, LeakMonitorConsts.WaterClearedState, newState)); _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); _notificationServiceMock.Verify( n => n.SendLeakAlert(It.Is(id => id != sensorEntityId)), Times.Never()); } [Theory] [MemberData(nameof(LeakMonitorTestData.WaterClearedCases), MemberType = typeof(LeakMonitorTestData))] public void InitializeAsync_WhenSubscribedSensorClearsWater_ShouldDismissLeakAlert( string sensorEntityId, string? newState) { CreateSut(); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( _haContextMock.Object, sensorEntityId, LeakMonitorConsts.WaterDetectedState, newState)); _notificationServiceMock.Verify(n => n.DismissLeakAlert(sensorEntityId), Times.Once()); _notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny()), Times.Never()); } [Theory] [MemberData(nameof(LeakMonitorTestData.NonActionableStateCases), MemberType = typeof(LeakMonitorTestData))] public void InitializeAsync_WhenSubscribedSensorReportsNonActionableState_ShouldNotNotify(string? newState) { CreateSut(); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( _haContextMock.Object, LeakMonitorTestData.AquariumSensorId, LeakMonitorConsts.WaterDetectedState, newState)); VerifyNotifications(Times.Never()); } [Fact] public void InitializeAsync_WhenStateIsUnchanged_ShouldNotNotify() { CreateSut(); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( _haContextMock.Object, LeakMonitorTestData.AquariumSensorId, LeakMonitorConsts.WaterDetectedState, LeakMonitorConsts.WaterDetectedState)); VerifyNotifications(Times.Never()); } [Fact] public void InitializeAsync_WhenUnrelatedEntityChanges_ShouldNotNotify() { CreateSut(); _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( _haContextMock.Object, "binary_sensor.unrelated_motion", LeakMonitorConsts.WaterClearedState, LeakMonitorConsts.WaterDetectedState)); VerifyNotifications(Times.Never()); } [Fact] public void InitializeAsync_WhenDetectionSequenceArrives_ShouldNotifyPerTransition() { CreateSut(); foreach (var change in LeakMonitorTestData.CreateStateChangeSequence( _haContextMock.Object, LeakMonitorTestData.AquariumSensorId, LeakMonitorTestData.DetectionSequence)) _stateChanges.Publish(change); _notificationServiceMock.Verify( n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), Times.Exactly(2)); _notificationServiceMock.Verify( n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId), Times.Exactly(2)); } [Fact] public void InitializeAsync_WhenNotificationServiceThrows_ShouldLogErrorAndKeepMonitoring() { _notificationServiceMock .Setup(n => n.SendLeakAlert(It.IsAny())) .Throws(new InvalidOperationException("notification failed")); CreateSut(); var act = () => _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( _haContextMock.Object, LeakMonitorTestData.AquariumSensorId, LeakMonitorConsts.WaterClearedState, LeakMonitorConsts.WaterDetectedState)); act.Should().NotThrow(); VerifyLogged(LogLevel.Error, Times.Once()); // The failed event must not tear down the subscription. _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( _haContextMock.Object, LeakMonitorTestData.AquariumSensorId, LeakMonitorConsts.WaterDetectedState, LeakMonitorConsts.WaterClearedState)); _notificationServiceMock.Verify( n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId), Times.Once()); } [Fact] public void InitializeAsync_WhenSubscriptionFails_ShouldSwallowAndLogError() { _haContextMock .Setup(h => h.StateAllChanges()) .Throws(new InvalidOperationException("home assistant offline")); var act = () => CreateSut(); act.Should().NotThrow(); _stateChanges.SubscriptionCount.Should().Be(0); VerifyNotifications(Times.Never()); VerifyLogged(LogLevel.Error, Times.Once()); } #endregion }