17774b40b8
Replace untyped MemberData sources with TheoryData<...>, use collection expressions for array and list literals, drop redundant casts and null suppressions, and give log-assertion helpers an IsEnabled setup so guarded log calls stay verifiable.
439 lines
14 KiB
C#
439 lines
14 KiB
C#
using System.Globalization;
|
|
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 = PowerMonitorTestData.BoilerSwitchEntityId;
|
|
private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId;
|
|
|
|
private readonly Mock<IHaContext> _haContextMock = new();
|
|
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new();
|
|
private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow);
|
|
private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions();
|
|
|
|
private PowerLimitEnforcementService CreateSut() =>
|
|
new(
|
|
_haContextMock.Object,
|
|
_loggerMock.Object,
|
|
Options.Create(_options),
|
|
_timeProvider);
|
|
|
|
private void VerifyNoServiceCalls() =>
|
|
_haContextMock.Verify(
|
|
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
|
Times.Never);
|
|
|
|
private void VerifyTurnOff(string entityId, int expectedCalls) =>
|
|
_haContextMock.Verify(
|
|
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
|
Times.Exactly(expectedCalls));
|
|
|
|
private void VerifyTurnOn(string entityId, int expectedCalls) =>
|
|
_haContextMock.Verify(
|
|
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
|
Times.Exactly(expectedCalls));
|
|
|
|
private void VerifyNotificationCreated(int expectedCalls) =>
|
|
_haContextMock.Verify(
|
|
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
|
Times.Exactly(expectedCalls));
|
|
|
|
private void VerifyNotificationDismissed(int expectedCalls) =>
|
|
_haContextMock.Verify(
|
|
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
|
Times.Exactly(expectedCalls));
|
|
|
|
#region EnforceLimit
|
|
|
|
[Theory]
|
|
[InlineData(0.0)]
|
|
[InlineData(5500.0)]
|
|
[InlineData(6000.0)]
|
|
[InlineData(1_000_000.0)]
|
|
public void EnforceLimit_WhenDisabled_ShouldNotCallAnyService(double powerWatts)
|
|
{
|
|
// Arrange
|
|
_options.EnforceLimitEnabled = false;
|
|
var sut = CreateSut();
|
|
|
|
// Act
|
|
sut.EnforceLimit(powerWatts);
|
|
|
|
// Assert
|
|
VerifyNoServiceCalls();
|
|
sut.IsLimitActive.Should().BeFalse();
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(-1000.0)]
|
|
[InlineData(0.0)]
|
|
[InlineData(0.5)]
|
|
[InlineData(2749.99)]
|
|
[InlineData(5499.99)]
|
|
[InlineData(5500.0)]
|
|
public void EnforceLimit_WhenPowerAtOrBelowLimit_ShouldNotEnforce(double powerWatts)
|
|
{
|
|
// Arrange
|
|
var sut = CreateSut();
|
|
|
|
// Act
|
|
sut.EnforceLimit(powerWatts);
|
|
|
|
// Assert
|
|
sut.IsLimitActive.Should().BeFalse("power equal to the limit must not trigger (strict greater-than)");
|
|
VerifyNoServiceCalls();
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(5500.01)]
|
|
[InlineData(6000.0)]
|
|
[InlineData(15_000.0)]
|
|
[InlineData(1_000_000.0)]
|
|
public void EnforceLimit_WhenPowerExceedsLimit_ShouldTurnOffSwitchesAndPauseMonitors(double powerWatts)
|
|
{
|
|
// Arrange
|
|
var sut = CreateSut();
|
|
|
|
// Act
|
|
sut.EnforceLimit(powerWatts);
|
|
|
|
// Assert
|
|
sut.IsLimitActive.Should().BeTrue();
|
|
VerifyTurnOff(BoilerSwitch, 1);
|
|
VerifyTurnOff(AutoManagement, 1);
|
|
VerifyNotificationCreated(1);
|
|
}
|
|
|
|
[Fact]
|
|
public void EnforceLimit_WhenBreached_ShouldTurnOffBoilerBeforeAutoManagement()
|
|
{
|
|
// Arrange
|
|
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();
|
|
|
|
// Act
|
|
sut.EnforceLimit(6000);
|
|
|
|
// Assert
|
|
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_WithMultipleConfiguredEntities_ShouldTurnOffEveryEntityInConfiguredOrder()
|
|
{
|
|
// Arrange
|
|
_options.EnforceSwitchOffEntityIds = ["switch.high_load_a", "switch.high_load_b"];
|
|
_options.PauseAndRestoreEntityIds = ["switch.monitor_c"];
|
|
var calls = new List<string?>();
|
|
_haContextMock
|
|
.Setup(x => x.CallService(It.IsAny<string>(), "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()))
|
|
.Callback<string, string, ServiceTarget?, object?>((_, _, target, _) =>
|
|
calls.Add(target?.EntityIds?.FirstOrDefault()));
|
|
var sut = CreateSut();
|
|
|
|
// Act
|
|
sut.EnforceLimit(7000);
|
|
|
|
// Assert
|
|
calls.Should().Equal("switch.high_load_a", "switch.high_load_b", "switch.monitor_c");
|
|
sut.IsLimitActive.Should().BeTrue();
|
|
}
|
|
|
|
[Fact]
|
|
public void EnforceLimit_WithNoConfiguredEntities_ShouldStillNotifyAndActivate()
|
|
{
|
|
// Arrange
|
|
_options.EnforceSwitchOffEntityIds = [];
|
|
_options.PauseAndRestoreEntityIds = [];
|
|
var sut = CreateSut();
|
|
|
|
// Act
|
|
sut.EnforceLimit(6000);
|
|
|
|
// Assert
|
|
sut.IsLimitActive.Should().BeTrue();
|
|
VerifyNotificationCreated(1);
|
|
_haContextMock.Verify(
|
|
x => x.CallService("switch", It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
|
Times.Never);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Recovery
|
|
|
|
public static TheoryData<string, int, double, bool, int> RecoveryCases => new()
|
|
{
|
|
{ "not yet due", 300, 3000.0, true, 0 },
|
|
{ "one second before due", 599, 3000.0, true, 0 },
|
|
{ "exactly due", 600, 3000.0, false, 1 },
|
|
{ "just under limit", 601, 5499.99, false, 1 },
|
|
{ "zero power", 900, 0.0, false, 1 },
|
|
{ "negative power", 601, -10.0, false, 1 },
|
|
{ "exactly at limit stays enforced", 601, 5500.0, true, 0 },
|
|
{ "above limit stays enforced", 601, 5800.0, true, 0 },
|
|
{ "very high power stays enforced", 601, 25_000.0, true, 0 }
|
|
};
|
|
|
|
[Theory]
|
|
[MemberData(nameof(RecoveryCases))]
|
|
public void EnforceLimit_AfterEnforcement_ShouldEvaluateRecovery(
|
|
string scenario,
|
|
int secondsAfterEnforcement,
|
|
double powerWatts,
|
|
bool expectedLimitActive,
|
|
int expectedRecoveryActions)
|
|
{
|
|
// Arrange
|
|
var sut = CreateSut();
|
|
sut.EnforceLimit(6000);
|
|
_haContextMock.Invocations.Clear();
|
|
|
|
// Act
|
|
_timeProvider.Advance(TimeSpan.FromSeconds(secondsAfterEnforcement));
|
|
sut.EnforceLimit(powerWatts);
|
|
|
|
// Assert
|
|
sut.IsLimitActive.Should().Be(expectedLimitActive, $"scenario: {scenario}");
|
|
VerifyTurnOn(AutoManagement, expectedRecoveryActions);
|
|
VerifyTurnOn(BoilerSwitch, 0);
|
|
VerifyNotificationDismissed(expectedRecoveryActions);
|
|
}
|
|
|
|
[Fact]
|
|
public void EnforceLimit_WhenRecoveryTimeReachedButPowerStillHigh_ShouldAllowAnotherRecoveryCheckAfterWait()
|
|
{
|
|
// Arrange
|
|
var sut = CreateSut();
|
|
sut.EnforceLimit(6000);
|
|
|
|
// Act - first recovery check finds power still high and resets the timer
|
|
_timeProvider.Advance(TimeSpan.FromSeconds(601));
|
|
sut.EnforceLimit(5800);
|
|
sut.IsLimitActive.Should().BeTrue();
|
|
|
|
sut.EnforceLimit(3000);
|
|
|
|
// Assert - not enough time has passed for another check
|
|
sut.IsLimitActive.Should().BeTrue();
|
|
|
|
// Act - after another full wait the power has dropped
|
|
_timeProvider.Advance(TimeSpan.FromSeconds(601));
|
|
sut.EnforceLimit(3000);
|
|
|
|
// Assert
|
|
sut.IsLimitActive.Should().BeFalse();
|
|
VerifyTurnOn(AutoManagement, 1);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Cooldown
|
|
|
|
[Theory]
|
|
[InlineData(0, false)]
|
|
[InlineData(29, false)]
|
|
[InlineData(30, true)]
|
|
[InlineData(31, true)]
|
|
[InlineData(600, true)]
|
|
public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery, bool expectedLimitActive)
|
|
{
|
|
// Arrange
|
|
var sut = CreateSut();
|
|
sut.EnforceLimit(6000);
|
|
_timeProvider.Advance(TimeSpan.FromSeconds(601));
|
|
sut.EnforceLimit(3000);
|
|
sut.IsLimitActive.Should().BeFalse();
|
|
|
|
_haContextMock.Invocations.Clear();
|
|
|
|
// Act
|
|
_timeProvider.Advance(TimeSpan.FromSeconds(secondsAfterRecovery));
|
|
sut.EnforceLimit(6000);
|
|
|
|
// Assert
|
|
sut.IsLimitActive.Should().Be(expectedLimitActive);
|
|
|
|
if (expectedLimitActive)
|
|
{
|
|
VerifyTurnOff(BoilerSwitch, 1);
|
|
VerifyTurnOff(AutoManagement, 1);
|
|
VerifyNotificationCreated(1);
|
|
}
|
|
else
|
|
{
|
|
VerifyNoServiceCalls();
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public void EnforceLimit_ImmediatelyAfterManualReset_ShouldNotReEnforceWithinCooldown()
|
|
{
|
|
// Arrange
|
|
var sut = CreateSut();
|
|
sut.TriggerLimitBreach();
|
|
sut.ResetLimitBreach();
|
|
_haContextMock.Invocations.Clear();
|
|
|
|
// Act
|
|
sut.EnforceLimit(6000);
|
|
|
|
// Assert
|
|
sut.IsLimitActive.Should().BeFalse("the manual reset starts the cooldown window");
|
|
VerifyNoServiceCalls();
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region BuildLimitMessage
|
|
|
|
[Theory]
|
|
[InlineData("typical breach", 6.0, 5.5, "6.00 kW", "5.5 kW")]
|
|
[InlineData("rounds current to two decimals", 5.999, 5.549, "6.00 kW", "5.5 kW")]
|
|
[InlineData("zero current", 0.0, 5.5, "0.00 kW", "5.5 kW")]
|
|
[InlineData("negative current", -1.0, 5.5, "-1.00 kW", "5.5 kW")]
|
|
[InlineData("large values", 123.456, 100.0, "123.46 kW", "100.0 kW")]
|
|
public void BuildLimitMessage_ShouldContainCurrentAndLimitInKw(
|
|
string scenario,
|
|
double currentKw,
|
|
double limitKw,
|
|
string expectedCurrentText,
|
|
string expectedLimitText)
|
|
{
|
|
// Act
|
|
var message = PowerLimitEnforcementService.BuildLimitMessage(currentKw, limitKw);
|
|
|
|
// Assert
|
|
message.Should().Contain(expectedCurrentText, $"scenario: {scenario}");
|
|
message.Should().Contain(expectedLimitText, $"scenario: {scenario}");
|
|
message.Should().Contain("exceeded the limit");
|
|
}
|
|
|
|
[Fact]
|
|
public void BuildLimitMessage_WithCommaDecimalCulture_ShouldStillUseInvariantFormatting()
|
|
{
|
|
// Arrange
|
|
var originalCulture = CultureInfo.CurrentCulture;
|
|
|
|
try
|
|
{
|
|
CultureInfo.CurrentCulture = new CultureInfo("de-DE");
|
|
|
|
// Act
|
|
var message = PowerLimitEnforcementService.BuildLimitMessage(6.0, 5.5);
|
|
|
|
// Assert
|
|
message.Should().Contain("6.00 kW");
|
|
message.Should().Contain("5.5 kW");
|
|
}
|
|
finally
|
|
{
|
|
CultureInfo.CurrentCulture = originalCulture;
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Debug triggers
|
|
|
|
[Fact]
|
|
public void TriggerLimitBreach_WhenNotActive_ShouldEnforceRegardlessOfPower()
|
|
{
|
|
// Arrange
|
|
var sut = CreateSut();
|
|
|
|
// Act
|
|
sut.TriggerLimitBreach();
|
|
|
|
// Assert
|
|
sut.IsLimitActive.Should().BeTrue();
|
|
_haContextMock.Verify(
|
|
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
|
Times.Exactly(3));
|
|
VerifyTurnOff(BoilerSwitch, 1);
|
|
VerifyTurnOff(AutoManagement, 1);
|
|
VerifyNotificationCreated(1);
|
|
}
|
|
|
|
[Fact]
|
|
public void TriggerLimitBreach_WhenAlreadyActive_ShouldDoNothing()
|
|
{
|
|
// Arrange
|
|
var sut = CreateSut();
|
|
sut.TriggerLimitBreach();
|
|
_haContextMock.Invocations.Clear();
|
|
|
|
// Act
|
|
sut.TriggerLimitBreach();
|
|
|
|
// Assert
|
|
VerifyNoServiceCalls();
|
|
}
|
|
|
|
[Fact]
|
|
public void ResetLimitBreach_WhenActive_ShouldRecoverWithoutWaiting()
|
|
{
|
|
// Arrange
|
|
var sut = CreateSut();
|
|
sut.TriggerLimitBreach();
|
|
_haContextMock.Invocations.Clear();
|
|
|
|
// Act
|
|
sut.ResetLimitBreach();
|
|
|
|
// Assert
|
|
sut.IsLimitActive.Should().BeFalse();
|
|
VerifyTurnOn(AutoManagement, 1);
|
|
VerifyTurnOn(BoilerSwitch, 0);
|
|
VerifyNotificationDismissed(1);
|
|
}
|
|
|
|
[Fact]
|
|
public void ResetLimitBreach_WhenNotActive_ShouldDoNothing()
|
|
{
|
|
// Arrange
|
|
var sut = CreateSut();
|
|
|
|
// Act
|
|
sut.ResetLimitBreach();
|
|
|
|
// Assert
|
|
VerifyNoServiceCalls();
|
|
}
|
|
|
|
[Fact]
|
|
public void TriggerLimitBreach_WhenDisabled_ShouldStillEnforce()
|
|
{
|
|
// Arrange
|
|
_options.EnforceLimitEnabled = false;
|
|
var sut = CreateSut();
|
|
|
|
// Act
|
|
sut.TriggerLimitBreach();
|
|
|
|
// Assert
|
|
sut.IsLimitActive.Should().BeTrue("debug trigger bypasses EnforceLimitEnabled so the button always works");
|
|
VerifyTurnOff(BoilerSwitch, 1);
|
|
VerifyNotificationCreated(1);
|
|
}
|
|
|
|
#endregion
|
|
}
|