Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests - Expand single-statement guards and loops into braced blocks - Realign wrapped method arguments, chained calls and continuations - Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty` - Flatten the boiler config expression and reindent the remaining touched files
This commit is contained in:
@@ -1,14 +1,18 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models.Enums;
|
||||
using BoilerMonitorManager;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
public class BoilerControlServiceTests
|
||||
{
|
||||
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new();
|
||||
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new Mock<ILogger<BoilerControlService>>();
|
||||
|
||||
private BoilerControlService CreateSut()
|
||||
{
|
||||
@@ -34,8 +38,9 @@ public class BoilerControlServiceTests
|
||||
bool budgetExhausted,
|
||||
bool budgetOverride)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
|
||||
|
||||
result.Should().Be(BoilerAction.NoChange);
|
||||
}
|
||||
@@ -57,9 +62,10 @@ public class BoilerControlServiceTests
|
||||
[InlineData("0")]
|
||||
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
true, false, switchState,
|
||||
false, false);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
true, false, switchState,
|
||||
false, false);
|
||||
|
||||
result.Should().Be(BoilerAction.TurnOn);
|
||||
}
|
||||
@@ -75,9 +81,10 @@ public class BoilerControlServiceTests
|
||||
string? switchState,
|
||||
BoilerAction expectedAction)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
true, false, switchState,
|
||||
true, true);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
true, false, switchState,
|
||||
true, true);
|
||||
|
||||
result.Should().Be(expectedAction);
|
||||
}
|
||||
@@ -93,9 +100,10 @@ public class BoilerControlServiceTests
|
||||
[InlineData("oN")]
|
||||
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
false, false, switchState,
|
||||
false, false);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
false, false, switchState,
|
||||
false, false);
|
||||
|
||||
result.Should().Be(BoilerAction.TurnOff);
|
||||
}
|
||||
@@ -109,9 +117,10 @@ public class BoilerControlServiceTests
|
||||
bool budgetExhausted,
|
||||
bool budgetOverride)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
true, waterReady, "on",
|
||||
budgetExhausted, budgetOverride);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
true, waterReady, "on",
|
||||
budgetExhausted, budgetOverride);
|
||||
|
||||
result.Should().Be(BoilerAction.TurnOff);
|
||||
}
|
||||
@@ -124,7 +133,7 @@ public class BoilerControlServiceTests
|
||||
/// 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 TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOnActionMatrix => new()
|
||||
public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOnActionMatrix => new TheoryData<bool, bool, bool, bool, BoilerAction>
|
||||
{
|
||||
{ false, false, false, false, BoilerAction.TurnOff },
|
||||
{ false, false, false, true, BoilerAction.TurnOff },
|
||||
@@ -153,8 +162,9 @@ public class BoilerControlServiceTests
|
||||
bool budgetOverride,
|
||||
BoilerAction expectedAction)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
|
||||
|
||||
result.Should().Be(expectedAction);
|
||||
}
|
||||
@@ -163,7 +173,7 @@ public class BoilerControlServiceTests
|
||||
/// 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 TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOffActionMatrix => new()
|
||||
public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOffActionMatrix => new TheoryData<bool, bool, bool, bool, BoilerAction>
|
||||
{
|
||||
{ false, false, false, false, BoilerAction.NoChange },
|
||||
{ false, false, false, true, BoilerAction.NoChange },
|
||||
@@ -192,8 +202,9 @@ public class BoilerControlServiceTests
|
||||
bool budgetOverride,
|
||||
BoilerAction expectedAction)
|
||||
{
|
||||
var result = CreateSut().DetermineAction(
|
||||
isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
|
||||
var result = CreateSut()
|
||||
.DetermineAction(
|
||||
isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
|
||||
|
||||
result.Should().Be(expectedAction);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
public class BoilerMonitorConfigTests
|
||||
@@ -7,7 +11,7 @@ public class BoilerMonitorConfigTests
|
||||
private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId;
|
||||
private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId;
|
||||
|
||||
public static TheoryData<string, string?, string?, int?, double?, bool> ConfigurationCases => new()
|
||||
public static TheoryData<string, string?, string?, int?, double?, bool> ConfigurationCases => new TheoryData<string, string?, string?, int?, double?, bool>
|
||||
{
|
||||
{ "fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true },
|
||||
{ "minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true },
|
||||
@@ -18,11 +22,11 @@ public class BoilerMonitorConfigTests
|
||||
{ "infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true },
|
||||
|
||||
{ "power entity id null", null, SwitchEntityId, 30, 5.0, false },
|
||||
{ "power entity id empty", "", SwitchEntityId, 30, 5.0, false },
|
||||
{ "power entity id empty", string.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, null, 30, 5.0, false },
|
||||
{ "switch entity id empty", PowerEntityId, "", 30, 5.0, false },
|
||||
{ "switch entity id empty", PowerEntityId, string.Empty, 30, 5.0, false },
|
||||
{ "switch entity id whitespace", PowerEntityId, " ", 30, 5.0, false },
|
||||
{ "both entity ids null", null, null, 30, 5.0, false },
|
||||
|
||||
@@ -50,10 +54,10 @@ public class BoilerMonitorConfigTests
|
||||
bool expected)
|
||||
{
|
||||
var config = BoilerMonitorTestData.CreateConfig(
|
||||
powerEntityId,
|
||||
switchEntityId,
|
||||
pollIntervalSeconds,
|
||||
heatingPowerThresholdWatts);
|
||||
powerEntityId,
|
||||
switchEntityId,
|
||||
pollIntervalSeconds,
|
||||
heatingPowerThresholdWatts);
|
||||
|
||||
config.IsFullyConfigured.Should().Be(expected, scenario);
|
||||
}
|
||||
@@ -62,8 +66,8 @@ public class BoilerMonitorConfigTests
|
||||
public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding()
|
||||
{
|
||||
var config = BoilerMonitorTestData.CreateConfig(
|
||||
" sensor.sonoff_1002230e32_power ",
|
||||
"SWITCH.SONOFF_1002230E32");
|
||||
" sensor.sonoff_1002230e32_power ",
|
||||
"SWITCH.SONOFF_1002230E32");
|
||||
|
||||
config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content");
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using BoilerMonitorManager;
|
||||
using FluentAssertions;
|
||||
@@ -8,6 +10,8 @@ using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
public class BoilerMonitorEntityServiceTests
|
||||
@@ -31,28 +35,31 @@ public class BoilerMonitorEntityServiceTests
|
||||
AutoManagementEntityId
|
||||
];
|
||||
|
||||
private readonly Mock<IEntityManager> _entityManagerMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new();
|
||||
private readonly Mock<IEntityManager> _entityManagerMock = new Mock<IEntityManager>();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
|
||||
|
||||
public BoilerMonitorEntityServiceTests()
|
||||
{
|
||||
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
}
|
||||
|
||||
private BoilerMonitorEntityService CreateSut()
|
||||
{
|
||||
return new BoilerMonitorEntityService(
|
||||
_entityManagerMock.Object,
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object);
|
||||
_entityManagerMock.Object,
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object);
|
||||
}
|
||||
|
||||
#region ReadPersistedState
|
||||
@@ -64,13 +71,14 @@ public class BoilerMonitorEntityServiceTests
|
||||
TimeSpan? expectedRunTime)
|
||||
{
|
||||
_haContextMock.SetupEntityStates(
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2"));
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2"));
|
||||
|
||||
var result = CreateSut().ReadPersistedState();
|
||||
|
||||
if (expectedRunTime is null)
|
||||
{
|
||||
result.Should().BeNull();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -86,13 +94,14 @@ public class BoilerMonitorEntityServiceTests
|
||||
int? expectedSessionCount)
|
||||
{
|
||||
_haContextMock.SetupEntityStates(
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState));
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState));
|
||||
|
||||
var result = CreateSut().ReadPersistedState();
|
||||
|
||||
if (expectedSessionCount is null)
|
||||
{
|
||||
result.Should().BeNull();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -105,7 +114,7 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
|
||||
{
|
||||
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||
"7200", "3", "ON"));
|
||||
"7200", "3", "ON"));
|
||||
|
||||
var result = CreateSut().ReadPersistedState();
|
||||
|
||||
@@ -125,7 +134,7 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedState_ShouldReturnRawSwitchStates(string? switchState)
|
||||
{
|
||||
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||
skipPriceCap: switchState, budgetOverride: switchState));
|
||||
skipPriceCap: switchState, budgetOverride: switchState));
|
||||
|
||||
var result = CreateSut().ReadPersistedState();
|
||||
|
||||
@@ -138,7 +147,7 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull()
|
||||
{
|
||||
_haContextMock.SetupEntityStates(
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates(null, null));
|
||||
BoilerMonitorTestData.CreatePersistedEntityStates(null, null));
|
||||
|
||||
CreateSut().ReadPersistedState().Should().BeNull();
|
||||
}
|
||||
@@ -151,9 +160,10 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedCooldownTimestamp_WithValidIsoString_ShouldReturnTimestamp()
|
||||
{
|
||||
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(30);
|
||||
|
||||
_haContextMock.SetupEntityState(
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O")));
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O")));
|
||||
|
||||
var result = CreateSut().ReadPersistedCooldownTimestamp();
|
||||
|
||||
@@ -164,9 +174,10 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp()
|
||||
{
|
||||
var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero);
|
||||
|
||||
_haContextMock.SetupEntityState(
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
|
||||
|
||||
var result = CreateSut().ReadPersistedCooldownTimestamp();
|
||||
|
||||
@@ -193,9 +204,9 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedCooldownTimestamp_WhenAttributeIsMissing_ShouldReturnNull()
|
||||
{
|
||||
_haContextMock.SetupEntityState(
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateEntityStateWithAttributes(
|
||||
new Dictionary<string, object?> { ["friendly_name"] = "Boiler water ready" }));
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateEntityStateWithAttributes(
|
||||
new Dictionary<string, object?> { ["friendly_name"] = "Boiler water ready" }));
|
||||
|
||||
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||
}
|
||||
@@ -212,8 +223,8 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedCooldownTimestamp_WhenAttributeIsNotAValidTimestamp_ShouldReturnNull(object? cooldownSince)
|
||||
{
|
||||
_haContextMock.SetupEntityState(
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince));
|
||||
WaterReadyEntityId,
|
||||
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince));
|
||||
|
||||
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||
}
|
||||
@@ -222,7 +233,7 @@ public class BoilerMonitorEntityServiceTests
|
||||
public void ReadPersistedCooldownTimestamp_WhenHaContextThrows_ShouldReturnNull()
|
||||
{
|
||||
_haContextMock.Setup(h => h.GetState(WaterReadyEntityId))
|
||||
.Throws(new InvalidOperationException("Home Assistant unavailable"));
|
||||
.Throws(new InvalidOperationException("Home Assistant unavailable"));
|
||||
|
||||
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||
}
|
||||
@@ -245,12 +256,12 @@ public class BoilerMonitorEntityServiceTests
|
||||
public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting()
|
||||
{
|
||||
var context = BoilerMonitorTestData.CreateUpdateContext(
|
||||
TimeSpan.FromSeconds(3723.9),
|
||||
TimeSpan.FromSeconds(42.9),
|
||||
150.0,
|
||||
true,
|
||||
4,
|
||||
waterReady: true);
|
||||
TimeSpan.FromSeconds(3723.9),
|
||||
TimeSpan.FromSeconds(42.9),
|
||||
150.0,
|
||||
true,
|
||||
4,
|
||||
waterReady: true);
|
||||
|
||||
await CreateSut().UpdateEntitiesAsync(context);
|
||||
|
||||
@@ -260,8 +271,9 @@ public class BoilerMonitorEntityServiceTests
|
||||
_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));
|
||||
Times.Exactly(5));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -276,11 +288,12 @@ public class BoilerMonitorEntityServiceTests
|
||||
double budgetPercentage,
|
||||
string expectedState)
|
||||
{
|
||||
await CreateSut().UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage));
|
||||
await CreateSut()
|
||||
.UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage));
|
||||
|
||||
_entityManagerMock.Verify(
|
||||
em => em.SetEntityState(BudgetPercentageEntityId, expectedState), Times.Once);
|
||||
em => em.SetEntityState(BudgetPercentageEntityId, expectedState), Times.Once);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -291,8 +304,9 @@ public class BoilerMonitorEntityServiceTests
|
||||
[InlineData(3600, "3600")]
|
||||
public async Task UpdateEntitiesAsync_ShouldClampAndTruncateRemainingTime(int seconds, string expectedState)
|
||||
{
|
||||
await CreateSut().UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds)));
|
||||
await CreateSut()
|
||||
.UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds)));
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, expectedState), Times.Once);
|
||||
}
|
||||
@@ -305,8 +319,9 @@ public class BoilerMonitorEntityServiceTests
|
||||
[InlineData(86_400.0, "86400")]
|
||||
public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState)
|
||||
{
|
||||
await CreateSut().UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds)));
|
||||
await CreateSut()
|
||||
.UpdateEntitiesAsync(
|
||||
BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds)));
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once);
|
||||
}
|
||||
@@ -315,15 +330,17 @@ public class BoilerMonitorEntityServiceTests
|
||||
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));
|
||||
_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!);
|
||||
@@ -338,13 +355,15 @@ public class BoilerMonitorEntityServiceTests
|
||||
{
|
||||
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));
|
||||
_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"));
|
||||
@@ -358,49 +377,54 @@ public class BoilerMonitorEntityServiceTests
|
||||
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);
|
||||
.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(
|
||||
[
|
||||
ConfigPowerEntityId,
|
||||
ConfigSwitchEntityId,
|
||||
ConfigPollIntervalEntityId,
|
||||
ConfigHeatingThresholdEntityId,
|
||||
CleanupButtonEntityId,
|
||||
WaterReadyEntityId,
|
||||
TodayRuntimeEntityId,
|
||||
BudgetExhaustedEntityId,
|
||||
AutoManagementEntityId
|
||||
]);
|
||||
|
||||
createdEntityIds.Should()
|
||||
.Contain(
|
||||
[
|
||||
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"));
|
||||
.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);
|
||||
.Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync))
|
||||
.Should()
|
||||
.Be(15);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ResetEntitiesAsync
|
||||
|
||||
public static TheoryData<string, string> ResetEntityStates => new()
|
||||
public static TheoryData<string, string> ResetEntityStates => new TheoryData<string, string>
|
||||
{
|
||||
{ StatusEntityId, StatusAwaitingConfiguration },
|
||||
{ WaterReadyEntityId, "unknown" },
|
||||
@@ -422,16 +446,17 @@ public class BoilerMonitorEntityServiceTests
|
||||
|
||||
_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));
|
||||
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"));
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
||||
|
||||
var act = () => CreateSut().ResetEntitiesAsync();
|
||||
|
||||
@@ -486,7 +511,9 @@ public class BoilerMonitorEntityServiceTests
|
||||
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));
|
||||
@@ -496,8 +523,8 @@ public class BoilerMonitorEntityServiceTests
|
||||
public async Task CleanupEntitiesAsync_WhenRemoveFails_ShouldRethrow()
|
||||
{
|
||||
_entityManagerMock
|
||||
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.Throws(new InvalidOperationException("MQTT unavailable"));
|
||||
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.Throws(new InvalidOperationException("MQTT unavailable"));
|
||||
|
||||
var act = () => CreateSut().CleanupEntitiesAsync();
|
||||
|
||||
@@ -536,12 +563,13 @@ public class BoilerMonitorEntityServiceTests
|
||||
{
|
||||
var canceledToken = new CancellationToken(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),
|
||||
BoilerMonitorTestData.CreateUpdateContext(), canceledToken),
|
||||
CancelableOperation.ResetTransientEntities => () => sut.ResetTransientEntitiesAsync(canceledToken),
|
||||
_ => () => sut.CleanupEntitiesAsync(canceledToken)
|
||||
};
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitorManager.Models;
|
||||
using FluentAssertions;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
public class BoilerMonitorOptionsTests
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using BoilerMonitorManager.Models;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
@@ -6,6 +8,8 @@ using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
/// <summary>
|
||||
@@ -19,7 +23,7 @@ internal static class BoilerMonitorTestData
|
||||
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 readonly DateTimeOffset BaseTime = new DateTimeOffset(2026, 3, 31, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null)
|
||||
{
|
||||
@@ -147,7 +151,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add("1e9", TimeSpan.FromSeconds(1e9));
|
||||
|
||||
data.Add(null, null);
|
||||
data.Add("", null);
|
||||
data.Add(string.Empty, null);
|
||||
data.Add(" ", null);
|
||||
data.Add("\t", null);
|
||||
data.Add("unavailable", null);
|
||||
@@ -159,6 +163,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add("1e308", null);
|
||||
data.Add("-1", null);
|
||||
data.Add("-0.001", null);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -175,7 +180,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add("2147483647", int.MaxValue);
|
||||
|
||||
data.Add(null, null);
|
||||
data.Add("", null);
|
||||
data.Add(string.Empty, null);
|
||||
data.Add(" ", null);
|
||||
data.Add("\t", null);
|
||||
data.Add("unavailable", null);
|
||||
@@ -185,6 +190,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add("-1", null);
|
||||
data.Add("2147483648", null);
|
||||
data.Add("1e3", null);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -204,6 +210,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add("actively heating", 2_150.0, false);
|
||||
data.Add("maximum", double.MaxValue, false);
|
||||
data.Add("not-a-number", double.NaN, true);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -222,6 +229,7 @@ internal static class BoilerMonitorTestData
|
||||
data.Add(TimeSpan.FromHours(25));
|
||||
data.Add(TimeSpan.FromHours(48));
|
||||
data.Add(TimeSpan.FromHours(168));
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -246,33 +254,35 @@ internal static class BoilerMonitorTestData
|
||||
// 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.
|
||||
data.Add(
|
||||
"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
|
||||
);
|
||||
"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
|
||||
);
|
||||
|
||||
data.Add(
|
||||
"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
|
||||
);
|
||||
"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.
|
||||
data.Add(
|
||||
"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
|
||||
);
|
||||
"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
|
||||
);
|
||||
|
||||
data.Add(
|
||||
"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
|
||||
);
|
||||
"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
|
||||
);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using BoilerMonitor.Models;
|
||||
using BoilerMonitorManager;
|
||||
using FluentAssertions;
|
||||
@@ -5,6 +7,8 @@ using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using Moq;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace BoilerMonitor.Manager.Tests;
|
||||
|
||||
public class WaterReadyServiceTests
|
||||
@@ -13,7 +17,7 @@ public class WaterReadyServiceTests
|
||||
private const double HighPowerWatts = 2150.0;
|
||||
private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired;
|
||||
|
||||
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new();
|
||||
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new Mock<ILogger<WaterReadyService>>();
|
||||
private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider();
|
||||
|
||||
private WaterReadyService CreateSut()
|
||||
@@ -25,6 +29,7 @@ public class WaterReadyServiceTests
|
||||
{
|
||||
var sut = CreateSut();
|
||||
sut.RecordHeatingObserved();
|
||||
|
||||
return sut;
|
||||
}
|
||||
|
||||
@@ -36,7 +41,11 @@ public class WaterReadyServiceTests
|
||||
double heatingThresholdWatts = Threshold)
|
||||
{
|
||||
var result = false;
|
||||
for (var i = 0; i < count; i++) result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -119,8 +128,10 @@ public class WaterReadyServiceTests
|
||||
|
||||
sut.ResetCooldown();
|
||||
|
||||
FeedReadings(sut, RequiredReadings).Should().BeTrue(
|
||||
"ResetCooldown clears the cooldown and counter, not the heating observation");
|
||||
FeedReadings(sut, RequiredReadings)
|
||||
.Should()
|
||||
.BeTrue(
|
||||
"ResetCooldown clears the cooldown and counter, not the heating observation");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -261,9 +272,10 @@ public class WaterReadyServiceTests
|
||||
|
||||
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts);
|
||||
|
||||
result.Should().Be(
|
||||
expectedBelowThreshold,
|
||||
$"{scenario}: readings below {Threshold}W are counted as 'not heating'");
|
||||
result.Should()
|
||||
.Be(
|
||||
expectedBelowThreshold,
|
||||
$"{scenario}: readings below {Threshold}W are counted as 'not heating'");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -283,7 +295,7 @@ public class WaterReadyServiceTests
|
||||
var sut = CreateSutWithHeatingObserved();
|
||||
|
||||
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts,
|
||||
heatingThresholdWatts: heatingThresholdWatts);
|
||||
heatingThresholdWatts: heatingThresholdWatts);
|
||||
|
||||
result.Should().Be(expected);
|
||||
}
|
||||
@@ -320,8 +332,12 @@ public class WaterReadyServiceTests
|
||||
_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.IsWaterReady("off", 0.0, Threshold)
|
||||
.Should()
|
||||
.BeTrue(
|
||||
"cooldown only clears via explicit ResetCooldown, not by elapsed time");
|
||||
|
||||
sut.WaterReadySince.Should().Be(triggeredAt);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user