Add shared test data builders and Qodana configuration

- Extract per-monitor *TestData helper classes and rework tests to use them
- Add boiler run-time tracker abstraction (implementation pending)
- Drop unused NordPool init/update-result types and stale PLAN.md
- Add qodana.yaml with the inspection set to keep the analysis focused
This commit is contained in:
2026-11-29 21:30:13 +02:00
parent 1152462765
commit 5777e641f6
79 changed files with 7162 additions and 3196 deletions
@@ -8,13 +8,9 @@ namespace BoilerMonitor.Manager.Tests;
public class BoilerControlServiceTests
{
private readonly BoilerControlService _sut;
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new();
public BoilerControlServiceTests()
{
var loggerMock = new Mock<ILogger<BoilerControlService>>();
_sut = new BoilerControlService(loggerMock.Object);
}
private BoilerControlService CreateSut() => new(_loggerMock.Object);
#region TurnOn scenarios
@@ -23,10 +19,15 @@ public class BoilerControlServiceTests
[InlineData("OFF")]
[InlineData("Off")]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("off ")]
[InlineData("unavailable")]
[InlineData("unknown")]
[InlineData("0")]
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
{
var result = _sut.DetermineAction(
var result = CreateSut().DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
budgetExhausted: false, budgetOverride: false);
@@ -34,60 +35,53 @@ public class BoilerControlServiceTests
}
[Theory]
[InlineData("off")]
[InlineData(null)]
public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOn(string? switchState)
[InlineData("off", BoilerAction.TurnOn)]
[InlineData(null, BoilerAction.TurnOn)]
[InlineData("unavailable", BoilerAction.TurnOn)]
[InlineData("on", BoilerAction.NoChange)]
[InlineData("On", BoilerAction.NoChange)]
[InlineData("ON", BoilerAction.NoChange)]
public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOnOnlyIfNotAlreadyOn(
string? switchState,
BoilerAction expectedAction)
{
var result = _sut.DetermineAction(
var result = CreateSut().DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
budgetExhausted: true, budgetOverride: true);
result.Should().Be(BoilerAction.TurnOn);
result.Should().Be(expectedAction);
}
#endregion
#region TurnOff scenarios
[Fact]
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff()
[Theory]
[InlineData("on")]
[InlineData("ON")]
[InlineData("On")]
[InlineData("oN")]
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
{
var result = _sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: "on",
var result = CreateSut().DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: switchState,
budgetExhausted: false, budgetOverride: false);
result.Should().Be(BoilerAction.TurnOff);
}
[Fact]
public void DetermineAction_WhenWaterReadyAndSwitchIsOn_ShouldReturnTurnOff()
{
var result = _sut.DetermineAction(
isNowCheap: true, waterReady: true, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
result.Should().Be(BoilerAction.TurnOff);
}
[Fact]
public void DetermineAction_WhenBudgetExhaustedAndNoOverride_ShouldReturnTurnOff()
{
var result = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "on",
budgetExhausted: true, budgetOverride: false);
result.Should().Be(BoilerAction.TurnOff);
}
[Theory]
[InlineData("on")]
[InlineData("ON")]
[InlineData("On")]
public void DetermineAction_WhenNotCheapAndSwitchIsOnCaseInsensitive_ShouldReturnTurnOff(string switchState)
[InlineData(true, false, false)] // water ready
[InlineData(false, true, false)] // budget exhausted, no override
[InlineData(true, true, true)] // water ready wins over the budget override
public void DetermineAction_WhenCheapButShouldNotHeatAndSwitchIsOn_ShouldReturnTurnOff(
bool waterReady,
bool budgetExhausted,
bool budgetOverride)
{
var result = _sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: switchState,
budgetExhausted: false, budgetOverride: false);
var result = CreateSut().DetermineAction(
isNowCheap: true, waterReady: waterReady, currentSwitchState: "on",
budgetExhausted: budgetExhausted, budgetOverride: budgetOverride);
result.Should().Be(BoilerAction.TurnOff);
}
@@ -96,56 +90,107 @@ public class BoilerControlServiceTests
#region NoChange scenarios
[Fact]
public void DetermineAction_WhenCheapAndNotReadyAndAlreadyOn_ShouldReturnNoChange()
[Theory]
[InlineData(true, false, "on", false, false)]
[InlineData(false, false, "off", false, false)]
[InlineData(false, false, null, false, false)]
[InlineData(false, false, "unavailable", false, false)]
[InlineData(true, true, "off", false, false)]
[InlineData(true, true, null, false, false)]
[InlineData(true, false, "off", true, false)]
[InlineData(true, false, "off ", true, false)]
[InlineData(true, true, "off", true, true)]
public void DetermineAction_WhenDesiredStateMatchesCurrentState_ShouldReturnNoChange(
bool isNowCheap,
bool waterReady,
string? switchState,
bool budgetExhausted,
bool budgetOverride)
{
var result = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
result.Should().Be(BoilerAction.NoChange);
}
[Fact]
public void DetermineAction_WhenNotCheapAndAlreadyOff_ShouldReturnNoChange()
{
var result = _sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: "off",
budgetExhausted: false, budgetOverride: false);
result.Should().Be(BoilerAction.NoChange);
}
[Fact]
public void DetermineAction_WhenBudgetExhaustedAndAlreadyOff_ShouldReturnNoChange()
{
var result = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "off",
budgetExhausted: true, budgetOverride: false);
var result = CreateSut().DetermineAction(
isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
result.Should().Be(BoilerAction.NoChange);
}
#endregion
#region Comprehensive theory covering all key combinations
#region Comprehensive truth tables
/// <summary>
/// Complete truth table for a boiler that is currently ON: it may only stay on when
/// it is cheap, water is not ready and the budget is available (or overridden).
/// </summary>
public static IEnumerable<object[]> SwitchOnActionMatrix =>
[
[false, false, false, false, BoilerAction.TurnOff],
[false, false, false, true, BoilerAction.TurnOff],
[false, false, true, false, BoilerAction.TurnOff],
[false, false, true, true, BoilerAction.TurnOff],
[false, true, false, false, BoilerAction.TurnOff],
[false, true, false, true, BoilerAction.TurnOff],
[false, true, true, false, BoilerAction.TurnOff],
[false, true, true, true, BoilerAction.TurnOff],
[true, false, false, false, BoilerAction.NoChange],
[true, false, false, true, BoilerAction.NoChange],
[true, false, true, false, BoilerAction.TurnOff],
[true, false, true, true, BoilerAction.NoChange],
[true, true, false, false, BoilerAction.TurnOff],
[true, true, false, true, BoilerAction.TurnOff],
[true, true, true, false, BoilerAction.TurnOff],
[true, true, true, true, BoilerAction.TurnOff]
];
[Theory]
[InlineData(true, false, "off", false, false, BoilerAction.TurnOn)]
[InlineData(true, false, "on", false, false, BoilerAction.NoChange)]
[InlineData(true, true, "on", false, false, BoilerAction.TurnOff)]
[InlineData(true, true, "off", false, false, BoilerAction.NoChange)]
[InlineData(false, false, "on", false, false, BoilerAction.TurnOff)]
[InlineData(false, false, "off", false, false, BoilerAction.NoChange)]
[InlineData(true, false, "on", true, false, BoilerAction.TurnOff)]
[InlineData(true, false, "off", true, false, BoilerAction.NoChange)]
[InlineData(true, false, "off", true, true, BoilerAction.TurnOn)]
[InlineData(true, false, "on", true, true, BoilerAction.NoChange)]
public void DetermineAction_AllCombinations_ShouldReturnExpectedAction(
bool isNowCheap, bool waterReady, string switchState,
bool budgetExhausted, bool budgetOverride, BoilerAction expectedAction)
[MemberData(nameof(SwitchOnActionMatrix))]
public void DetermineAction_AllCombinationsWhileSwitchIsOn_ShouldReturnExpectedAction(
bool isNowCheap,
bool waterReady,
bool budgetExhausted,
bool budgetOverride,
BoilerAction expectedAction)
{
var result = _sut.DetermineAction(isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
var result = CreateSut().DetermineAction(
isNowCheap, waterReady, currentSwitchState: "on", budgetExhausted, budgetOverride);
result.Should().Be(expectedAction);
}
/// <summary>
/// Complete truth table for a boiler that is currently OFF: it may only turn on when
/// it is cheap, water is not ready and the budget is available (or overridden).
/// </summary>
public static IEnumerable<object[]> SwitchOffActionMatrix =>
[
[false, false, false, false, BoilerAction.NoChange],
[false, false, false, true, BoilerAction.NoChange],
[false, false, true, false, BoilerAction.NoChange],
[false, false, true, true, BoilerAction.NoChange],
[false, true, false, false, BoilerAction.NoChange],
[false, true, false, true, BoilerAction.NoChange],
[false, true, true, false, BoilerAction.NoChange],
[false, true, true, true, BoilerAction.NoChange],
[true, false, false, false, BoilerAction.TurnOn],
[true, false, false, true, BoilerAction.TurnOn],
[true, false, true, false, BoilerAction.NoChange],
[true, false, true, true, BoilerAction.TurnOn],
[true, true, false, false, BoilerAction.NoChange],
[true, true, false, true, BoilerAction.NoChange],
[true, true, true, false, BoilerAction.NoChange],
[true, true, true, true, BoilerAction.NoChange]
];
[Theory]
[MemberData(nameof(SwitchOffActionMatrix))]
public void DetermineAction_AllCombinationsWhileSwitchIsOff_ShouldReturnExpectedAction(
bool isNowCheap,
bool waterReady,
bool budgetExhausted,
bool budgetOverride,
BoilerAction expectedAction)
{
var result = CreateSut().DetermineAction(
isNowCheap, waterReady, currentSwitchState: "off", budgetExhausted, budgetOverride);
result.Should().Be(expectedAction);
}
@@ -8,22 +8,22 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="8.0.0">
<PackageReference Include="coverlet.collector" Version="10.1.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.4.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="11.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<PackageReference Include="System.Reactive" Version="6.1.0" />
<PackageReference Include="FluentAssertions" Version="8.11.0" />
<PackageReference Include="Moq" Version="4.21.0" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1" />
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1" />
<PackageReference Include="System.Reactive" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
@@ -5,129 +5,67 @@ namespace BoilerMonitor.Manager.Tests;
public class BoilerMonitorConfigTests
{
[Fact]
public void IsFullyConfigured_WhenAllFieldsSet_ShouldReturnTrue()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId;
private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId;
config.IsFullyConfigured.Should().BeTrue();
public static IEnumerable<object?[]> ConfigurationCases =>
[
["fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true],
["minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true],
["poll interval of one second", PowerEntityId, SwitchEntityId, 1, 5.0, true],
["maximum poll interval", PowerEntityId, SwitchEntityId, int.MaxValue, 5.0, true],
["smallest positive threshold", PowerEntityId, SwitchEntityId, 30, double.Epsilon, true],
["maximum threshold", PowerEntityId, SwitchEntityId, 30, double.MaxValue, true],
["infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true],
["power entity id null", (string?)null, SwitchEntityId, 30, 5.0, false],
["power entity id empty", "", SwitchEntityId, 30, 5.0, false],
["power entity id whitespace", " ", SwitchEntityId, 30, 5.0, false],
["power entity id tabs and newlines", "\t\n", SwitchEntityId, 30, 5.0, false],
["switch entity id null", PowerEntityId, (string?)null, 30, 5.0, false],
["switch entity id empty", PowerEntityId, "", 30, 5.0, false],
["switch entity id whitespace", PowerEntityId, " ", 30, 5.0, false],
["both entity ids null", (string?)null, (string?)null, 30, 5.0, false],
["poll interval null", PowerEntityId, SwitchEntityId, (int?)null, 5.0, false],
["poll interval zero", PowerEntityId, SwitchEntityId, 0, 5.0, false],
["poll interval negative", PowerEntityId, SwitchEntityId, -1, 5.0, false],
["poll interval minimum value", PowerEntityId, SwitchEntityId, int.MinValue, 5.0, false],
["threshold null", PowerEntityId, SwitchEntityId, 30, (double?)null, false],
["threshold zero", PowerEntityId, SwitchEntityId, 30, 0.0, false],
["threshold negative", PowerEntityId, SwitchEntityId, 30, -1.0, false],
["threshold minimum value", PowerEntityId, SwitchEntityId, 30, double.MinValue, false],
["threshold NaN", PowerEntityId, SwitchEntityId, 30, double.NaN, false],
["threshold negative infinity", PowerEntityId, SwitchEntityId, 30, double.NegativeInfinity, false]
];
[Theory]
[MemberData(nameof(ConfigurationCases))]
public void IsFullyConfigured_ShouldValidateEveryRequiredField(
string scenario,
string? powerEntityId,
string? switchEntityId,
int? pollIntervalSeconds,
double? heatingPowerThresholdWatts,
bool expected)
{
var config = BoilerMonitorTestData.CreateConfig(
boilerPowerEntityId: powerEntityId,
boilerSwitchEntityId: switchEntityId,
pollIntervalSeconds: pollIntervalSeconds,
heatingPowerThresholdWatts: heatingPowerThresholdWatts);
config.IsFullyConfigured.Should().Be(expected, scenario);
}
[Fact]
public void IsFullyConfigured_WhenPowerEntityMissing_ShouldReturnFalse()
public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = null,
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
var config = BoilerMonitorTestData.CreateConfig(
boilerPowerEntityId: " sensor.sonoff_1002230e32_power ",
boilerSwitchEntityId: "SWITCH.SONOFF_1002230E32");
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenSwitchEntityMissing_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = null,
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenPollIntervalMissing_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = null,
HeatingPowerThresholdWatts = 5.0
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenThresholdMissing_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = null
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenPowerEntityIsWhitespace_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = " ",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenPollIntervalIsZero_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 0,
HeatingPowerThresholdWatts = 5.0
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenThresholdIsZero_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 0.0
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenPollIntervalIsNegative_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = -1,
HeatingPowerThresholdWatts = 5.0
};
config.IsFullyConfigured.Should().BeFalse();
config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content");
}
}
@@ -1,283 +1,436 @@
using System.Text.Json;
using BoilerMonitorManager;
using FluentAssertions;
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.Models;
using Microsoft.Extensions.Logging;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts;
namespace BoilerMonitor.Manager.Tests;
public class BoilerMonitorEntityServiceTests
{
private readonly Mock<IEntityManager> _entityManagerMock;
private readonly Mock<IHaContext> _haContextMock;
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock;
private readonly BoilerMonitorEntityService _sut;
/// <summary>Every entity that <c>CleanupEntitiesAsync</c> is expected to remove.</summary>
private static readonly string[] CleanableEntityIds =
[
ConfigPowerEntityId,
ConfigSwitchEntityId,
ConfigPollIntervalEntityId,
ConfigHeatingThresholdEntityId,
StatusEntityId,
WaterReadyEntityId,
SkipPriceCapEntityId,
TodayRuntimeEntityId,
RemainingTimeEntityId,
BudgetPercentageEntityId,
BudgetExhaustedEntityId,
SessionCountEntityId,
BudgetOverrideEntityId,
AutoManagementEntityId
];
private readonly Mock<IEntityManager> _entityManagerMock = new();
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new();
public BoilerMonitorEntityServiceTests()
{
_entityManagerMock = new Mock<IEntityManager>();
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
_sut = new BoilerMonitorEntityService(
_entityManagerMock.Object,
_haContextMock.Object,
_loggerMock.Object);
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
}
private void SetupEntityState(string entityId, string? state)
{
if (state is null)
{
_haContextMock.Setup(h => h.GetState(entityId)).Returns((EntityState?)null);
}
else
{
_haContextMock.Setup(h => h.GetState(entityId))
.Returns(new EntityState { State = state });
}
}
private BoilerMonitorEntityService CreateSut() => new(
_entityManagerMock.Object,
_haContextMock.Object,
_loggerMock.Object);
#region ReadPersistedState
[Theory]
[MemberData(nameof(BoilerMonitorTestData.RuntimeStateSamples), MemberType = typeof(BoilerMonitorTestData))]
public void ReadPersistedState_WhenRuntimeStateVaries_ShouldParseOrReject(
string? runtimeState,
TimeSpan? expectedRunTime)
{
_haContextMock.SetupEntityStates(
BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: runtimeState, sessionCount: "2"));
var result = CreateSut().ReadPersistedState();
if (expectedRunTime is null)
{
result.Should().BeNull();
return;
}
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(expectedRunTime.Value);
result.SessionCount.Should().Be(2);
}
[Theory]
[MemberData(nameof(BoilerMonitorTestData.SessionCountStateSamples), MemberType = typeof(BoilerMonitorTestData))]
public void ReadPersistedState_WhenSessionCountStateVaries_ShouldParseOrReject(
string? sessionCountState,
int? expectedSessionCount)
{
_haContextMock.SetupEntityStates(
BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: "3600", sessionCount: sessionCountState));
var result = CreateSut().ReadPersistedState();
if (expectedSessionCount is null)
{
result.Should().BeNull();
return;
}
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(1));
result.SessionCount.Should().Be(expectedSessionCount.Value);
}
[Fact]
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "7200");
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SkipPriceCapEntityId, "ON");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
todayRuntime: "7200", sessionCount: "3", skipPriceCap: "ON", budgetOverride: "OFF"));
// Act
var result = _sut.ReadPersistedState();
var result = CreateSut().ReadPersistedState();
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(7200));
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(2));
result.SessionCount.Should().Be(3);
result.SkipPriceCapState.Should().Be("ON");
result.BudgetOverrideState.Should().Be("OFF");
}
[Fact]
public void ReadPersistedState_WithZeroRuntime_ShouldReturnZeroValues()
[Theory]
[InlineData("ON")]
[InlineData("on")]
[InlineData(" On ")]
[InlineData("")]
[InlineData(null)]
public void ReadPersistedState_ShouldReturnRawSwitchStates(string? switchState)
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "0");
SetupEntityState(SessionCountEntityId, "0");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
skipPriceCap: switchState, budgetOverride: switchState));
// Act
var result = _sut.ReadPersistedState();
var result = CreateSut().ReadPersistedState();
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
result.SessionCount.Should().Be(0);
result!.SkipPriceCapState.Should().Be(switchState);
result.BudgetOverrideState.Should().Be(switchState);
}
[Fact]
public void ReadPersistedState_WhenRuntimeIsUnavailable_ShouldReturnNull()
public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "unavailable");
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityStates(
BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: null, sessionCount: null));
// Act
var result = _sut.ReadPersistedState();
CreateSut().ReadPersistedState().Should().BeNull();
}
// Assert
result.Should().BeNull();
#endregion
#region ReadPersistedCooldownTimestamp
[Fact]
public void ReadPersistedCooldownTimestamp_WithValidIsoString_ShouldReturnTimestamp()
{
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(30);
_haContextMock.SetupEntityState(
WaterReadyEntityId,
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O")));
var result = CreateSut().ReadPersistedCooldownTimestamp();
result.Should().Be(cooldownSince);
}
[Fact]
public void ReadPersistedState_WhenRuntimeIsUnknown_ShouldReturnNull()
public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "unknown");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero);
_haContextMock.SetupEntityState(
WaterReadyEntityId,
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
// Act
var result = _sut.ReadPersistedState();
var result = CreateSut().ReadPersistedCooldownTimestamp();
// Assert
result.Should().BeNull();
result.Should().Be(cooldownSince);
}
[Fact]
public void ReadPersistedState_WhenSessionCountIsUnavailable_ShouldReturnNull()
public void ReadPersistedCooldownTimestamp_WhenEntityDoesNotExist_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, "unavailable");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityState(WaterReadyEntityId, null);
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenRuntimeEntityDoesNotExist_ShouldReturnNull()
public void ReadPersistedCooldownTimestamp_WhenEntityHasNoAttributes_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, null);
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityState(WaterReadyEntityId, BoilerMonitorTestData.CreateEntityState("yes"));
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenSessionCountEntityDoesNotExist_ShouldReturnNull()
public void ReadPersistedCooldownTimestamp_WhenAttributeIsMissing_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, null);
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityState(
WaterReadyEntityId,
BoilerMonitorTestData.CreateEntityStateWithAttributes(
new Dictionary<string, object?> { ["friendly_name"] = "Boiler water ready" }));
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenRuntimeIsNonNumeric_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "not_a_number");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenSessionCountIsNonNumeric_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, "abc");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenRuntimeIsNegative_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "-100");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenSessionCountIsNegative_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, "-1");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenSwitchEntitiesAreNull_ShouldStillReturnWithNullSwitchStates()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "1800");
SetupEntityState(SessionCountEntityId, "1");
SetupEntityState(SkipPriceCapEntityId, null);
SetupEntityState(BudgetOverrideEntityId, null);
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800));
result.SessionCount.Should().Be(1);
result.SkipPriceCapState.Should().BeNull();
result.BudgetOverrideState.Should().BeNull();
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
}
[Theory]
[InlineData("")] // empty string
[InlineData(" ")] // whitespace
public void ReadPersistedState_WhenRuntimeIsEmptyOrWhitespace_ShouldReturnNull(string state)
[InlineData(null)]
[InlineData(42)]
[InlineData(true)]
[InlineData("")]
[InlineData(" ")]
[InlineData("not-a-timestamp")]
[InlineData("2026-13-45T99:99:99")]
[InlineData("unavailable")]
public void ReadPersistedCooldownTimestamp_WhenAttributeIsNotAValidTimestamp_ShouldReturnNull(object? cooldownSince)
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, state);
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityState(
WaterReadyEntityId,
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince));
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
}
[Fact]
public void ReadPersistedState_WithDecimalRuntime_ShouldParseCorrectly()
public void ReadPersistedCooldownTimestamp_WhenHaContextThrows_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "134.66");
SetupEntityState(SessionCountEntityId, "1");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.Setup(h => h.GetState(WaterReadyEntityId))
.Throws(new InvalidOperationException("Home Assistant unavailable"));
// Act
var result = _sut.ReadPersistedState();
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
}
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(134.66));
result.SessionCount.Should().Be(1);
#endregion
#region UpdateEntitiesAsync
[Theory]
[InlineData(true, "yes")]
[InlineData(false, "no")]
public async Task UpdateEntitiesAsync_ShouldWriteWaterReadyState(bool waterReady, string expectedState)
{
await CreateSut().UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(waterReady: waterReady));
_entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, expectedState), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting()
{
var context = BoilerMonitorTestData.CreateUpdateContext(
todayRunTime: TimeSpan.FromSeconds(3723.9),
remainingTime: TimeSpan.FromSeconds(42.9),
budgetPercentage: 150.0,
budgetExhausted: true,
sessionCount: 4,
waterReady: true);
await CreateSut().UpdateEntitiesAsync(context);
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusConfigured), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, "3723"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, "42"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, "100"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, "on"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, "4"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Exactly(5));
}
[Theory]
[InlineData(-0.1, "0")]
[InlineData(0.0, "0")]
[InlineData(49.9, "49")]
[InlineData(99.999, "99")]
[InlineData(100.0, "100")]
[InlineData(100.1, "100")]
[InlineData(1_000.0, "100")]
public async Task UpdateEntitiesAsync_ShouldClampAndTruncateBudgetPercentage(
double budgetPercentage,
string expectedState)
{
await CreateSut().UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage));
_entityManagerMock.Verify(
em => em.SetEntityState(BudgetPercentageEntityId, expectedState), Times.Once);
}
[Theory]
[InlineData(-60, "0")]
[InlineData(0, "0")]
[InlineData(1, "1")]
[InlineData(59, "59")]
[InlineData(3600, "3600")]
public async Task UpdateEntitiesAsync_ShouldClampAndTruncateRemainingTime(int seconds, string expectedState)
{
await CreateSut().UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds)));
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, expectedState), Times.Once);
}
[Theory]
[InlineData(0.0, "0")]
[InlineData(0.9, "0")]
[InlineData(59.9, "59")]
[InlineData(60.0, "60")]
[InlineData(86_400.0, "86400")]
public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState)
{
await CreateSut().UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(todayRunTime: TimeSpan.FromSeconds(seconds)));
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WhenSwitchStateIsNull_ShouldWriteUnknownWaterReadyAttributes()
{
object? capturedAttributes = null;
_entityManagerMock
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
.Callback<string, object>((_, attributes) => capturedAttributes = attributes)
.Returns(Task.CompletedTask);
await CreateSut().UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(
waterReady: false,
boilerSwitchState: null,
boilerPowerWatts: 1234.5));
capturedAttributes.Should().NotBeNull();
var attributes = JsonSerializer.SerializeToElement(capturedAttributes!);
attributes.GetProperty("boiler_switch_state").GetString().Should().Be("unknown");
attributes.GetProperty("boiler_power_watts").GetDouble().Should().Be(1234.5);
attributes.GetProperty("cooldown_since").ValueKind.Should().Be(JsonValueKind.Null);
attributes.GetProperty("last_updated").GetString().Should().NotBeNullOrEmpty();
}
[Fact]
public async Task UpdateEntitiesAsync_WhenCooldownIsActive_ShouldSerializeCooldownTimestamp()
{
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(15);
object? capturedAttributes = null;
_entityManagerMock
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
.Callback<string, object>((_, attributes) => capturedAttributes = attributes)
.Returns(Task.CompletedTask);
await CreateSut().UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(cooldownSince: cooldownSince));
var attributes = JsonSerializer.SerializeToElement(capturedAttributes!);
attributes.GetProperty("cooldown_since").GetString().Should().Be(cooldownSince.ToString("O"));
}
#endregion
#region CreateEntitiesAsync
[Fact]
public async Task CreateEntitiesAsync_ShouldCreateEveryBoilerMonitorEntityOnce()
{
var createdEntityIds = new List<string?>();
_entityManagerMock
.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
.Callback<EntityCreateModel>(entity => createdEntityIds.Add(entity.EntityId))
.Returns(Task.CompletedTask);
await CreateSut().CreateEntitiesAsync();
createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems();
createdEntityIds.Should().Contain(new[]
{
ConfigPowerEntityId,
ConfigSwitchEntityId,
ConfigPollIntervalEntityId,
ConfigHeatingThresholdEntityId,
CleanupButtonEntityId,
WaterReadyEntityId,
TodayRuntimeEntityId,
BudgetExhaustedEntityId,
AutoManagementEntityId
});
}
[Fact]
public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldStillAttemptEveryEntity()
{
_entityManagerMock
.Setup(em => em.CreateEntityAsync(It.Is<EntityCreateModel>(
entity => entity.EntityId == CleanupButtonEntityId)))
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
var act = () => CreateSut().CreateEntitiesAsync();
await act.Should().NotThrowAsync();
_entityManagerMock.Invocations
.Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync))
.Should().Be(15);
}
#endregion
#region ResetEntitiesAsync
public static TheoryData<string, string> ResetEntityStates => new()
{
{ StatusEntityId, StatusAwaitingConfiguration },
{ WaterReadyEntityId, "unknown" },
{ SkipPriceCapEntityId, "OFF" },
{ TodayRuntimeEntityId, "0" },
{ RemainingTimeEntityId, "0" },
{ BudgetPercentageEntityId, "0" },
{ BudgetExhaustedEntityId, "off" },
{ SessionCountEntityId, "0" },
{ BudgetOverrideEntityId, "OFF" },
{ AutoManagementEntityId, "ON" }
};
[Theory]
[MemberData(nameof(ResetEntityStates))]
public async Task ResetEntitiesAsync_ShouldWriteExpectedDefaultState(string entityId, string expectedState)
{
await CreateSut().ResetEntitiesAsync();
_entityManagerMock.Verify(em => em.SetEntityState(entityId, expectedState), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(10));
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Exactly(5));
}
[Fact]
public async Task ResetEntitiesAsync_WhenEntityManagerThrows_ShouldNotThrow()
{
_entityManagerMock
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
var act = () => CreateSut().ResetEntitiesAsync();
await act.Should().NotThrowAsync();
}
#endregion
@@ -287,55 +440,111 @@ public class BoilerMonitorEntityServiceTests
[Fact]
public async Task ResetTransientEntitiesAsync_ShouldResetStatusAndWaterReady()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
await CreateSut().ResetTransientEntitiesAsync();
// Act
await _sut.ResetTransientEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusAwaitingConfiguration), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, "unknown"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()), Times.Once);
}
public static TheoryData<string> UntouchedByTransientResetEntityIds => new()
{
TodayRuntimeEntityId,
SessionCountEntityId,
BudgetPercentageEntityId,
BudgetExhaustedEntityId,
RemainingTimeEntityId,
SkipPriceCapEntityId,
BudgetOverrideEntityId,
AutoManagementEntityId,
ConfigPowerEntityId,
ConfigSwitchEntityId
};
[Theory]
[MemberData(nameof(UntouchedByTransientResetEntityIds))]
public async Task ResetTransientEntitiesAsync_ShouldNotResetPersistentOrSwitchEntities(string entityId)
{
await CreateSut().ResetTransientEntitiesAsync();
_entityManagerMock.Verify(em => em.SetEntityState(entityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityAttributes(entityId, It.IsAny<object>()), Times.Never);
}
#endregion
#region CleanupEntitiesAsync
[Fact]
public async Task CleanupEntitiesAsync_ShouldRemoveEveryEntityExceptCleanupButton()
{
await CreateSut().CleanupEntitiesAsync();
foreach (var entityId in CleanableEntityIds)
{
_entityManagerMock.Verify(em => em.RemoveEntity(entityId), Times.Once);
}
_entityManagerMock.Verify(em => em.RemoveEntity(CleanupButtonEntityId), Times.Never);
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(CleanableEntityIds.Length));
}
[Fact]
public async Task ResetTransientEntitiesAsync_ShouldNotResetRuntimeEntities()
public async Task CleanupEntitiesAsync_WhenRemoveFails_ShouldRethrow()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
_entityManagerMock
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Throws(new InvalidOperationException("MQTT unavailable"));
// Act
await _sut.ResetTransientEntitiesAsync();
var act = () => CreateSut().CleanupEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, It.IsAny<string>()), Times.Never);
await act.Should().ThrowAsync<InvalidOperationException>();
}
#endregion
#region SetStatusAsync and cancellation
[Fact]
public async Task ResetTransientEntitiesAsync_ShouldNotResetSwitchEntities()
public async Task SetStatusAsync_ShouldWriteStatusEntity()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
await CreateSut().SetStatusAsync(StatusConfigured);
// Act
await _sut.ResetTransientEntitiesAsync();
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusConfigured), Times.Once);
}
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(SkipPriceCapEntityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(BudgetOverrideEntityId, It.IsAny<string>()), Times.Never);
public enum CancelableOperation
{
CreateEntities,
ResetEntities,
UpdateEntities,
ResetTransientEntities,
CleanupEntities
}
[Theory]
[InlineData(CancelableOperation.CreateEntities)]
[InlineData(CancelableOperation.ResetEntities)]
[InlineData(CancelableOperation.UpdateEntities)]
[InlineData(CancelableOperation.ResetTransientEntities)]
[InlineData(CancelableOperation.CleanupEntities)]
public async Task Operation_WhenCancellationIsAlreadyRequested_ShouldThrowAndNotTouchEntityManager(
CancelableOperation operation)
{
var canceledToken = new CancellationToken(canceled: true);
var sut = CreateSut();
Func<Task> act = operation switch
{
CancelableOperation.CreateEntities => () => sut.CreateEntitiesAsync(canceledToken),
CancelableOperation.ResetEntities => () => sut.ResetEntitiesAsync(canceledToken),
CancelableOperation.UpdateEntities => () => sut.UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(), canceledToken),
CancelableOperation.ResetTransientEntities => () => sut.ResetTransientEntitiesAsync(canceledToken),
_ => () => sut.CleanupEntitiesAsync(canceledToken)
};
await act.Should().ThrowAsync<OperationCanceledException>();
_entityManagerMock.Invocations.Should().BeEmpty();
}
#endregion
@@ -13,17 +13,47 @@ public class BoilerMonitorOptionsTests
options.Enabled.Should().BeTrue();
}
[Fact]
public void Defaults_ShouldHaveCleanupEntitiesOnStartupTrue()
{
var options = new BoilerMonitorOptions();
options.CleanupEntitiesOnStartup.Should().BeTrue();
}
[Fact]
public void SectionName_ShouldBeBoilerMonitor()
{
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
}
[Fact]
public void Enabled_WhenSetToFalse_ShouldReturnFalse()
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Enabled_WhenSet_ShouldReturnConfiguredValue(bool enabled)
{
var options = new BoilerMonitorOptions { Enabled = false };
var options = BoilerMonitorTestData.CreateOptions(enabled: enabled);
options.Enabled.Should().Be(enabled);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void CleanupEntitiesOnStartup_WhenSet_ShouldReturnConfiguredValue(bool cleanupEntitiesOnStartup)
{
var options = BoilerMonitorTestData.CreateOptions(cleanupEntitiesOnStartup: cleanupEntitiesOnStartup);
options.CleanupEntitiesOnStartup.Should().Be(cleanupEntitiesOnStartup);
}
[Fact]
public void Options_WhenBothFlagsDisabled_ShouldPreserveEachValueIndependently()
{
var options = BoilerMonitorTestData.CreateOptions(enabled: false, cleanupEntitiesOnStartup: false);
options.Enabled.Should().BeFalse();
options.CleanupEntitiesOnStartup.Should().BeFalse();
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
}
}
@@ -0,0 +1,271 @@
using System.Text.Json;
using BoilerMonitor.Models;
using BoilerMonitorManager.Models;
using Microsoft.Extensions.Time.Testing;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts;
namespace BoilerMonitor.Manager.Tests;
/// <summary>
/// Shared, deterministic fixtures used by the BoilerMonitor tests: config/options builders,
/// entity-state sets, parse samples and a fixed clock. Keeping them here avoids copy-pasted
/// setup and makes every timestamp/DST assertion independent of the real clock.
/// </summary>
internal static class BoilerMonitorTestData
{
public const string PowerEntityId = "sensor.sonoff_1002230e32_power";
public const string SwitchEntityId = "switch.sonoff_1002230e32";
/// <summary>Fixed "now" (UTC) used by every time based test.</summary>
public static readonly DateTimeOffset BaseTime = new(2026, 3, 31, 12, 0, 0, TimeSpan.Zero);
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null) =>
new(utcNow ?? BaseTime);
public static BoilerMonitorConfig CreateConfig(
string? boilerPowerEntityId = PowerEntityId,
string? boilerSwitchEntityId = SwitchEntityId,
int? pollIntervalSeconds = DefaultPollIntervalSeconds,
double? heatingPowerThresholdWatts = DefaultHeatingPowerThresholdWatts) =>
new()
{
BoilerPowerEntityId = boilerPowerEntityId,
BoilerSwitchEntityId = boilerSwitchEntityId,
PollIntervalSeconds = pollIntervalSeconds,
HeatingPowerThresholdWatts = heatingPowerThresholdWatts
};
public static BoilerMonitorOptions CreateOptions(
bool enabled = true,
bool cleanupEntitiesOnStartup = true) =>
new()
{
Enabled = enabled,
CleanupEntitiesOnStartup = cleanupEntitiesOnStartup
};
public static PersistedBoilerState CreatePersistedState(
TimeSpan? accumulatedRunTime = null,
int sessionCount = 3,
string? skipPriceCapState = "ON",
string? budgetOverrideState = "OFF") =>
new()
{
AccumulatedRunTime = accumulatedRunTime ?? TimeSpan.FromHours(2),
SessionCount = sessionCount,
SkipPriceCapState = skipPriceCapState,
BudgetOverrideState = budgetOverrideState
};
public static BoilerMonitorUpdateContext CreateUpdateContext(
TimeSpan? todayRunTime = null,
TimeSpan? remainingTime = null,
double budgetPercentage = 50.0,
bool budgetExhausted = false,
int sessionCount = 1,
double budgetHours = 2.0,
bool waterReady = false,
string? boilerSwitchState = "on",
double? boilerPowerWatts = 0.0,
DateTimeOffset? cooldownSince = null,
bool isNowCheap = true) =>
new()
{
TodayRunTime = todayRunTime ?? TimeSpan.FromHours(1),
RemainingTime = remainingTime ?? TimeSpan.FromHours(1),
BudgetPercentage = budgetPercentage,
BudgetExhausted = budgetExhausted,
SessionCount = sessionCount,
BudgetHours = budgetHours,
IsCurrentlyHeating = false,
WaterReady = waterReady,
BoilerSwitchState = boilerSwitchState,
BoilerPowerWatts = boilerPowerWatts,
CooldownSince = cooldownSince,
IsNowCheap = isNowCheap,
NextCheapIntervalStart = null
};
/// <summary>
/// The four entity states <c>ReadPersistedState</c> reads, with valid defaults.
/// A null value means the entity does not exist in Home Assistant.
/// </summary>
public static Dictionary<string, string?> CreatePersistedEntityStates(
string? todayRuntime = "7200",
string? sessionCount = "3",
string? skipPriceCap = "OFF",
string? budgetOverride = "OFF") =>
new()
{
[TodayRuntimeEntityId] = todayRuntime,
[SessionCountEntityId] = sessionCount,
[SkipPriceCapEntityId] = skipPriceCap,
[BudgetOverrideEntityId] = budgetOverride
};
public static EntityState CreateEntityState(string state) => new() { State = state };
public static EntityState CreateEntityStateWithAttributes(IReadOnlyDictionary<string, object?> attributes) =>
new() { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) };
public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince) =>
CreateEntityStateWithAttributes(new Dictionary<string, object?> { ["cooldown_since"] = cooldownSince });
public static void SetupEntityStates(
this Mock<IHaContext> haContextMock,
IReadOnlyDictionary<string, string?> states)
{
foreach (var (entityId, state) in states)
{
var entityState = state is null ? null : CreateEntityState(state);
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
}
}
public static void SetupEntityState(
this Mock<IHaContext> haContextMock,
string entityId,
EntityState? entityState) =>
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
/// <summary>
/// Entity-state samples for the today-runtime sensor: valid values with the expected
/// <see cref="TimeSpan"/>, plus unavailable/negative/overflow values that must be rejected.
/// </summary>
public static IEnumerable<object?[]> RuntimeStateSamples()
{
yield return ["7200", TimeSpan.FromHours(2)];
yield return ["0", TimeSpan.Zero];
yield return ["134.66", TimeSpan.FromSeconds(134.66)];
yield return ["1E3", TimeSpan.FromSeconds(1000)];
yield return ["0.001", TimeSpan.FromSeconds(0.001)];
yield return [" 60 ", TimeSpan.FromSeconds(60)];
yield return ["86400", TimeSpan.FromDays(1)];
yield return ["1e9", TimeSpan.FromSeconds(1e9)];
yield return [(string?)null, (TimeSpan?)null];
yield return ["", (TimeSpan?)null];
yield return [" ", (TimeSpan?)null];
yield return ["\t", (TimeSpan?)null];
yield return ["unavailable", (TimeSpan?)null];
yield return ["unknown", (TimeSpan?)null];
yield return ["Unavailable", (TimeSpan?)null];
yield return ["not_a_number", (TimeSpan?)null];
yield return ["NaN", (TimeSpan?)null];
yield return ["Infinity", (TimeSpan?)null];
yield return ["1e308", (TimeSpan?)null];
yield return ["-1", (TimeSpan?)null];
yield return ["-0.001", (TimeSpan?)null];
}
/// <summary>
/// Entity-state samples for the session-count sensor, including the int boundaries.
/// </summary>
public static IEnumerable<object?[]> SessionCountStateSamples()
{
yield return ["0", 0];
yield return ["3", 3];
yield return [" 2 ", 2];
yield return ["+4", 4];
yield return ["2147483647", int.MaxValue];
yield return [(string?)null, (int?)null];
yield return ["", (int?)null];
yield return [" ", (int?)null];
yield return ["\t", (int?)null];
yield return ["unavailable", (int?)null];
yield return ["unknown", (int?)null];
yield return ["abc", (int?)null];
yield return ["1.5", (int?)null];
yield return ["-1", (int?)null];
yield return ["2147483648", (int?)null];
yield return ["1e3", (int?)null];
}
/// <summary>
/// Water-ready detection samples around the heating threshold, including negative,
/// zero, exact-boundary, huge and NaN readings.
/// </summary>
public static IEnumerable<object?[]> PowerReadingSamples()
{
yield return ["negative sensor glitch", -1_000.0, true];
yield return ["just below zero", -0.001, true];
yield return ["zero", 0.0, true];
yield return ["just below threshold", 4.999, true];
yield return ["exactly at threshold", 5.0, false];
yield return ["just above threshold", 5.001, false];
yield return ["actively heating", 2_150.0, false];
yield return ["maximum", double.MaxValue, false];
yield return ["not-a-number", double.NaN, true];
}
/// <summary>
/// Elapsed-time sweep showing that the water-ready cooldown never expires on its own.
/// </summary>
public static IEnumerable<object?[]> GeneratedElapsedTimes()
{
foreach (var hours in new[] { 1, 2, 6, 12, 23, 24, 25, 48, 168 })
{
yield return [TimeSpan.FromHours(hours)];
}
}
/// <summary>
/// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end
/// timestamps carrying non-zero offsets.
/// </summary>
public static IEnumerable<object?[]> CooldownRestoreSamples()
{
yield return ["30 minutes ago", BaseTime, BaseTime - TimeSpan.FromMinutes(30), true];
yield return ["5 hours ago", BaseTime, BaseTime - TimeSpan.FromHours(5), true];
yield return ["exactly at today's UTC midnight", BaseTime, TodayMidnight(), true];
yield return ["one tick after today's UTC midnight", BaseTime, TodayMidnight().AddTicks(1), true];
yield return ["one tick before today's UTC midnight", BaseTime, TodayMidnight().AddTicks(-1), false];
yield return ["one second before today's UTC midnight", BaseTime, TodayMidnight().AddSeconds(-1), false];
yield return ["yesterday same time", BaseTime, BaseTime.AddDays(-1), false];
yield return ["two days ago", BaseTime, BaseTime.AddDays(-2), false];
yield return ["future timestamp", BaseTime, BaseTime.AddHours(1), true];
yield return ["maximum timestamp", BaseTime, DateTimeOffset.MaxValue, true];
// Europe DST starts 2026-03-29 02:00 CET → 03:00 CEST.
// now = 03:30+02:00 = 01:30Z, so UTC midnight is 2026-03-29T00:00Z.
yield return
[
"DST spring-forward, same UTC day",
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)),
true
];
yield return
[
"DST spring-forward, previous UTC day",
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)),
false
];
// Europe DST ends 2026-10-25 03:00 CEST → 02:00 CET. The 02:30 wall-clock hour occurs twice.
// now = 03:30+01:00 = 02:30Z, timestamp 02:30+02:00 = 00:30Z is still "today" in UTC.
yield return
[
"DST fall-back, ambiguous local hour",
new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)),
new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)),
true
];
yield return
[
"crossing midnight between restore and now",
new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero),
new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero),
false
];
}
private static DateTimeOffset TodayMidnight() =>
new(BaseTime.Date, TimeSpan.Zero);
}
@@ -11,15 +11,10 @@ public class WaterReadyServiceTests
{
private const double Threshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts;
private const double HighPowerWatts = 2150.0;
private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired;
private readonly Mock<ILogger<WaterReadyService>> _loggerMock;
private readonly FakeTimeProvider _timeProvider;
public WaterReadyServiceTests()
{
_loggerMock = new Mock<ILogger<WaterReadyService>>();
_timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow);
}
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new();
private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider();
private WaterReadyService CreateSut() => new(_loggerMock.Object, _timeProvider);
@@ -30,26 +25,36 @@ public class WaterReadyServiceTests
return sut;
}
private static bool TriggerWaterReady(WaterReadyService sut, double powerWatts = 0.0)
private static bool FeedReadings(
WaterReadyService sut,
int count,
string? switchState = "on",
double? powerWatts = 0.0,
double heatingThresholdWatts = Threshold)
{
var result = false;
for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++)
for (var i = 0; i < count; i++)
{
result = sut.IsWaterReady("on", powerWatts, Threshold);
result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
}
return result;
}
#region Heating observation prerequisite
[Fact]
public void IsWaterReady_SwitchOnLowPowerButNeverObservedHeating_ShouldReturnFalse()
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(10)]
public void IsWaterReady_WhenHeatingWasNeverObserved_ShouldAlwaysReturnFalse(int readingCount)
{
var sut = CreateSut();
var result = sut.IsWaterReady("on", 0.0, Threshold);
var result = FeedReadings(sut, readingCount);
result.Should().BeFalse();
sut.IsInCooldown.Should().BeFalse();
}
[Fact]
@@ -57,7 +62,7 @@ public class WaterReadyServiceTests
{
var sut = CreateSutWithHeatingObserved();
var result = TriggerWaterReady(sut);
var result = FeedReadings(sut, RequiredReadings);
result.Should().BeTrue();
}
@@ -66,11 +71,21 @@ public class WaterReadyServiceTests
public void RecordHeatingObserved_ShouldEnableDetection()
{
var sut = CreateSut();
sut.RecordHeatingObserved();
var result = TriggerWaterReady(sut);
FeedReadings(sut, RequiredReadings).Should().BeTrue();
}
result.Should().BeTrue();
[Fact]
public void RecordHeatingObserved_WhenCalledRepeatedly_ShouldStayEnabled()
{
var sut = CreateSut();
sut.RecordHeatingObserved();
sut.RecordHeatingObserved();
FeedReadings(sut, RequiredReadings).Should().BeTrue();
}
[Fact]
@@ -79,7 +94,7 @@ public class WaterReadyServiceTests
var sut = CreateSutWithHeatingObserved();
sut.NotifyTurnedOn();
var result = sut.IsWaterReady("on", 0.0, Threshold);
var result = FeedReadings(sut, 10);
result.Should().BeFalse("heating observation was reset by NotifyTurnedOn");
}
@@ -91,20 +106,32 @@ public class WaterReadyServiceTests
sut.NotifyTurnedOn();
sut.RecordHeatingObserved();
var result = TriggerWaterReady(sut);
var result = FeedReadings(sut, RequiredReadings);
result.Should().BeTrue();
}
[Fact]
public void ResetCooldown_ShouldKeepHeatingObservationEnabled()
{
var sut = CreateSutWithHeatingObserved();
FeedReadings(sut, RequiredReadings).Should().BeTrue();
sut.ResetCooldown();
FeedReadings(sut, RequiredReadings).Should().BeTrue(
"ResetCooldown clears the cooldown and counter, not the heating observation");
}
[Fact]
public void IsWaterReady_AfterResetAndReObservedHeating_ShouldTriggerAgain()
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
FeedReadings(sut, RequiredReadings);
sut.ResetCooldown();
sut.RecordHeatingObserved();
var result = TriggerWaterReady(sut);
var result = FeedReadings(sut, RequiredReadings);
result.Should().BeTrue("detection should work again after reset + new heating observation");
}
@@ -113,112 +140,99 @@ public class WaterReadyServiceTests
#region Debouncing (consecutive readings)
[Fact]
public void IsWaterReady_SingleBelowThresholdReading_ShouldReturnFalse()
[Theory]
[InlineData(1, false)]
[InlineData(2, true)]
[InlineData(3, true)]
[InlineData(10, true)]
public void IsWaterReady_ShouldRequireConsecutiveBelowThresholdReadings(int readingCount, bool expected)
{
var sut = CreateSutWithHeatingObserved();
var result = sut.IsWaterReady("on", 0.0, Threshold);
var result = FeedReadings(sut, readingCount);
result.Should().BeFalse("only 1 consecutive reading, need {0}",
BoilerMonitorConsts.ConsecutiveReadingsRequired);
result.Should().Be(expected);
}
[Fact]
public void IsWaterReady_ConsecutiveBelowThresholdReadings_ShouldReturnTrue()
[Theory]
[InlineData(HighPowerWatts)]
[InlineData(Threshold)]
[InlineData(double.MaxValue)]
public void IsWaterReady_WhenReadingIsAtOrAboveThreshold_ShouldResetConsecutiveCount(double powerWatts)
{
var sut = CreateSutWithHeatingObserved();
FeedReadings(sut, RequiredReadings - 1).Should().BeFalse();
var result = TriggerWaterReady(sut);
sut.IsWaterReady("on", powerWatts, Threshold).Should().BeFalse("power is not below the threshold");
result.Should().BeTrue();
FeedReadings(sut, 1).Should().BeFalse("the counter was reset by the above-threshold reading");
FeedReadings(sut, RequiredReadings - 1).Should().BeTrue();
}
[Fact]
public void IsWaterReady_BelowThresholdResetByAboveThreshold_ShouldRequireConsecutiveAgain()
[Theory]
[InlineData(0)]
[InlineData(1)]
public void IsWaterReady_NotifyTurnedOn_ShouldResetConsecutiveCount(int belowThresholdBeforeTurnOn)
{
var sut = CreateSutWithHeatingObserved();
FeedReadings(sut, belowThresholdBeforeTurnOn);
sut.IsWaterReady("on", 0.0, Threshold);
sut.IsWaterReady("on", HighPowerWatts, Threshold);
var result = sut.IsWaterReady("on", 0.0, Threshold);
result.Should().BeFalse("counter was reset by above-threshold reading");
}
[Fact]
public void IsWaterReady_NotifyTurnedOn_ShouldResetConsecutiveCount()
{
var sut = CreateSutWithHeatingObserved();
sut.IsWaterReady("on", 0.0, Threshold);
sut.NotifyTurnedOn();
sut.RecordHeatingObserved();
var result = sut.IsWaterReady("on", 0.0, Threshold);
result.Should().BeFalse("NotifyTurnedOn reset the consecutive counter");
FeedReadings(sut, RequiredReadings - 1).Should().BeFalse("NotifyTurnedOn reset the consecutive counter");
FeedReadings(sut, 1).Should().BeTrue();
}
[Fact]
public void IsWaterReady_InterleavedReadings_ShouldOnlyTriggerAfterLastConsecutiveLowReading()
{
var sut = CreateSutWithHeatingObserved();
var results = new[]
{
sut.IsWaterReady("on", 0.0, Threshold),
sut.IsWaterReady("on", HighPowerWatts, Threshold),
sut.IsWaterReady("on", 0.0, Threshold),
sut.IsWaterReady("on", 0.0, Threshold)
};
results.Should().Equal(false, false, false, true);
}
#endregion
#region Basic state checks
[Fact]
public void IsWaterReady_SwitchOnAndPowerAtThreshold_ShouldReturnFalse()
[Theory]
[InlineData("off")]
[InlineData("OFF")]
[InlineData(" off")]
[InlineData("on ")]
[InlineData("unknown")]
[InlineData("unavailable")]
[InlineData("yes")]
[InlineData("1")]
public void IsWaterReady_WhenSwitchIsNotOn_ShouldReturnFalse(string switchState)
{
var sut = CreateSutWithHeatingObserved();
var result = sut.IsWaterReady("on", Threshold, Threshold);
var result = FeedReadings(sut, 10, switchState);
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_SwitchOnAndHighPower_ShouldReturnFalse()
[Theory]
[InlineData("on", null)]
[InlineData(null, 0.0)]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("", 0.0)]
public void IsWaterReady_WhenSwitchStateOrPowerIsNull_ShouldReturnFalse(string? switchState, double? powerWatts)
{
var sut = CreateSutWithHeatingObserved();
var result = sut.IsWaterReady("on", HighPowerWatts, Threshold);
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_SwitchOff_ShouldReturnFalse()
{
var sut = CreateSutWithHeatingObserved();
var result = sut.IsWaterReady("off", 0.0, Threshold);
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_NullSwitchState_ShouldReturnFalse()
{
var sut = CreateSutWithHeatingObserved();
var result = sut.IsWaterReady(null, 0.0, Threshold);
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_NullPowerWatts_ShouldReturnFalse()
{
var sut = CreateSutWithHeatingObserved();
var result = sut.IsWaterReady("on", null, Threshold);
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_BothNull_ShouldReturnFalse()
{
var sut = CreateSut();
var result = sut.IsWaterReady(null, null, Threshold);
var result = FeedReadings(sut, 10, switchState, powerWatts);
result.Should().BeFalse();
}
@@ -226,33 +240,49 @@ public class WaterReadyServiceTests
[Theory]
[InlineData("ON")]
[InlineData("On")]
[InlineData("on")]
[InlineData("oN")]
public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState)
{
var sut = CreateSutWithHeatingObserved();
var result = false;
for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++)
{
result = sut.IsWaterReady(switchState, 0.0, Threshold);
}
var result = FeedReadings(sut, RequiredReadings, switchState);
result.Should().BeTrue();
}
[Theory]
[MemberData(nameof(BoilerMonitorTestData.PowerReadingSamples), MemberType = typeof(BoilerMonitorTestData))]
public void IsWaterReady_PowerAroundThreshold_ShouldFollowThresholdRule(
string scenario,
double powerWatts,
bool expectedBelowThreshold)
{
var sut = CreateSutWithHeatingObserved();
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts);
result.Should().Be(
expectedBelowThreshold,
$"{scenario}: readings below {Threshold}W are counted as 'not heating'");
}
[Theory]
[InlineData(9.9, 10.0, true)]
[InlineData(10.0, 10.0, false)]
[InlineData(10.1, 10.0, false)]
public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(double powerWatts, double threshold, bool expected)
[InlineData(0.0, 0.0, false)]
[InlineData(-10.0, -5.0, true)]
[InlineData(-0.001, 0.0, true)]
[InlineData(0.0, -5.0, false)]
[InlineData(10.0, 0.0, false)]
public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(
double powerWatts,
double heatingThresholdWatts,
bool expected)
{
var sut = CreateSutWithHeatingObserved();
var result = false;
for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++)
{
result = sut.IsWaterReady("on", powerWatts, threshold);
}
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts, heatingThresholdWatts: heatingThresholdWatts);
result.Should().Be(expected);
}
@@ -261,60 +291,37 @@ public class WaterReadyServiceTests
#region Cooldown period
[Fact]
public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfSwitchState()
[Theory]
[InlineData("off", 0.0)]
[InlineData("off", null)]
[InlineData(null, 0.0)]
[InlineData(null, null)]
[InlineData("on", HighPowerWatts)]
[InlineData("unknown", 12.0)]
public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfInputs(string? switchState, double? powerWatts)
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
FeedReadings(sut, RequiredReadings).Should().BeTrue();
var result = sut.IsWaterReady("off", 0.0, Threshold);
var result = sut.IsWaterReady(switchState, powerWatts, Threshold);
result.Should().BeTrue();
}
[Fact]
public void IsWaterReady_DuringCooldown_ShouldReturnTrueEvenWithNullState()
[Theory]
[MemberData(nameof(BoilerMonitorTestData.GeneratedElapsedTimes), MemberType = typeof(BoilerMonitorTestData))]
public void IsWaterReady_CooldownDoesNotExpireByTime_ShouldStayActive(TimeSpan elapsed)
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
FeedReadings(sut, RequiredReadings);
var triggeredAt = sut.WaterReadySince;
var result = sut.IsWaterReady(null, null, Threshold);
result.Should().BeTrue();
}
[Fact]
public void IsWaterReady_CooldownDoesNotExpireByTime_ShouldStayActiveAfterHours()
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
_timeProvider.Advance(TimeSpan.FromHours(12));
var result = sut.IsWaterReady("off", 0.0, Threshold);
result.Should().BeTrue("cooldown only clears via explicit ResetCooldown, not by elapsed time");
}
[Fact]
public void IsWaterReady_CooldownClearedOnlyByExplicitReset_ShouldResumeAfterReset()
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
_timeProvider.Advance(TimeSpan.FromHours(5));
sut.IsInCooldown.Should().BeTrue();
sut.ResetCooldown();
sut.IsWaterReady("off", 0.0, Threshold).Should().BeFalse();
}
[Fact]
public void IsInCooldown_WhenCooldownActive_ShouldReturnTrue()
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
_timeProvider.Advance(elapsed);
sut.IsInCooldown.Should().BeTrue();
sut.IsWaterReady("off", 0.0, Threshold).Should().BeTrue(
"cooldown only clears via explicit ResetCooldown, not by elapsed time");
sut.WaterReadySince.Should().Be(triggeredAt);
}
[Fact]
@@ -326,67 +333,65 @@ public class WaterReadyServiceTests
}
[Fact]
public void IsInCooldown_DoesNotExpireByTime_ShouldRemainTrueAfterHours()
public void ResetCooldown_ShouldClearActiveCooldownAndAllowDetectionToResume()
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
_timeProvider.Advance(TimeSpan.FromHours(8));
sut.IsInCooldown.Should().BeTrue();
}
[Fact]
public void ResetCooldown_ShouldClearActiveCooldown()
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
FeedReadings(sut, RequiredReadings);
sut.IsInCooldown.Should().BeTrue();
sut.ResetCooldown();
sut.IsInCooldown.Should().BeFalse();
sut.WaterReadySince.Should().BeNull();
sut.IsWaterReady("off", 0.0, Threshold).Should().BeFalse();
FeedReadings(sut, RequiredReadings - 1).Should().BeFalse();
FeedReadings(sut, 1).Should().BeTrue();
}
[Fact]
public void ResetCooldown_ShouldAllowNormalDetectionToResume()
public void ResetCooldown_WhenNoCooldownIsActive_ShouldBeANoOp()
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
var sut = CreateSut();
sut.ResetCooldown();
var result = sut.IsWaterReady("off", 0.0, Threshold);
result.Should().BeFalse();
sut.IsInCooldown.Should().BeFalse();
sut.WaterReadySince.Should().BeNull();
FeedReadings(sut, 10).Should().BeFalse("heating was never observed");
}
[Fact]
public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp()
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
FeedReadings(sut, RequiredReadings);
var originalTimestamp = sut.WaterReadySince;
_timeProvider.Advance(TimeSpan.FromHours(2));
sut.IsWaterReady("on", 0.0, Threshold);
sut.IsWaterReady("on", 0.0, Threshold).Should().BeTrue();
sut.WaterReadySince.Should().Be(originalTimestamp);
}
[Fact]
public void IsWaterReady_HighPowerDoesNotTriggerCooldown_ShouldReturnFalse()
[Theory]
[InlineData(Threshold)]
[InlineData(HighPowerWatts)]
[InlineData(double.MaxValue)]
public void IsWaterReady_PowerAtOrAboveThreshold_ShouldNotStartCooldown(double powerWatts)
{
var sut = CreateSutWithHeatingObserved();
sut.IsWaterReady("on", HighPowerWatts, Threshold);
FeedReadings(sut, RequiredReadings, powerWatts: powerWatts).Should().BeFalse();
sut.IsInCooldown.Should().BeFalse();
sut.WaterReadySince.Should().BeNull();
}
[Fact]
public void NotifyTurnedOn_DuringActiveCooldown_ShouldNotClearCooldown()
{
var sut = CreateSutWithHeatingObserved();
TriggerWaterReady(sut);
FeedReadings(sut, RequiredReadings);
sut.NotifyTurnedOn();
@@ -397,60 +402,22 @@ public class WaterReadyServiceTests
#region Cooldown persistence
[Fact]
public void RestoreCooldownState_ShouldResumeActiveCooldown()
[Theory]
[MemberData(nameof(BoilerMonitorTestData.CooldownRestoreSamples), MemberType = typeof(BoilerMonitorTestData))]
public void RestoreCooldownState_ShouldRestoreOnlyTimestampsFromTodayUtc(
string scenario,
DateTimeOffset now,
DateTimeOffset cooldownSince,
bool expectedRestored)
{
var sut = CreateSut();
var cooldownStart = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(30);
var timeProvider = BoilerMonitorTestData.CreateTimeProvider(now);
var sut = new WaterReadyService(_loggerMock.Object, timeProvider);
sut.RestoreCooldownState(cooldownStart);
sut.RestoreCooldownState(cooldownSince);
sut.IsInCooldown.Should().BeTrue();
sut.IsWaterReady("off", 0.0, Threshold).Should().BeTrue();
}
[Fact]
public void RestoreCooldownState_WithYesterdayTimestamp_ShouldNotActivateCooldown()
{
var sut = CreateSut();
var yesterday = _timeProvider.GetUtcNow().AddDays(-1);
sut.RestoreCooldownState(yesterday);
sut.IsInCooldown.Should().BeFalse();
}
[Fact]
public void RestoreCooldownState_WithTodayTimestamp_ShouldRestoreCooldown()
{
var sut = CreateSut();
var earlierToday = _timeProvider.GetUtcNow() - TimeSpan.FromHours(5);
sut.RestoreCooldownState(earlierToday);
sut.IsInCooldown.Should().BeTrue();
}
[Fact]
public void RestoreCooldownState_WithExactlyMidnightTimestamp_ShouldRestoreCooldown()
{
var sut = CreateSut();
var todayMidnight = new DateTimeOffset(_timeProvider.GetUtcNow().Date, TimeSpan.Zero);
sut.RestoreCooldownState(todayMidnight);
sut.IsInCooldown.Should().BeTrue("timestamp at today's midnight is not before today");
}
[Fact]
public void RestoreCooldownState_ShouldPreserveOriginalTimestamp()
{
var sut = CreateSut();
var cooldownStart = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(30);
sut.RestoreCooldownState(cooldownStart);
sut.WaterReadySince.Should().Be(cooldownStart);
sut.IsInCooldown.Should().Be(expectedRestored, scenario);
sut.WaterReadySince.Should().Be(expectedRestored ? cooldownSince : null, scenario);
sut.IsWaterReady("off", 0.0, Threshold).Should().Be(expectedRestored, scenario);
}
[Fact]
@@ -459,7 +426,7 @@ public class WaterReadyServiceTests
var sut = CreateSutWithHeatingObserved();
var beforeTrigger = _timeProvider.GetUtcNow();
TriggerWaterReady(sut);
FeedReadings(sut, RequiredReadings).Should().BeTrue();
sut.WaterReadySince.Should().Be(beforeTrigger);
}