using FluentAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Time.Testing; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using PowerMonitorManager; using PowerMonitorManager.Models; namespace PowerMonitor.Manager.Tests; public class PowerLimitEnforcementServiceTests { private const string BoilerSwitch = "switch.sonoff_1002230e32"; private const string AutoManagement = "switch.boilermonitor_auto_management"; private readonly Mock _haContextMock; private readonly Mock> _loggerMock; private readonly FakeTimeProvider _timeProvider; private readonly PowerMonitorOptions _options; public PowerLimitEnforcementServiceTests() { _haContextMock = new Mock(); _loggerMock = new Mock>(); _timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); _options = new PowerMonitorOptions { EnforceLimitEnabled = true, PowerLimitWatts = 5500, RecoverySeconds = 600, LimitCooldownSeconds = 30, EnforceSwitchOffEntityIds = [BoilerSwitch], PauseAndRestoreEntityIds = [AutoManagement] }; } private PowerLimitEnforcementService CreateSut() => new( _haContextMock.Object, _loggerMock.Object, Options.Create(_options), _timeProvider); private static bool IsTurnOffCall(string domain, string service, string entityId) => domain == "switch" && service == "turn_off"; private static bool IsTurnOnCall(string domain, string service, string entityId) => domain == "switch" && service == "turn_on"; [Fact] public void EnforceLimit_WhenDisabled_ShouldNotCallAnyService() { _options.EnforceLimitEnabled = false; var sut = CreateSut(); sut.EnforceLimit(6000); _haContextMock.Verify( x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); sut.IsLimitActive.Should().BeFalse(); } [Fact] public void EnforceLimit_WhenPowerBelowLimit_ShouldNotEnforce() { var sut = CreateSut(); sut.EnforceLimit(5000); sut.IsLimitActive.Should().BeFalse(); _haContextMock.Verify( x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } [Fact] public void EnforceLimit_WhenPowerExceedsLimit_ShouldTurnOffSwitchesAndPauseMonitors() { var sut = CreateSut(); sut.EnforceLimit(6000); sut.IsLimitActive.Should().BeTrue(); // turn_off called for boiler switch + auto_management _haContextMock.Verify( x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(BoilerSwitch)), null), Times.Once); _haContextMock.Verify( x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(AutoManagement)), null), Times.Once); // notification created _haContextMock.Verify( x => x.CallService("persistent_notification", "create", It.IsAny(), It.IsAny()), Times.Once); } [Fact] public void EnforceLimit_WhenBreached_ShouldTurnOffBoilerBeforeAutoManagement() { var calls = new List<(string domain, string service, string? entityId)>(); _haContextMock .Setup(x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((d, s, t, _) => calls.Add((d, s, t?.EntityIds?.FirstOrDefault()))); var sut = CreateSut(); sut.EnforceLimit(6000); var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList(); turnOffCalls.Should().HaveCount(2); turnOffCalls[0].entityId.Should().Be(BoilerSwitch, "boiler switch must be turned off before auto_management (race-safe order)"); turnOffCalls[1].entityId.Should().Be(AutoManagement); } [Fact] public void EnforceLimit_WhenAlreadyActiveAndBeforeRecoveryTime_ShouldDoNothing() { var sut = CreateSut(); sut.EnforceLimit(6000); _haContextMock.Invocations.Clear(); // advance less than recovery _timeProvider.Advance(TimeSpan.FromMinutes(5)); sut.EnforceLimit(5000); sut.IsLimitActive.Should().BeTrue(); _haContextMock.Verify( x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } [Fact] public void EnforceLimit_WhenRecoveryTimeReachedAndPowerBelowLimit_ShouldRestoreMonitorsAndNotTurnBoilerOn() { var sut = CreateSut(); sut.EnforceLimit(6000); _haContextMock.Invocations.Clear(); _timeProvider.Advance(TimeSpan.FromSeconds(601)); sut.EnforceLimit(4000); sut.IsLimitActive.Should().BeFalse(); // auto_management turned back ON _haContextMock.Verify( x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(AutoManagement)), null), Times.Once); // boiler switch should NOT be turned back on _haContextMock.Verify( x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(BoilerSwitch)), null), Times.Never); // notification dismissed _haContextMock.Verify( x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), Times.Once); } [Fact] public void EnforceLimit_WhenRecoveryTimeReachedButPowerStillHigh_ShouldStayEnforcedAndResetTimer() { var sut = CreateSut(); sut.EnforceLimit(6000); _haContextMock.Invocations.Clear(); _timeProvider.Advance(TimeSpan.FromSeconds(601)); sut.EnforceLimit(5800); sut.IsLimitActive.Should().BeTrue(); // no restore, no dismiss _haContextMock.Verify( x => x.CallService("switch", "turn_on", It.IsAny(), It.IsAny()), Times.Never); _haContextMock.Verify( x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), Times.Never); } [Fact] public void EnforceLimit_WhenRecoveryTimeReachedButPowerStillHigh_ShouldAllowAnotherRecoveryCheckAfterWait() { var sut = CreateSut(); sut.EnforceLimit(6000); // first recovery check - still high, timer resets _timeProvider.Advance(TimeSpan.FromSeconds(601)); sut.EnforceLimit(5800); sut.IsLimitActive.Should().BeTrue(); // immediately after - not enough time, no-op sut.EnforceLimit(3000); sut.IsLimitActive.Should().BeTrue(); // after another full wait - power dropped, recovers _timeProvider.Advance(TimeSpan.FromSeconds(601)); sut.EnforceLimit(3000); sut.IsLimitActive.Should().BeFalse(); } [Fact] public void EnforceLimit_WhenCooldownActive_ShouldNotReEnforce() { var sut = CreateSut(); sut.EnforceLimit(6000); sut.IsLimitActive.Should().BeTrue(); // recover so we can re-trigger _timeProvider.Advance(TimeSpan.FromSeconds(601)); sut.EnforceLimit(3000); sut.IsLimitActive.Should().BeFalse(); _haContextMock.Invocations.Clear(); // immediately breach again - within cooldown, should NOT enforce sut.EnforceLimit(6000); sut.IsLimitActive.Should().BeFalse("cooldown should block immediate re-enforcement"); _haContextMock.Verify( x => x.CallService("switch", "turn_off", It.IsAny(), It.IsAny()), Times.Never); } [Fact] public void EnforceLimit_WhenCooldownPassed_ShouldReEnforce() { var sut = CreateSut(); sut.EnforceLimit(6000); _timeProvider.Advance(TimeSpan.FromSeconds(601)); sut.EnforceLimit(3000); sut.IsLimitActive.Should().BeFalse(); // wait past cooldown _timeProvider.Advance(TimeSpan.FromSeconds(31)); _haContextMock.Invocations.Clear(); sut.EnforceLimit(6000); sut.IsLimitActive.Should().BeTrue(); _haContextMock.Verify( x => x.CallService("switch", "turn_off", It.IsAny(), It.IsAny()), Times.AtLeastOnce); } [Fact] public void EnforceLimit_WhenExactlyAtLimit_ShouldNotEnforce() { var sut = CreateSut(); sut.EnforceLimit(5500); sut.IsLimitActive.Should().BeFalse("power equal to limit should not trigger (strict greater-than)"); _haContextMock.Verify( x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } [Fact] public void BuildLimitMessage_ShouldContainCurrentAndLimitInKw() { var message = PowerLimitEnforcementService.BuildLimitMessage(6.0, 5.5); message.Should().Contain("6.00 kW"); message.Should().Contain("5.5 kW"); } [Fact] public void TriggerLimitBreach_WhenNotActive_ShouldEnforceRegardlessOfPower() { var sut = CreateSut(); sut.TriggerLimitBreach(); sut.IsLimitActive.Should().BeTrue(); _haContextMock.Verify( x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(BoilerSwitch)), null), Times.Once); _haContextMock.Verify( x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(AutoManagement)), null), Times.Once); _haContextMock.Verify( x => x.CallService("persistent_notification", "create", It.IsAny(), It.IsAny()), Times.Once); } [Fact] public void TriggerLimitBreach_WhenAlreadyActive_ShouldDoNothing() { var sut = CreateSut(); sut.TriggerLimitBreach(); _haContextMock.Invocations.Clear(); sut.TriggerLimitBreach(); _haContextMock.Verify( x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } [Fact] public void ResetLimitBreach_WhenActive_ShouldRecoverWithoutWaiting() { var sut = CreateSut(); sut.TriggerLimitBreach(); _haContextMock.Invocations.Clear(); sut.ResetLimitBreach(); sut.IsLimitActive.Should().BeFalse(); _haContextMock.Verify( x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(AutoManagement)), null), Times.Once); _haContextMock.Verify( x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), Times.Once); // boiler switch should NOT be turned on _haContextMock.Verify( x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(BoilerSwitch)), null), Times.Never); } [Fact] public void ResetLimitBreach_WhenNotActive_ShouldDoNothing() { var sut = CreateSut(); sut.ResetLimitBreach(); _haContextMock.Verify( x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } [Fact] public void TriggerLimitBreach_WhenDisabled_ShouldStillEnforce() { _options.EnforceLimitEnabled = false; var sut = CreateSut(); sut.TriggerLimitBreach(); sut.IsLimitActive.Should().BeTrue("debug trigger bypasses EnforceLimitEnabled so the button always works"); _haContextMock.Verify( x => x.CallService("switch", "turn_off", It.IsAny(), It.IsAny()), Times.AtLeastOnce); } }