Files
HomeAssistant/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs
T
gitea_admin 1152462765 Add PowerMonitor power limit enforcement service
Introduce IPowerLimitEnforcementService and its implementation: turn off configured high-power switches and pause/restore entities when the limit is exceeded, notify via persistent_notification, and restore control after the recovery window once power drops below the limit. Includes cooldown handling and manual TriggerLimitBreach/ResetLimitBreach hooks, with FakeTimeProvider-based tests covering enforcement, recovery, cooldown and debug paths.

Add opencode.json wiring the HomeAssistant MCP server, the .junie MCP config files, and the implementation plan in PLAN.md.
2026-11-29 13:58:28 +02:00

345 lines
12 KiB
C#

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<IHaContext> _haContextMock;
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock;
private readonly FakeTimeProvider _timeProvider;
private readonly PowerMonitorOptions _options;
public PowerLimitEnforcementServiceTests()
{
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<PowerLimitEnforcementService>>();
_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<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
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<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
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<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
Times.Once);
_haContextMock.Verify(
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
Times.Once);
// notification created
_haContextMock.Verify(
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
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<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()))
.Callback<string, string, ServiceTarget?, object?>((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<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
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<ServiceTarget>(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<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
Times.Never);
// notification dismissed
_haContextMock.Verify(
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
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<ServiceTarget>(), It.IsAny<object?>()),
Times.Never);
_haContextMock.Verify(
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
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<ServiceTarget>(), It.IsAny<object?>()),
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<ServiceTarget>(), It.IsAny<object?>()),
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<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
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<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
Times.Once);
_haContextMock.Verify(
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
Times.Once);
_haContextMock.Verify(
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
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<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
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<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
Times.Once);
_haContextMock.Verify(
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Once);
// boiler switch should NOT be turned on
_haContextMock.Verify(
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(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<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
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<ServiceTarget>(), It.IsAny<object?>()),
Times.AtLeastOnce);
}
}