Convert test data sources to typed TheoryData

Replace untyped MemberData sources with TheoryData<...>, use collection
expressions for array and list literals, drop redundant casts and null
suppressions, and give log-assertion helpers an IsEnabled setup so guarded
log calls stay verifiable.
This commit is contained in:
2026-11-29 21:42:41 +02:00
parent ada3c77778
commit 17774b40b8
31 changed files with 649 additions and 693 deletions
@@ -14,7 +14,7 @@ namespace BatteryMonitor.Manager.Tests;
/// </summary> /// </summary>
internal static class BatteryMonitorTestData internal static class BatteryMonitorTestData
{ {
public const string DefaultFriendlyName = "Battery Device"; private const string DefaultFriendlyName = "Battery Device";
/// <summary> /// <summary>
/// Describes one entity exposed through <see cref="IHaContext.GetAllEntities"/>. /// Describes one entity exposed through <see cref="IHaContext.GetAllEntities"/>.
@@ -79,9 +79,9 @@ internal static class BatteryMonitorTestData
/// <summary> /// <summary>
/// Wires <see cref="IHaContext.GetState"/> and <see cref="IHaContext.GetAllEntities"/> /// Wires <see cref="IHaContext.GetState"/> and <see cref="IHaContext.GetAllEntities"/>
/// on the mock and returns the created entities in declaration order. /// on the mock, exposing the entities in declaration order.
/// </summary> /// </summary>
public static IReadOnlyList<Entity> ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities) public static void ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities)
{ {
var entityList = new List<Entity>(entities.Length); var entityList = new List<Entity>(entities.Length);
@@ -96,8 +96,6 @@ internal static class BatteryMonitorTestData
} }
haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList); haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
return entityList;
} }
public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null) public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
@@ -112,16 +110,12 @@ internal static class BatteryMonitorTestData
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors) public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
{ {
return sensors return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))
.ToList();
} }
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors) public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
{ {
return sensors return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))
.ToList();
} }
/// <summary> /// <summary>
@@ -129,12 +123,14 @@ internal static class BatteryMonitorTestData
/// </summary> /// </summary>
public static EntitySpec[] CreateGeneratedBatteryEntities(int count) public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
{ {
return Enumerable.Range(0, count) return
.Select(i => Battery( [
$"sensor.generated_battery_{i:D3}", .. Enumerable.Range(0, count)
i.ToString(CultureInfo.InvariantCulture), .Select(i => Battery(
$"Generated Battery {i:D3}")) $"sensor.generated_battery_{i:D3}",
.ToArray(); i.ToString(CultureInfo.InvariantCulture),
$"Generated Battery {i:D3}"))
];
} }
/// <summary> /// <summary>
@@ -143,12 +139,14 @@ internal static class BatteryMonitorTestData
/// </summary> /// </summary>
public static IReadOnlyList<BatterySensorInfo> CreateGeneratedSensorInfos(int count) public static IReadOnlyList<BatterySensorInfo> CreateGeneratedSensorInfos(int count)
{ {
return Enumerable.Range(0, count) return
.Select(i => CreateSensorInfo( [
$"sensor.generated_{i:D3}", .. Enumerable.Range(0, count)
(i * 37) % 101, .Select(i => CreateSensorInfo(
$"Generated Device {i:D3}")) $"sensor.generated_{i:D3}",
.ToList(); i * 37 % 101,
$"Generated Device {i:D3}"))
];
} }
/// <summary> /// <summary>
@@ -188,8 +186,8 @@ internal static class BatteryMonitorTestData
/// States that must never produce a <see cref="BatterySensorInfo"/>, including /// States that must never produce a <see cref="BatterySensorInfo"/>, including
/// whitespace/malformed strings and a null state. /// whitespace/malformed strings and a null state.
/// </summary> /// </summary>
public static TheoryData<string?> UnusableStateRows { get; } = new() public static TheoryData<string?> UnusableStateRows { get; } =
{ [
"unavailable", "unavailable",
"unknown", "unknown",
"UNAVAILABLE", "UNAVAILABLE",
@@ -202,8 +200,8 @@ internal static class BatteryMonitorTestData
"--1", "--1",
"low", "low",
"1 2", "1 2",
(string?)null null
}; ];
/// <summary> /// <summary>
/// Cross-product of every excluded keyword (lower and upper case) plus /// Cross-product of every excluded keyword (lower and upper case) plus
@@ -232,13 +230,5 @@ internal static class BatteryMonitorTestData
} }
/// <summary>Device counts used to exercise notification payload generation.</summary> /// <summary>Device counts used to exercise notification payload generation.</summary>
public static TheoryData<int> NotifyDeviceCounts { get; } = new() public static TheoryData<int> NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
{
1,
2,
3,
5,
10,
50
};
} }
@@ -36,9 +36,10 @@ public class BatteryNotificationServiceTests
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount) public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount)
{ {
var devices = CreateSensorInfos( var devices = CreateSensorInfos(
Enumerable.Range(0, deviceCount) [
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5))) .. Enumerable.Range(0, deviceCount)
.ToArray()); .Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
]);
var sut = CreateSut(); var sut = CreateSut();
sut.NotifyLowBattery(devices); sut.NotifyLowBattery(devices);
@@ -99,6 +100,7 @@ public class BatteryNotificationServiceTests
[Fact] [Fact]
public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount() public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount()
{ {
_loggerMock.Setup(l => l.IsEnabled(LogLevel.Information)).Returns(true);
var devices = CreateSensorInfos( var devices = CreateSensorInfos(
("sensor.a", "Device A", 2), ("sensor.a", "Device A", 2),
("sensor.b", "Device B", 3)); ("sensor.b", "Device B", 3));
@@ -106,17 +108,13 @@ public class BatteryNotificationServiceTests
var sut = CreateSut(); var sut = CreateSut();
sut.NotifyLowBattery(devices); sut.NotifyLowBattery(devices);
_loggerMock.Verify( var logInvocation = _loggerMock.Invocations
l => l.Log( .Where(invocation => invocation.Method.Name == nameof(ILogger.Log))
LogLevel.Information, .Should().ContainSingle().Subject;
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((state, _) => string.Equals( logInvocation.Arguments[0].Should().Be(LogLevel.Information);
state!.ToString(), logInvocation.Arguments[2].Should().NotBeNull();
"Sent low battery notification for 2 device(s)", logInvocation.Arguments[2]!.ToString().Should().Be("Sent low battery notification for 2 device(s)");
StringComparison.Ordinal)),
It.IsAny<Exception?>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
Times.Once);
} }
#endregion #endregion
@@ -274,7 +272,7 @@ public class BatteryNotificationServiceTests
[Fact] [Fact]
public void BuildNotificationMessage_WithNoDevices_ShouldContainOnlyHeader() public void BuildNotificationMessage_WithNoDevices_ShouldContainOnlyHeader()
{ {
var message = BatteryNotificationService.BuildNotificationMessage(Array.Empty<BatterySensorInfo>()); var message = BatteryNotificationService.BuildNotificationMessage([]);
message.Should().Be("The following devices have low battery:"); message.Should().Be("The following devices have low battery:");
message.Should().NotContain("- **"); message.Should().NotContain("- **");
@@ -12,23 +12,17 @@ namespace BatteryMonitor.Manager.Tests;
public class BatterySensorDiscoveryServiceTests public class BatterySensorDiscoveryServiceTests
{ {
private readonly Mock<IHaContext> _haContextMock; private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock; private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new();
public BatterySensorDiscoveryServiceTests()
{
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
}
private BatterySensorDiscoveryService CreateSut() private BatterySensorDiscoveryService CreateSut()
{ {
return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object); return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object);
} }
private IReadOnlyList<Entity> SetupEntities(params EntitySpec[] entities) private void SetupEntities(params EntitySpec[] entities)
{ {
return ConfigureHaContext(_haContextMock, entities); ConfigureHaContext(_haContextMock, entities);
} }
#region Discovery #region Discovery
@@ -139,11 +133,13 @@ public class BatterySensorDiscoveryServiceTests
result.Should().HaveCount(expectedIncluded ? 1 : 0); result.Should().HaveCount(expectedIncluded ? 1 : 0);
if (expectedIncluded) if (!expectedIncluded)
{ {
result[0].EntityId.Should().Be("sensor.boundary_battery"); return;
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
} }
result[0].EntityId.Should().Be("sensor.boundary_battery");
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
} }
[Fact] [Fact]
@@ -121,25 +121,25 @@ public class BoilerControlServiceTests
/// Complete truth table for a boiler that is currently ON: it may only stay on when /// 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). /// it is cheap, water is not ready and the budget is available (or overridden).
/// </summary> /// </summary>
public static IEnumerable<object[]> SwitchOnActionMatrix => public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOnActionMatrix => new()
[ {
[false, false, false, false, BoilerAction.TurnOff], { false, false, false, false, BoilerAction.TurnOff },
[false, false, false, true, BoilerAction.TurnOff], { false, false, false, true, BoilerAction.TurnOff },
[false, false, true, false, BoilerAction.TurnOff], { false, false, true, false, BoilerAction.TurnOff },
[false, false, true, true, BoilerAction.TurnOff], { false, false, true, true, BoilerAction.TurnOff },
[false, true, false, false, BoilerAction.TurnOff], { false, true, false, false, BoilerAction.TurnOff },
[false, true, false, true, BoilerAction.TurnOff], { false, true, false, true, BoilerAction.TurnOff },
[false, true, true, false, BoilerAction.TurnOff], { false, true, true, false, BoilerAction.TurnOff },
[false, true, true, true, BoilerAction.TurnOff], { false, true, true, true, BoilerAction.TurnOff },
[true, false, false, false, BoilerAction.NoChange], { true, false, false, false, BoilerAction.NoChange },
[true, false, false, true, BoilerAction.NoChange], { true, false, false, true, BoilerAction.NoChange },
[true, false, true, false, BoilerAction.TurnOff], { true, false, true, false, BoilerAction.TurnOff },
[true, false, true, true, BoilerAction.NoChange], { true, false, true, true, BoilerAction.NoChange },
[true, true, false, false, BoilerAction.TurnOff], { true, true, false, false, BoilerAction.TurnOff },
[true, true, false, true, BoilerAction.TurnOff], { true, true, false, true, BoilerAction.TurnOff },
[true, true, true, false, BoilerAction.TurnOff], { true, true, true, false, BoilerAction.TurnOff },
[true, true, true, true, BoilerAction.TurnOff] { true, true, true, true, BoilerAction.TurnOff }
]; };
[Theory] [Theory]
[MemberData(nameof(SwitchOnActionMatrix))] [MemberData(nameof(SwitchOnActionMatrix))]
@@ -160,25 +160,25 @@ public class BoilerControlServiceTests
/// Complete truth table for a boiler that is currently OFF: it may only turn on when /// 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). /// it is cheap, water is not ready and the budget is available (or overridden).
/// </summary> /// </summary>
public static IEnumerable<object[]> SwitchOffActionMatrix => public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOffActionMatrix => new()
[ {
[false, false, false, false, BoilerAction.NoChange], { false, false, false, false, BoilerAction.NoChange },
[false, false, false, true, BoilerAction.NoChange], { false, false, false, true, BoilerAction.NoChange },
[false, false, true, false, BoilerAction.NoChange], { false, false, true, false, BoilerAction.NoChange },
[false, false, true, true, BoilerAction.NoChange], { false, false, true, true, BoilerAction.NoChange },
[false, true, false, false, BoilerAction.NoChange], { false, true, false, false, BoilerAction.NoChange },
[false, true, false, true, BoilerAction.NoChange], { false, true, false, true, BoilerAction.NoChange },
[false, true, true, false, BoilerAction.NoChange], { false, true, true, false, BoilerAction.NoChange },
[false, true, true, true, BoilerAction.NoChange], { false, true, true, true, BoilerAction.NoChange },
[true, false, false, false, BoilerAction.TurnOn], { true, false, false, false, BoilerAction.TurnOn },
[true, false, false, true, BoilerAction.TurnOn], { true, false, false, true, BoilerAction.TurnOn },
[true, false, true, false, BoilerAction.NoChange], { true, false, true, false, BoilerAction.NoChange },
[true, false, true, true, BoilerAction.TurnOn], { true, false, true, true, BoilerAction.TurnOn },
[true, true, false, false, BoilerAction.NoChange], { true, true, false, false, BoilerAction.NoChange },
[true, true, false, true, BoilerAction.NoChange], { true, true, false, true, BoilerAction.NoChange },
[true, true, true, false, BoilerAction.NoChange], { true, true, true, false, BoilerAction.NoChange },
[true, true, true, true, BoilerAction.NoChange] { true, true, true, true, BoilerAction.NoChange }
]; };
[Theory] [Theory]
[MemberData(nameof(SwitchOffActionMatrix))] [MemberData(nameof(SwitchOffActionMatrix))]
@@ -8,37 +8,37 @@ public class BoilerMonitorConfigTests
private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId; private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId;
private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId; private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId;
public static IEnumerable<object?[]> ConfigurationCases => public static TheoryData<string, string?, string?, int?, double?, bool> ConfigurationCases => new()
[ {
["fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true], { "fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true },
["minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.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], { "poll interval of one second", PowerEntityId, SwitchEntityId, 1, 5.0, true },
["maximum poll interval", PowerEntityId, SwitchEntityId, int.MaxValue, 5.0, true], { "maximum poll interval", PowerEntityId, SwitchEntityId, int.MaxValue, 5.0, true },
["smallest positive threshold", PowerEntityId, SwitchEntityId, 30, double.Epsilon, true], { "smallest positive threshold", PowerEntityId, SwitchEntityId, 30, double.Epsilon, true },
["maximum threshold", PowerEntityId, SwitchEntityId, 30, double.MaxValue, true], { "maximum threshold", PowerEntityId, SwitchEntityId, 30, double.MaxValue, true },
["infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true], { "infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true },
["power entity id null", (string?)null, SwitchEntityId, 30, 5.0, false], { "power entity id null", null, SwitchEntityId, 30, 5.0, false },
["power entity id empty", "", 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 whitespace", " ", SwitchEntityId, 30, 5.0, false },
["power entity id tabs and newlines", "\t\n", 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 null", PowerEntityId, null, 30, 5.0, false },
["switch entity id empty", PowerEntityId, "", 30, 5.0, false], { "switch entity id empty", PowerEntityId, "", 30, 5.0, false },
["switch entity id whitespace", 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], { "both entity ids null", null, null, 30, 5.0, false },
["poll interval null", PowerEntityId, SwitchEntityId, (int?)null, 5.0, false], { "poll interval null", PowerEntityId, SwitchEntityId, null, 5.0, false },
["poll interval zero", PowerEntityId, SwitchEntityId, 0, 5.0, false], { "poll interval zero", PowerEntityId, SwitchEntityId, 0, 5.0, false },
["poll interval negative", PowerEntityId, SwitchEntityId, -1, 5.0, false], { "poll interval negative", PowerEntityId, SwitchEntityId, -1, 5.0, false },
["poll interval minimum value", PowerEntityId, SwitchEntityId, int.MinValue, 5.0, false], { "poll interval minimum value", PowerEntityId, SwitchEntityId, int.MinValue, 5.0, false },
["threshold null", PowerEntityId, SwitchEntityId, 30, (double?)null, false], { "threshold null", PowerEntityId, SwitchEntityId, 30, null, false },
["threshold zero", PowerEntityId, SwitchEntityId, 30, 0.0, false], { "threshold zero", PowerEntityId, SwitchEntityId, 30, 0.0, false },
["threshold negative", PowerEntityId, SwitchEntityId, 30, -1.0, false], { "threshold negative", PowerEntityId, SwitchEntityId, 30, -1.0, false },
["threshold minimum value", PowerEntityId, SwitchEntityId, 30, double.MinValue, false], { "threshold minimum value", PowerEntityId, SwitchEntityId, 30, double.MinValue, false },
["threshold NaN", PowerEntityId, SwitchEntityId, 30, double.NaN, false], { "threshold NaN", PowerEntityId, SwitchEntityId, 30, double.NaN, false },
["threshold negative infinity", PowerEntityId, SwitchEntityId, 30, double.NegativeInfinity, false] { "threshold negative infinity", PowerEntityId, SwitchEntityId, 30, double.NegativeInfinity, false }
]; };
[Theory] [Theory]
[MemberData(nameof(ConfigurationCases))] [MemberData(nameof(ConfigurationCases))]
@@ -72,7 +72,7 @@ public class BoilerMonitorEntityServiceTests
} }
result.Should().NotBeNull(); result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(expectedRunTime.Value); result.AccumulatedRunTime.Should().Be(expectedRunTime.Value);
result.SessionCount.Should().Be(2); result.SessionCount.Should().Be(2);
} }
@@ -94,7 +94,7 @@ public class BoilerMonitorEntityServiceTests
} }
result.Should().NotBeNull(); result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(1)); result.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(1));
result.SessionCount.Should().Be(expectedSessionCount.Value); result.SessionCount.Should().Be(expectedSessionCount.Value);
} }
@@ -107,7 +107,7 @@ public class BoilerMonitorEntityServiceTests
var result = CreateSut().ReadPersistedState(); var result = CreateSut().ReadPersistedState();
result.Should().NotBeNull(); result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(2)); result.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(2));
result.SessionCount.Should().Be(3); result.SessionCount.Should().Be(3);
result.SkipPriceCapState.Should().Be("ON"); result.SkipPriceCapState.Should().Be("ON");
result.BudgetOverrideState.Should().Be("OFF"); result.BudgetOverrideState.Should().Be("OFF");
@@ -127,7 +127,7 @@ public class BoilerMonitorEntityServiceTests
var result = CreateSut().ReadPersistedState(); var result = CreateSut().ReadPersistedState();
result.Should().NotBeNull(); result.Should().NotBeNull();
result!.SkipPriceCapState.Should().Be(switchState); result.SkipPriceCapState.Should().Be(switchState);
result.BudgetOverrideState.Should().Be(switchState); result.BudgetOverrideState.Should().Be(switchState);
} }
@@ -362,8 +362,8 @@ public class BoilerMonitorEntityServiceTests
await CreateSut().CreateEntitiesAsync(); await CreateSut().CreateEntitiesAsync();
createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems(); createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems();
createdEntityIds.Should().Contain(new[] createdEntityIds.Should().Contain(
{ [
ConfigPowerEntityId, ConfigPowerEntityId,
ConfigSwitchEntityId, ConfigSwitchEntityId,
ConfigPollIntervalEntityId, ConfigPollIntervalEntityId,
@@ -373,7 +373,7 @@ public class BoilerMonitorEntityServiceTests
TodayRuntimeEntityId, TodayRuntimeEntityId,
BudgetExhaustedEntityId, BudgetExhaustedEntityId,
AutoManagementEntityId AutoManagementEntityId
}); ]);
} }
[Fact] [Fact]
@@ -1,5 +1,4 @@
using System.Text.Json; using System.Text.Json;
using BoilerMonitor.Models;
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
using Microsoft.Extensions.Time.Testing; using Microsoft.Extensions.Time.Testing;
using Moq; using Moq;
@@ -47,19 +46,6 @@ internal static class BoilerMonitorTestData
CleanupEntitiesOnStartup = cleanupEntitiesOnStartup 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( public static BoilerMonitorUpdateContext CreateUpdateContext(
TimeSpan? todayRunTime = null, TimeSpan? todayRunTime = null,
TimeSpan? remainingTime = null, TimeSpan? remainingTime = null,
@@ -80,13 +66,10 @@ internal static class BoilerMonitorTestData
BudgetExhausted = budgetExhausted, BudgetExhausted = budgetExhausted,
SessionCount = sessionCount, SessionCount = sessionCount,
BudgetHours = budgetHours, BudgetHours = budgetHours,
IsCurrentlyHeating = false,
WaterReady = waterReady, WaterReady = waterReady,
BoilerSwitchState = boilerSwitchState, BoilerSwitchState = boilerSwitchState,
BoilerPowerWatts = boilerPowerWatts, BoilerPowerWatts = boilerPowerWatts,
CooldownSince = cooldownSince, CooldownSince = cooldownSince,
IsNowCheap = isNowCheap,
NextCheapIntervalStart = null
}; };
/// <summary> /// <summary>
@@ -114,156 +97,170 @@ internal static class BoilerMonitorTestData
public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince) => public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince) =>
CreateEntityStateWithAttributes(new Dictionary<string, object?> { ["cooldown_since"] = cooldownSince }); CreateEntityStateWithAttributes(new Dictionary<string, object?> { ["cooldown_since"] = cooldownSince });
public static void SetupEntityStates( extension(Mock<IHaContext> haContextMock)
this Mock<IHaContext> haContextMock,
IReadOnlyDictionary<string, string?> states)
{ {
foreach (var (entityId, state) in states) public void SetupEntityStates(IReadOnlyDictionary<string, string?> states)
{ {
var entityState = state is null ? null : CreateEntityState(state); foreach (var (entityId, state) in states)
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState); {
var entityState = state is null ? null : CreateEntityState(state);
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
}
} }
}
public static void SetupEntityState( public void SetupEntityState(string entityId, EntityState? entityState) =>
this Mock<IHaContext> haContextMock, haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
string entityId, }
EntityState? entityState) =>
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
/// <summary> /// <summary>
/// Entity-state samples for the today-runtime sensor: valid values with the expected /// 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. /// <see cref="TimeSpan"/>, plus unavailable/negative/overflow values that must be rejected.
/// </summary> /// </summary>
public static IEnumerable<object?[]> RuntimeStateSamples() public static TheoryData<string?, TimeSpan?> RuntimeStateSamples()
{ {
yield return ["7200", TimeSpan.FromHours(2)]; var data = new TheoryData<string?, TimeSpan?>();
yield return ["0", TimeSpan.Zero]; data.Add("7200", TimeSpan.FromHours(2));
yield return ["134.66", TimeSpan.FromSeconds(134.66)]; data.Add("0", TimeSpan.Zero);
yield return ["1E3", TimeSpan.FromSeconds(1000)]; data.Add("134.66", TimeSpan.FromSeconds(134.66));
yield return ["0.001", TimeSpan.FromSeconds(0.001)]; data.Add("1E3", TimeSpan.FromSeconds(1000));
yield return [" 60 ", TimeSpan.FromSeconds(60)]; data.Add("0.001", TimeSpan.FromSeconds(0.001));
yield return ["86400", TimeSpan.FromDays(1)]; data.Add(" 60 ", TimeSpan.FromSeconds(60));
yield return ["1e9", TimeSpan.FromSeconds(1e9)]; data.Add("86400", TimeSpan.FromDays(1));
data.Add("1e9", TimeSpan.FromSeconds(1e9));
data.Add(null, null);
data.Add("", null);
data.Add(" ", null);
data.Add("\t", null);
data.Add("unavailable", null);
data.Add("unknown", null);
data.Add("Unavailable", null);
data.Add("not_a_number", null);
data.Add("NaN", null);
data.Add("Infinity", null);
data.Add("1e308", null);
data.Add("-1", null);
data.Add("-0.001", null);
return data;
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> /// <summary>
/// Entity-state samples for the session-count sensor, including the int boundaries. /// Entity-state samples for the session-count sensor, including the int boundaries.
/// </summary> /// </summary>
public static IEnumerable<object?[]> SessionCountStateSamples() public static TheoryData<string?, int?> SessionCountStateSamples()
{ {
yield return ["0", 0]; var data = new TheoryData<string?, int?>();
yield return ["3", 3]; data.Add("0", 0);
yield return [" 2 ", 2]; data.Add("3", 3);
yield return ["+4", 4]; data.Add(" 2 ", 2);
yield return ["2147483647", int.MaxValue]; data.Add("+4", 4);
data.Add("2147483647", int.MaxValue);
data.Add(null, null);
data.Add("", null);
data.Add(" ", null);
data.Add("\t", null);
data.Add("unavailable", null);
data.Add("unknown", null);
data.Add("abc", null);
data.Add("1.5", null);
data.Add("-1", null);
data.Add("2147483648", null);
data.Add("1e3", null);
return data;
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> /// <summary>
/// Water-ready detection samples around the heating threshold, including negative, /// Water-ready detection samples around the heating threshold, including negative,
/// zero, exact-boundary, huge and NaN readings. /// zero, exact-boundary, huge and NaN readings.
/// </summary> /// </summary>
public static IEnumerable<object?[]> PowerReadingSamples() public static TheoryData<string, double, bool> PowerReadingSamples()
{ {
yield return ["negative sensor glitch", -1_000.0, true]; var data = new TheoryData<string, double, bool>();
yield return ["just below zero", -0.001, true]; data.Add("negative sensor glitch", -1_000.0, true);
yield return ["zero", 0.0, true]; data.Add("just below zero", -0.001, true);
yield return ["just below threshold", 4.999, true]; data.Add("zero", 0.0, true);
yield return ["exactly at threshold", 5.0, false]; data.Add("just below threshold", 4.999, true);
yield return ["just above threshold", 5.001, false]; data.Add("exactly at threshold", 5.0, false);
yield return ["actively heating", 2_150.0, false]; data.Add("just above threshold", 5.001, false);
yield return ["maximum", double.MaxValue, false]; data.Add("actively heating", 2_150.0, false);
yield return ["not-a-number", double.NaN, true]; data.Add("maximum", double.MaxValue, false);
data.Add("not-a-number", double.NaN, true);
return data;
} }
/// <summary> /// <summary>
/// Elapsed-time sweep showing that the water-ready cooldown never expires on its own. /// Elapsed-time sweep showing that the water-ready cooldown never expires on its own.
/// </summary> /// </summary>
public static IEnumerable<object?[]> GeneratedElapsedTimes() public static TheoryData<TimeSpan> GeneratedElapsedTimes()
{ {
foreach (var hours in new[] { 1, 2, 6, 12, 23, 24, 25, 48, 168 }) var data = new TheoryData<TimeSpan>();
{ data.Add(TimeSpan.FromHours(1));
yield return [TimeSpan.FromHours(hours)]; data.Add(TimeSpan.FromHours(2));
} data.Add(TimeSpan.FromHours(6));
data.Add(TimeSpan.FromHours(12));
data.Add(TimeSpan.FromHours(23));
data.Add(TimeSpan.FromHours(24));
data.Add(TimeSpan.FromHours(25));
data.Add(TimeSpan.FromHours(48));
data.Add(TimeSpan.FromHours(168));
return data;
} }
/// <summary> /// <summary>
/// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end /// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end
/// timestamps carrying non-zero offsets. /// timestamps carrying non-zero offsets.
/// </summary> /// </summary>
public static IEnumerable<object?[]> CooldownRestoreSamples() public static TheoryData<string, DateTimeOffset, DateTimeOffset, bool> CooldownRestoreSamples()
{ {
yield return ["30 minutes ago", BaseTime, BaseTime - TimeSpan.FromMinutes(30), true]; var data = new TheoryData<string, DateTimeOffset, DateTimeOffset, bool>();
yield return ["5 hours ago", BaseTime, BaseTime - TimeSpan.FromHours(5), true]; data.Add("30 minutes ago", BaseTime, BaseTime - TimeSpan.FromMinutes(30), true);
yield return ["exactly at today's UTC midnight", BaseTime, TodayMidnight(), true]; data.Add("5 hours ago", BaseTime, BaseTime - TimeSpan.FromHours(5), true);
yield return ["one tick after today's UTC midnight", BaseTime, TodayMidnight().AddTicks(1), true]; data.Add("exactly at today's UTC midnight", BaseTime, TodayMidnight(), true);
yield return ["one tick before today's UTC midnight", BaseTime, TodayMidnight().AddTicks(-1), false]; data.Add("one tick after today's UTC midnight", BaseTime, TodayMidnight().AddTicks(1), true);
yield return ["one second before today's UTC midnight", BaseTime, TodayMidnight().AddSeconds(-1), false]; data.Add("one tick before today's UTC midnight", BaseTime, TodayMidnight().AddTicks(-1), false);
yield return ["yesterday same time", BaseTime, BaseTime.AddDays(-1), false]; data.Add("one second before today's UTC midnight", BaseTime, TodayMidnight().AddSeconds(-1), false);
yield return ["two days ago", BaseTime, BaseTime.AddDays(-2), false]; data.Add("yesterday same time", BaseTime, BaseTime.AddDays(-1), false);
yield return ["future timestamp", BaseTime, BaseTime.AddHours(1), true]; data.Add("two days ago", BaseTime, BaseTime.AddDays(-2), false);
yield return ["maximum timestamp", BaseTime, DateTimeOffset.MaxValue, true]; data.Add("future timestamp", BaseTime, BaseTime.AddHours(1), true);
data.Add("maximum timestamp", BaseTime, DateTimeOffset.MaxValue, true);
// Europe DST starts 2026-03-29 02:00 CET → 03:00 CEST. // 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. // now = 03:30+02:00 = 01:30Z, so UTC midnight is 2026-03-29T00:00Z.
yield return data.Add(
[
"DST spring-forward, same UTC day", "DST spring-forward, same UTC day",
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)), new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)), new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)),
true true
]; );
yield return data.Add(
[
"DST spring-forward, previous UTC day", "DST spring-forward, previous UTC day",
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)), new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)), new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)),
false false
]; );
// Europe DST ends 2026-10-25 03:00 CEST → 02:00 CET. The 02:30 wall-clock hour occurs twice. // 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. // now = 03:30+01:00 = 02:30Z, timestamp 02:30+02:00 = 00:30Z is still "today" in UTC.
yield return data.Add(
[
"DST fall-back, ambiguous local hour", "DST fall-back, ambiguous local hour",
new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)), new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)),
new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)), new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)),
true true
]; );
yield return data.Add(
[
"crossing midnight between restore and now", "crossing midnight between restore and now",
new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero), new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero),
new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero), new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero),
false false
]; );
return data;
} }
private static DateTimeOffset TodayMidnight() => private static DateTimeOffset TodayMidnight() =>
@@ -21,6 +21,7 @@ public class LeakMonitorInitTests
public LeakMonitorInitTests() public LeakMonitorInitTests()
{ {
_haContextMock.Setup(h => h.StateAllChanges()).Returns(_stateChanges); _haContextMock.Setup(h => h.StateAllChanges()).Returns(_stateChanges);
_loggerMock.Setup(l => l.IsEnabled(It.IsAny<LogLevel>())).Returns(true);
} }
private LeakMonitorInit CreateSut(LeakMonitorOptions? options = null) private LeakMonitorInit CreateSut(LeakMonitorOptions? options = null)
@@ -40,14 +41,12 @@ public class LeakMonitorInitTests
private void VerifyLogged(LogLevel level, Times times) private void VerifyLogged(LogLevel level, Times times)
{ {
_loggerMock.Verify( var logCount = _loggerMock.Invocations.Count(invocation =>
l => l.Log( invocation.Method.Name == nameof(ILogger.Log) &&
level, invocation.Arguments[0] is LogLevel loggedLevel &&
It.IsAny<EventId>(), loggedLevel == level);
It.IsAny<It.IsAnyType>(),
It.IsAny<Exception?>(), times.Validate(logCount);
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
times);
} }
#region HandleStateChange #region HandleStateChange
@@ -170,7 +169,7 @@ public class LeakMonitorInitTests
[MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))] [MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))]
public void InitializeAsync_WithBlankSensorId_ShouldStillSubscribeAndForward(string sensorEntityId) public void InitializeAsync_WithBlankSensorId_ShouldStillSubscribeAndForward(string sensorEntityId)
{ {
var sut = CreateSut(LeakMonitorTestData.CreateOptions(sensorEntityIds: [sensorEntityId])); CreateSut(LeakMonitorTestData.CreateOptions(sensorEntityIds: [sensorEntityId]));
_stateChanges.SubscriptionCount.Should().Be(1); _stateChanges.SubscriptionCount.Should().Be(1);
@@ -20,7 +20,7 @@ internal static class LeakMonitorTestData
public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId]; public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId];
public static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); private static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
/// <summary> /// <summary>
/// Builds leak monitor options with production-compatible defaults. /// Builds leak monitor options with production-compatible defaults.
@@ -63,8 +63,8 @@ internal static class LeakMonitorTestData
/// States that must never send or dismiss a leak notification. Covers unavailable, /// States that must never send or dismiss a leak notification. Covers unavailable,
/// unknown, blank, null and near-miss strings (the comparison is exact apart from casing). /// unknown, blank, null and near-miss strings (the comparison is exact apart from casing).
/// </summary> /// </summary>
public static TheoryData<string?> NonActionableStateCases { get; } = new() public static TheoryData<string?> NonActionableStateCases { get; } =
{ [
"unavailable", "unavailable",
"UNAVAILABLE", "UNAVAILABLE",
"unknown", "unknown",
@@ -80,18 +80,18 @@ internal static class LeakMonitorTestData
"1", "1",
"true", "true",
null null
}; ];
/// <summary> /// <summary>
/// Blank but non-null sensor ids. Production does not validate ids, so these are /// Blank but non-null sensor ids. Production does not validate ids, so these are
/// subscribed and forwarded verbatim. /// subscribed and forwarded verbatim.
/// </summary> /// </summary>
public static TheoryData<string> BlankSensorIds { get; } = new() public static TheoryData<string> BlankSensorIds { get; } =
{ [
string.Empty, string.Empty,
" ", " ",
"\t" "\t"
}; ];
/// <summary> /// <summary>
/// (sensor id, expected notification id) rows for the id sanitising rules: /// (sensor id, expected notification id) rows for the id sanitising rules:
@@ -132,13 +132,13 @@ internal static class LeakMonitorTestData
/// <summary> /// <summary>
/// Repetition counts used to exercise duplicate suppression and zero-cooldown behaviour. /// Repetition counts used to exercise duplicate suppression and zero-cooldown behaviour.
/// </summary> /// </summary>
public static TheoryData<int> RepeatedNotificationCounts { get; } = new() public static TheoryData<int> RepeatedNotificationCounts { get; } =
{ [
2, 2,
3, 3,
5, 5,
10 10
}; ];
/// <summary> /// <summary>
/// A deterministic detection/recovery sequence. The repeated "on" transition is filtered /// A deterministic detection/recovery sequence. The repeated "on" transition is filtered
@@ -157,7 +157,7 @@ internal static class LeakMonitorTestData
/// <summary> /// <summary>
/// Builds an <see cref="EntityState"/>, or <c>null</c> when the entity has no state at all. /// Builds an <see cref="EntityState"/>, or <c>null</c> when the entity has no state at all.
/// </summary> /// </summary>
public static EntityState? CreateOptionalState(string? state) => private static EntityState? CreateOptionalState(string? state) =>
state is null ? null : new EntityState { State = state }; state is null ? null : new EntityState { State = state };
public static StateChange CreateStateChange( public static StateChange CreateStateChange(
@@ -171,9 +171,7 @@ internal static class LeakMonitorTestData
IHaContext haContext, IHaContext haContext,
string entityId, string entityId,
params (string? OldState, string? NewState)[] transitions) => params (string? OldState, string? NewState)[] transitions) =>
transitions [.. transitions.Select(transition => CreateStateChange(haContext, entityId, transition.OldState, transition.NewState))];
.Select(transition => CreateStateChange(haContext, entityId, transition.OldState, transition.NewState))
.ToList();
/// <summary>One captured <c>IHaContext.CallService</c> invocation.</summary> /// <summary>One captured <c>IHaContext.CallService</c> invocation.</summary>
public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data); public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data);
@@ -85,7 +85,7 @@ public class LeakNotificationServiceTests
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock); var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
var sut = CreateSut(); var sut = CreateSut();
const string sensorId = LeakMonitorTestData.AquariumSensorId; const string sensorId = LeakMonitorTestData.AquariumSensorId;
var expectedMessage = $"Water detected by {sensorId}! Check immediately."; const string expectedMessage = $"Water detected by {sensorId}! Check immediately.";
sut.SendLeakAlert(sensorId); sut.SendLeakAlert(sensorId);
@@ -136,8 +136,11 @@ public class LeakNotificationServiceTests
sut.SendLeakAlert(sensorId); sut.SendLeakAlert(sensorId);
var persistentCall = calls.Single(c => var persistentCall = calls.Single(c =>
c.Domain == LeakMonitorConsts.PersistentNotificationDomain && c is
c.Service == LeakMonitorConsts.PersistentNotificationCreateService); {
Domain: LeakMonitorConsts.PersistentNotificationDomain,
Service: LeakMonitorConsts.PersistentNotificationCreateService
});
LeakMonitorTestData.SerializePayload(persistentCall.Data) LeakMonitorTestData.SerializePayload(persistentCall.Data)
.GetProperty("notification_id") .GetProperty("notification_id")
@@ -345,7 +348,7 @@ public class LeakNotificationServiceTests
public void BuildNotificationId_WithNullSensorId_ShouldThrow() public void BuildNotificationId_WithNullSensorId_ShouldThrow()
{ {
// Production has no null guard; the string.Replace call fails before any prefix is built. // Production has no null guard; the string.Replace call fails before any prefix is built.
Action act = () => LeakNotificationService.BuildNotificationId(null!); var act = () => LeakNotificationService.BuildNotificationId(null!);
act.Should().Throw<NullReferenceException>(); act.Should().Throw<NullReferenceException>();
} }
@@ -227,7 +227,7 @@ public class LightMonitorInitTests
{ {
var sut = CreateSut(); var sut = CreateSut();
var act = () => sut.InitializeAsync(); var act = sut.InitializeAsync;
await act.Should().NotThrowAsync(); await act.Should().NotThrowAsync();
} }
@@ -151,12 +151,12 @@ internal static class LightMonitorTestData
/// <summary> /// <summary>
/// Person id configurations that resolve to "nobody tracked". /// Person id configurations that resolve to "nobody tracked".
/// </summary> /// </summary>
public static TheoryData<string[]> NoPersonEntityIdSets { get; } = new() public static TheoryData<string[]> NoPersonEntityIdSets { get; } =
{ [
{ [] }, [],
{ [string.Empty] }, [string.Empty],
{ [" "] } [" "]
}; ];
private static TheoryData<string?[]> CreatePresenceStateMatrix() private static TheoryData<string?[]> CreatePresenceStateMatrix()
{ {
@@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Moq; using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using LightMonitorManager; using LightMonitorManager;
namespace LightMonitor.Manager.Tests; namespace LightMonitor.Manager.Tests;
@@ -49,20 +49,20 @@ public class CheapestIntervalsFinderTests
#region FindCheapestIntervals #region FindCheapestIntervals
public static IEnumerable<object[]> FilteringCases => public static TheoryData<string, double[], int, double, double, int> FilteringCases => new()
[ {
["deadline includes interval ending exactly at it", new[] { 4.93, 5.63, 6.20 }, 10, double.MaxValue, 1_800.0, 2], { "deadline includes interval ending exactly at it", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_800.0, 2 },
["deadline excludes interval ending one second late", new[] { 4.93, 5.63, 6.20 }, 10, double.MaxValue, 1_799.0, 1], { "deadline excludes interval ending one second late", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_799.0, 1 },
["deadline before first interval", new[] { 4.93, 5.63, 6.20 }, 10, double.MaxValue, -1.0, 0], { "deadline before first interval", [4.93, 5.63, 6.20], 10, double.MaxValue, -1.0, 0 },
["price cap is inclusive", new[] { 12.50, 12.51 }, 10, 12.50, 86_400.0, 1], { "price cap is inclusive", [12.50, 12.51], 10, 12.50, 86_400.0, 1 },
["zero price cap keeps non-positive prices", new[] { -1.50, 0.0, 0.01, 2.0 }, 10, 0.0, 86_400.0, 2], { "zero price cap keeps non-positive prices", [-1.50, 0.0, 0.01, 2.0], 10, 0.0, 86_400.0, 2 },
["all prices above cap", new[] { 17.91, 24.92, 22.44 }, 4, 10.0, 86_400.0, 0], { "all prices above cap", [17.91, 24.92, 22.44], 4, 10.0, 86_400.0, 0 },
["fewer available than requested", new[] { 6.20, 8.96 }, 10, double.MaxValue, 86_400.0, 2], { "fewer available than requested", [6.20, 8.96], 10, double.MaxValue, 86_400.0, 2 },
["zero intervals requested", new[] { 17.91, 6.20 }, 0, double.MaxValue, 86_400.0, 0], { "zero intervals requested", [17.91, 6.20], 0, double.MaxValue, 86_400.0, 0 },
["negative intervals requested", new[] { 17.91, 6.20 }, -1, double.MaxValue, 86_400.0, 0], { "negative intervals requested", [17.91, 6.20], -1, double.MaxValue, 86_400.0, 0 },
["deadline and price cap combined", new[] { 17.91, 6.20, 12.50, 4.93, 8.96, 2.50 }, 2, 10.0, 4_500.0, 2], { "deadline and price cap combined", [17.91, 6.20, 12.50, 4.93, 8.96, 2.50], 2, 10.0, 4_500.0, 2 },
["all prices equal", new[] { 12.50, 12.50, 12.50, 12.50, 12.50 }, 3, double.MaxValue, 86_400.0, 3] { "all prices equal", [12.50, 12.50, 12.50, 12.50, 12.50], 3, double.MaxValue, 86_400.0, 3 }
]; };
[Theory] [Theory]
[MemberData(nameof(FilteringCases))] [MemberData(nameof(FilteringCases))]
@@ -304,19 +304,19 @@ public class CheapestIntervalsFinderTests
#region IsCurrentIntervalCheap #region IsCurrentIntervalCheap
public static IEnumerable<object[]> CurrentIntervalCases => public static TheoryData<string, int, CheapestIntervalResult[], bool> CurrentIntervalCases => new()
[ {
["inside interval", 10 * Hour + 7 * 60, new[] { Interval(10 * Hour, 10 * Hour + Quarter) }, true], { "inside interval", 10 * Hour + 7 * 60, [Interval(10 * Hour, 10 * Hour + Quarter)], true },
["exactly at start", 10 * Hour, new[] { Interval(10 * Hour, 10 * Hour + Quarter) }, true], { "exactly at start", 10 * Hour, [Interval(10 * Hour, 10 * Hour + Quarter)], true },
["exactly at end", 10 * Hour + Quarter, new[] { Interval(10 * Hour, 10 * Hour + Quarter) }, false], { "exactly at end", 10 * Hour + Quarter, [Interval(10 * Hour, 10 * Hour + Quarter)], false },
["outside all intervals", 12 * Hour, new[] { Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter) }, false], { "outside all intervals", 12 * Hour, [Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter)], false },
["boundary between adjacent intervals", 10 * Hour + Quarter, new[] { Interval(10 * Hour, 10 * Hour + Quarter, price: 8.96, rank: 1), Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, price: 6.20, rank: 2) }, true], { "boundary between adjacent intervals", 10 * Hour + Quarter, [Interval(10 * Hour, 10 * Hour + Quarter, price: 8.96, rank: 1), Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, price: 6.20, rank: 2)], true },
["unsorted intervals", 14 * Hour + 5 * 60, new[] { Interval(14 * Hour, 14 * Hour + Quarter, price: 4.93, rank: 2), Interval(10 * Hour, 10 * Hour + Quarter, price: 6.20, rank: 1) }, true], { "unsorted intervals", 14 * Hour + 5 * 60, [Interval(14 * Hour, 14 * Hour + Quarter, price: 4.93, rank: 2), Interval(10 * Hour, 10 * Hour + Quarter, price: 6.20, rank: 1)], true },
["before first interval", 10 * Hour - 1, new[] { Interval(10 * Hour, 10 * Hour + Quarter) }, false], { "before first interval", 10 * Hour - 1, [Interval(10 * Hour, 10 * Hour + Quarter)], false },
["in gap between intervals", 10 * Hour + 2 * Quarter, new[] { Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter) }, false], { "in gap between intervals", 10 * Hour + 2 * Quarter, [Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter)], false },
["middle of three consecutive intervals", 10 * Hour + Quarter + 5 * 60, new[] { Interval(10 * Hour, 10 * Hour + Quarter, rank: 1), Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, rank: 2), Interval(10 * Hour + 2 * Quarter, 10 * Hour + 3 * Quarter, rank: 3) }, true], { "middle of three consecutive intervals", 10 * Hour + Quarter + 5 * 60, [Interval(10 * Hour, 10 * Hour + Quarter, rank: 1), Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, rank: 2), Interval(10 * Hour + 2 * Quarter, 10 * Hour + 3 * Quarter, rank: 3)], true },
["empty interval list", 12 * Hour, Array.Empty<CheapestIntervalResult>(), false] { "empty interval list", 12 * Hour, [], false }
]; };
[Theory] [Theory]
[MemberData(nameof(CurrentIntervalCases))] [MemberData(nameof(CurrentIntervalCases))]
@@ -161,17 +161,17 @@ public class CompactNordPoolDayPriceTests
act.Should().Throw<ArgumentNullException>(); act.Should().Throw<ArgumentNullException>();
} }
public static IEnumerable<object[]> InvalidJsonPayloads => public static TheoryData<string, string> InvalidJsonPayloads => new()
[ {
["empty array", "[]"], { "empty array", "[]" },
["too few elements", "[1,2]"], { "too few elements", "[1,2]" },
["extra elements", "[1,2,3,4]"], { "extra elements", "[1,2,3,4]" },
["missing end of array", "[1,2,3"], { "missing end of array", "[1,2,3" },
["non-numeric start", "[\"abc\",2,3]"], { "non-numeric start", "[\"abc\",2,3]" },
["non-numeric end", "[1,\"abc\",3]"], { "non-numeric end", "[1,\"abc\",3]" },
["non-numeric price", "[1,2,\"abc\"]"], { "non-numeric price", "[1,2,\"abc\"]" },
["object instead of array", "{\"start\":1}"] { "object instead of array", "{\"start\":1}" }
]; };
[Theory] [Theory]
[MemberData(nameof(InvalidJsonPayloads))] [MemberData(nameof(InvalidJsonPayloads))]
@@ -249,7 +249,7 @@ public class CompactNordPoolDayPriceTests
var roundTripped = JsonSerializer.Deserialize<List<CompactNordPoolDayPrice>>(json); var roundTripped = JsonSerializer.Deserialize<List<CompactNordPoolDayPrice>>(json);
roundTripped.Should().NotBeNull(); roundTripped.Should().NotBeNull();
roundTripped!.Should().HaveCount(compact.Count); roundTripped.Should().HaveCount(compact.Count);
roundTripped.Should().BeEquivalentTo(compact); roundTripped.Should().BeEquivalentTo(compact);
} }
@@ -27,7 +27,7 @@ public class NordPoolEntityServiceTests
public void GetInitEntitiesList_ShouldReturnAllEntities() public void GetInitEntitiesList_ShouldReturnAllEntities()
{ {
// Act // Act
var result = _sut.GetInitEntitiesList("EUR/kWh"); var result = NordPoolEntityService.GetInitEntitiesList("EUR/kWh");
// Assert // Assert
result.Should().NotBeNull(); result.Should().NotBeNull();
@@ -45,7 +45,7 @@ public class NordPoolEntityServiceTests
public void GetInitEntitiesList_ShouldHaveCorrectEntityProperties() public void GetInitEntitiesList_ShouldHaveCorrectEntityProperties()
{ {
// Act // Act
var result = _sut.GetInitEntitiesList("EUR/kWh"); var result = NordPoolEntityService.GetInitEntitiesList("EUR/kWh");
// Assert // Assert
var entity = result.First(e => e.EntityId == "sensor.nordpool_current_price"); var entity = result.First(e => e.EntityId == "sensor.nordpool_current_price");
@@ -58,7 +58,7 @@ public class NordPoolEntityServiceTests
public void GetInitEntitiesList_CurrentPriceEntity_ShouldHaveMonetaryDeviceClassConfig() public void GetInitEntitiesList_CurrentPriceEntity_ShouldHaveMonetaryDeviceClassConfig()
{ {
// Act // Act
var result = _sut.GetInitEntitiesList("EUR/kWh"); var result = NordPoolEntityService.GetInitEntitiesList("EUR/kWh");
// Assert // Assert
var currentPriceEntity = result.First(e => e.EntityId == "sensor.nordpool_current_price"); var currentPriceEntity = result.First(e => e.EntityId == "sensor.nordpool_current_price");
@@ -72,7 +72,7 @@ public class NordPoolEntityServiceTests
public void GetInitEntitiesList_ShouldContainExpectedDomains() public void GetInitEntitiesList_ShouldContainExpectedDomains()
{ {
// Act // Act
var result = _sut.GetInitEntitiesList("EUR/kWh"); var result = NordPoolEntityService.GetInitEntitiesList("EUR/kWh");
// Assert // Assert
result.Should().OnlyContain(e => e.Domain == "sensor" || e.Domain == "button"); result.Should().OnlyContain(e => e.Domain == "sensor" || e.Domain == "button");
@@ -82,7 +82,7 @@ public class NordPoolEntityServiceTests
public void GetInitEntitiesList_AllEntities_ShouldHaveUniqueEntityIds() public void GetInitEntitiesList_AllEntities_ShouldHaveUniqueEntityIds()
{ {
// Act // Act
var result = _sut.GetInitEntitiesList("EUR/kWh"); var result = NordPoolEntityService.GetInitEntitiesList("EUR/kWh");
// Assert // Assert
result.Select(e => e.EntityId).Should().OnlyHaveUniqueItems(); result.Select(e => e.EntityId).Should().OnlyHaveUniqueItems();
@@ -115,12 +115,9 @@ public class NordPoolEntityServiceTests
.Returns(() => .Returns(() =>
{ {
callCount++; callCount++;
if (callCount == 2) return callCount == 2
{ ? throw new InvalidOperationException("Entity creation failed")
throw new InvalidOperationException("Entity creation failed"); : Task.CompletedTask;
}
return Task.CompletedTask;
}); });
// Act // Act
@@ -435,13 +432,13 @@ public class NordPoolEntityServiceTests
Times.Once); Times.Once);
} }
public static IEnumerable<object?[]> MergedPriceScenarios() public static TheoryData<string, NordPoolPrice?, NordPoolPrice?, int> MergedPriceScenarios()
{ {
var data = new TheoryData<string, NordPoolPrice?, NordPoolPrice?, int>();
var todayStart = new DateTime(2026, 3, 31, 6, 0, 0, DateTimeKind.Utc); var todayStart = new DateTime(2026, 3, 31, 6, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 6, 0, 0, DateTimeKind.Utc); var tomorrowStart = new DateTime(2026, 4, 1, 6, 0, 0, DateTimeKind.Utc);
yield return data.Add(
[
"today and tomorrow with null-start entry filtered", "today and tomorrow with null-start entry filtered",
new NordPoolPrice new NordPoolPrice
{ {
@@ -456,27 +453,26 @@ public class NordPoolEntityServiceTests
Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }]
}, },
2 2
]; );
yield return data.Add(
[
"only today", "only today",
new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 }] }, new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 }] },
new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] },
1 1
]; );
yield return data.Add(
[
"only tomorrow", "only tomorrow",
new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] },
new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] }, new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] },
1 1
]; );
yield return ["empty lists", new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] }, 0]; data.Add("empty lists", new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] }, 0);
yield return ["null lists", new NordPoolPrice { Prices = null }, new NordPoolPrice { Prices = null }, 0]; data.Add("null lists", new NordPoolPrice { Prices = null }, new NordPoolPrice { Prices = null }, 0);
yield return ["null price objects", (NordPoolPrice?)null, (NordPoolPrice?)null, 0]; data.Add("null price objects", null, null, 0);
return data;
} }
[Theory] [Theory]
@@ -832,15 +828,17 @@ public class NordPoolEntityServiceTests
#region Cancellation #region Cancellation
public static IEnumerable<object[]> CancelledOperations() public static TheoryData<string, Func<NordPoolEntityService, Task>> CancelledOperations()
{ {
var data = new TheoryData<string, Func<NordPoolEntityService, Task>>();
var cancelled = new CancellationToken(canceled: true); var cancelled = new CancellationToken(canceled: true);
var context = CreateDefaultContext(); var context = CreateDefaultContext();
yield return ["create entities", (Func<NordPoolEntityService, Task>)(sut => sut.CreateEntitiesAsync("EUR/kWh", cancelled))]; data.Add("create entities", sut => sut.CreateEntitiesAsync("EUR/kWh", cancelled));
yield return ["reset entities", (Func<NordPoolEntityService, Task>)(sut => sut.ResetEntitiesAsync(cancelled))]; data.Add("reset entities", sut => sut.ResetEntitiesAsync(cancelled));
yield return ["update entities", (Func<NordPoolEntityService, Task>)(sut => sut.UpdateEntitiesAsync(context, cancelled))]; data.Add("update entities", sut => sut.UpdateEntitiesAsync(context, cancelled));
yield return ["cleanup entities", (Func<NordPoolEntityService, Task>)(sut => sut.CleanupEntitiesAsync(cancelled))]; data.Add("cleanup entities", sut => sut.CleanupEntitiesAsync(cancelled));
return data;
} }
[Theory] [Theory]
+1 -1
View File
@@ -114,7 +114,7 @@ public class NordPoolInitTests
.Setup(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>())) .Setup(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException("create failed")); .ThrowsAsync(new InvalidOperationException("create failed"));
var act = () => sut.InitializeAsync(); var act = sut.InitializeAsync;
await act.Should().ThrowAsync<InvalidOperationException>().WithMessage("create failed"); await act.Should().ThrowAsync<InvalidOperationException>().WithMessage("create failed");
_entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.Never); _entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.Never);
@@ -316,7 +316,7 @@ public class NordPoolPriceServiceTests
}; };
// Act // Act
var result = _sut.AdjustedNordPoolPrice(inputPrice); var result = NordPoolPriceService.AdjustedNordPoolPrice(inputPrice);
// Assert // Assert
result.Should().NotBeNull(); result.Should().NotBeNull();
@@ -341,7 +341,7 @@ public class NordPoolPriceServiceTests
}; };
// Act // Act
var result = _sut.AdjustedNordPoolPrice(inputPrice); var result = NordPoolPriceService.AdjustedNordPoolPrice(inputPrice);
// Assert // Assert
result.Should().NotBeNull(); result.Should().NotBeNull();
@@ -356,7 +356,7 @@ public class NordPoolPriceServiceTests
var inputPrice = new NordPoolPrice { Prices = null }; var inputPrice = new NordPoolPrice { Prices = null };
// Act // Act
var result = _sut.AdjustedNordPoolPrice(inputPrice); var result = NordPoolPriceService.AdjustedNordPoolPrice(inputPrice);
// Assert // Assert
result.Should().NotBeNull(); result.Should().NotBeNull();
@@ -380,7 +380,7 @@ public class NordPoolPriceServiceTests
}; };
// Act // Act
var result = _sut.AdjustedNordPoolPrice(inputPrice); var result = NordPoolPriceService.AdjustedNordPoolPrice(inputPrice);
// Assert // Assert
result.Should().NotBeNull(); result.Should().NotBeNull();
@@ -395,7 +395,7 @@ public class NordPoolPriceServiceTests
var inputPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() }; var inputPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() };
// Act // Act
var result = _sut.AdjustedNordPoolPrice(inputPrice); var result = NordPoolPriceService.AdjustedNordPoolPrice(inputPrice);
// Assert // Assert
result.Should().NotBeNull(); result.Should().NotBeNull();
@@ -417,7 +417,7 @@ public class NordPoolPriceServiceTests
}; };
// Act // Act
var result = _sut.AdjustedNordPoolPrice(inputPrice); var result = NordPoolPriceService.AdjustedNordPoolPrice(inputPrice);
// Assert // Assert
result.Should().NotBeNull(); result.Should().NotBeNull();
@@ -437,7 +437,7 @@ public class NordPoolPriceServiceTests
}; };
// Act // Act
var result = _sut.AdjustedNordPoolPrice(inputPrice); var result = NordPoolPriceService.AdjustedNordPoolPrice(inputPrice);
// Assert // Assert
inputPrice.Prices[0].Price.Should().Be(81.0); inputPrice.Prices[0].Price.Should().Be(81.0);
@@ -627,7 +627,7 @@ public class NordPoolPriceServiceTests
// Arrange // Arrange
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals) var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
.Select(i => new NordPoolDayPrice { Price = 99.0 }) .Select(_ => new NordPoolDayPrice { Price = 99.0 })
.ToList(); .ToList();
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
@@ -671,23 +671,25 @@ public class NordPoolPriceServiceTests
/// Scenarios that do not depend on the time of day (tomorrow's prices are published after 13:00, /// Scenarios that do not depend on the time of day (tomorrow's prices are published after 13:00,
/// so the "tomorrow missing" cases are covered separately below). /// so the "tomorrow missing" cases are covered separately below).
/// </summary> /// </summary>
public static IEnumerable<object?[]> ShouldFetchScenarios() public static TheoryData<string, DateOnly?, NordPoolPrice?, NordPoolPrice?, bool> ShouldFetchScenarios()
{ {
var data = new TheoryData<string, DateOnly?, NordPoolPrice?, NordPoolPrice?, bool>();
var today = DateOnly.FromDateTime(DateTime.Now); var today = DateOnly.FromDateTime(DateTime.Now);
static NordPoolPrice Prices(params double?[] values) => new() static NordPoolPrice Prices(params double?[] values) => new()
{ {
Prices = values.Select(price => new NordPoolDayPrice { Price = price }).ToList() Prices = [.. values.Select(price => new NordPoolDayPrice { Price = price })]
}; };
yield return ["no fetch date yet", (DateOnly?)null, Prices(12.50), Prices(18.71), true]; data.Add("no fetch date yet", null, Prices(12.50), Prices(18.71), true);
yield return ["last fetch was yesterday", today.AddDays(-1), Prices(12.50), Prices(18.71), true]; data.Add("last fetch was yesterday", today.AddDays(-1), Prices(12.50), Prices(18.71), true);
yield return ["last fetch date is in the future", today.AddDays(1), Prices(12.50), Prices(18.71), false]; data.Add("last fetch date is in the future", today.AddDays(1), Prices(12.50), Prices(18.71), false);
yield return ["today prices are null", today, new NordPoolPrice { Prices = null }, Prices(18.71), true]; data.Add("today prices are null", today, new NordPoolPrice { Prices = null }, Prices(18.71), true);
yield return ["today prices are empty", today, new NordPoolPrice { Prices = [] }, Prices(18.71), true]; data.Add("today prices are empty", today, new NordPoolPrice { Prices = [] }, Prices(18.71), true);
yield return ["today and tomorrow prices present", today, Prices(12.50), Prices(18.71), false]; data.Add("today and tomorrow prices present", today, Prices(12.50), Prices(18.71), false);
yield return ["price values are null but entries exist", today, Prices((double?)null), Prices((double?)null), false]; data.Add("price values are null but entries exist", today, Prices((double?)null), Prices((double?)null), false);
yield return ["all price payloads are null", today, (NordPoolPrice?)null, (NordPoolPrice?)null, true]; data.Add("all price payloads are null", today, null, null, true);
return data;
} }
[Theory] [Theory]
@@ -780,12 +782,12 @@ public class NordPoolPriceServiceTests
_sut.LastFetchedDate.Should().Be(today); _sut.LastFetchedDate.Should().Be(today);
} }
public static IEnumerable<object?[]> UnusableTomorrowPrices => public static TheoryData<NordPoolPrice?> UnusableTomorrowPrices => new()
[ {
[null], { null },
[new NordPoolPrice { Prices = null }], { new NordPoolPrice { Prices = null } },
[new NordPoolPrice { Prices = [] }] { new NordPoolPrice { Prices = [] } }
]; };
[Theory] [Theory]
[MemberData(nameof(UnusableTomorrowPrices))] [MemberData(nameof(UnusableTomorrowPrices))]
+11 -11
View File
@@ -10,8 +10,6 @@ internal static class NordPoolTestData
{ {
public static readonly DateTime DayStart = new(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); public static readonly DateTime DayStart = new(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
public static readonly DateTime TomorrowStart = DayStart.AddDays(1);
/// <summary> /// <summary>
/// Builds a contiguous set of 15-minute intervals starting at <paramref name="dayStart"/>. /// Builds a contiguous set of 15-minute intervals starting at <paramref name="dayStart"/>.
/// </summary> /// </summary>
@@ -22,14 +20,16 @@ internal static class NordPoolTestData
{ {
var start = dayStart ?? DayStart; var start = dayStart ?? DayStart;
return Enumerable.Range(0, count) return
.Select(i => new NordPoolDayPrice [
{ .. Enumerable.Range(0, count)
Start = start.AddMinutes(i * NordPoolConsts.MinutesPerInterval), .Select(i => new NordPoolDayPrice
End = start.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), {
Price = priceFactory(i) Start = start.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
}) End = start.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
.ToList(); Price = priceFactory(i)
})
];
} }
/// <summary> /// <summary>
@@ -42,7 +42,7 @@ internal static class NordPoolTestData
return CreateIntervals( return CreateIntervals(
NordPoolConsts.MaxDailyIntervals, NordPoolConsts.MaxDailyIntervals,
i => Math.Round(15.0 * Math.Sin(i / 6.0) + (i % 8) - 2.0, 2), i => Math.Round(15.0 * Math.Sin(i / 6.0) + i % 8 - 2.0, 2),
start); start);
} }
} }
@@ -140,24 +140,24 @@ public class CostAccumulatorTests
#region Window rollovers #region Window rollovers
public static IEnumerable<object[]> WindowRolloverCases => public static TheoryData<string, CostWindow, DateTime, DateTime, double, double> WindowRolloverCases => new()
[ {
["15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0), new DateTime(2026, 3, 17, 10, 15, 0), 0.10, 0.02], { "15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0), new DateTime(2026, 3, 17, 10, 15, 0), 0.10, 0.02 },
["15 minute slot ends across the hour", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 11, 0, 0), 0.10, 0.02], { "15 minute slot ends across the hour", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 11, 0, 0), 0.10, 0.02 },
["15 minute slot ends at midnight", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 23, 45, 0), new DateTime(2026, 3, 18, 0, 0, 0), 0.10, 0.02], { "15 minute slot ends at midnight", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 23, 45, 0), new DateTime(2026, 3, 18, 0, 0, 0), 0.10, 0.02 },
["15 minute slot ends on DST spring forward", CostWindow.FifteenMinutes, new DateTime(2026, 3, 29, 2, 45, 0), new DateTime(2026, 3, 29, 3, 0, 0), 0.10, 0.02], { "15 minute slot ends on DST spring forward", CostWindow.FifteenMinutes, new DateTime(2026, 3, 29, 2, 45, 0), new DateTime(2026, 3, 29, 3, 0, 0), 0.10, 0.02 },
["15 minute slot ends on DST fall back", CostWindow.FifteenMinutes, new DateTime(2026, 10, 25, 2, 45, 0), new DateTime(2026, 10, 25, 3, 0, 0), 0.10, 0.02], { "15 minute slot ends on DST fall back", CostWindow.FifteenMinutes, new DateTime(2026, 10, 25, 2, 45, 0), new DateTime(2026, 10, 25, 3, 0, 0), 0.10, 0.02 },
["hour ends", CostWindow.Hour, new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 0, 0), 0.50, 0.01], { "hour ends", CostWindow.Hour, new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 0, 0), 0.50, 0.01 },
["hour ends at midnight", CostWindow.Hour, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), 0.50, 0.01], { "hour ends at midnight", CostWindow.Hour, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), 0.50, 0.01 },
["hour ends on DST spring forward", CostWindow.Hour, new DateTime(2026, 3, 29, 2, 59, 0), new DateTime(2026, 3, 29, 3, 0, 0), 0.50, 0.01], { "hour ends on DST spring forward", CostWindow.Hour, new DateTime(2026, 3, 29, 2, 59, 0), new DateTime(2026, 3, 29, 3, 0, 0), 0.50, 0.01 },
["hour ends on DST fall back", CostWindow.Hour, new DateTime(2026, 10, 25, 2, 59, 0), new DateTime(2026, 10, 25, 3, 0, 0), 0.50, 0.01], { "hour ends on DST fall back", CostWindow.Hour, new DateTime(2026, 10, 25, 2, 59, 0), new DateTime(2026, 10, 25, 3, 0, 0), 0.50, 0.01 },
["day changes", CostWindow.Day, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), 5.00, 0.01], { "day changes", CostWindow.Day, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), 5.00, 0.01 },
["day changes at month end", CostWindow.Day, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), 5.00, 0.01], { "day changes at month end", CostWindow.Day, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), 5.00, 0.01 },
["day changes at year end", CostWindow.Day, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), 5.00, 0.01], { "day changes at year end", CostWindow.Day, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), 5.00, 0.01 },
["month changes", CostWindow.Month, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), 100.00, 0.01], { "month changes", CostWindow.Month, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), 100.00, 0.01 },
["year changes", CostWindow.Month, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), 100.00, 0.01], { "year changes", CostWindow.Month, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), 100.00, 0.01 },
["month changes on leap day", CostWindow.Month, new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), 100.00, 0.01] { "month changes on leap day", CostWindow.Month, new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), 100.00, 0.01 }
]; };
[Theory] [Theory]
[MemberData(nameof(WindowRolloverCases))] [MemberData(nameof(WindowRolloverCases))]
@@ -227,19 +227,19 @@ public class CostAccumulatorTests
#region Window boundary detection (static methods) #region Window boundary detection (static methods)
public static IEnumerable<object[]> FifteenMinuteBoundaryCases => public static TheoryData<string, DateTime, DateTime, bool> FifteenMinuteBoundaryCases => new()
[ {
["same slot, first second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false], { "same slot, first second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false },
["same slot, last second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 14, 59), false], { "same slot, last second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 14, 59), false },
["slot boundary 14 -> 15", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 15, 0), true], { "slot boundary 14 -> 15", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 15, 0), true },
["slot boundary 29 -> 30", new DateTime(2026, 3, 17, 10, 29, 0), new DateTime(2026, 3, 17, 10, 30, 0), true], { "slot boundary 29 -> 30", new DateTime(2026, 3, 17, 10, 29, 0), new DateTime(2026, 3, 17, 10, 30, 0), true },
["slot boundary 44 -> 45", new DateTime(2026, 3, 17, 10, 44, 0), new DateTime(2026, 3, 17, 10, 45, 0), true], { "slot boundary 44 -> 45", new DateTime(2026, 3, 17, 10, 44, 0), new DateTime(2026, 3, 17, 10, 45, 0), true },
["same slot, late", new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 10, 59, 59), false], { "same slot, late", new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 10, 59, 59), false },
["hour boundary", new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 11, 0, 0), true], { "hour boundary", new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 11, 0, 0), true },
["midnight boundary", new DateTime(2026, 3, 17, 23, 45, 0), new DateTime(2026, 3, 18, 0, 0, 0), true], { "midnight boundary", new DateTime(2026, 3, 17, 23, 45, 0), new DateTime(2026, 3, 18, 0, 0, 0), true },
["clock moved backwards", new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 10, 44, 0), true], { "clock moved backwards", new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 10, 44, 0), true },
["DST spring forward", new DateTime(2026, 3, 29, 2, 45, 0), new DateTime(2026, 3, 29, 3, 0, 0), true] { "DST spring forward", new DateTime(2026, 3, 29, 2, 45, 0), new DateTime(2026, 3, 29, 3, 0, 0), true }
]; };
[Theory] [Theory]
[MemberData(nameof(FifteenMinuteBoundaryCases))] [MemberData(nameof(FifteenMinuteBoundaryCases))]
@@ -248,18 +248,18 @@ public class CostAccumulatorTests
CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
} }
public static IEnumerable<object[]> HourBoundaryCases => public static TheoryData<string, DateTime, DateTime, bool> HourBoundaryCases => new()
[ {
["same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false], { "same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false },
["same hour, later minute", new DateTime(2026, 3, 17, 10, 10, 0), new DateTime(2026, 3, 17, 10, 11, 0), false], { "same hour, later minute", new DateTime(2026, 3, 17, 10, 10, 0), new DateTime(2026, 3, 17, 10, 11, 0), false },
["same hour, last minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 59, 59), false], { "same hour, last minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 59, 59), false },
["next hour", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 11, 0, 0), true], { "next hour", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 11, 0, 0), true },
["next hour, late minute", new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 59, 0), true], { "next hour, late minute", new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 59, 0), true },
["midnight boundary", new DateTime(2026, 3, 17, 23, 0, 0), new DateTime(2026, 3, 18, 0, 0, 0), true], { "midnight boundary", new DateTime(2026, 3, 17, 23, 0, 0), new DateTime(2026, 3, 18, 0, 0, 0), true },
["clock moved backwards", new DateTime(2026, 3, 17, 11, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), true], { "clock moved backwards", new DateTime(2026, 3, 17, 11, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), true },
["DST spring forward", new DateTime(2026, 3, 29, 2, 0, 0), new DateTime(2026, 3, 29, 3, 0, 0), true], { "DST spring forward", new DateTime(2026, 3, 29, 2, 0, 0), new DateTime(2026, 3, 29, 3, 0, 0), true },
["DST fall back", new DateTime(2026, 10, 25, 2, 0, 0), new DateTime(2026, 10, 25, 3, 0, 0), true] { "DST fall back", new DateTime(2026, 10, 25, 2, 0, 0), new DateTime(2026, 10, 25, 3, 0, 0), true }
]; };
[Theory] [Theory]
[MemberData(nameof(HourBoundaryCases))] [MemberData(nameof(HourBoundaryCases))]
@@ -268,17 +268,17 @@ public class CostAccumulatorTests
CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
} }
public static IEnumerable<object[]> DayBoundaryCases => public static TheoryData<string, DateTime, DateTime, bool> DayBoundaryCases => new()
[ {
["same timestamp", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 0, 0, 0), false], { "same timestamp", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 0, 0, 0), false },
["same day, last second", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 23, 59, 59), false], { "same day, last second", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 23, 59, 59), false },
["next day", new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), true], { "next day", new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), true },
["month rollover", new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), true], { "month rollover", new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), true },
["year rollover", new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), true], { "year rollover", new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), true },
["leap day rollover", new DateTime(2028, 2, 28, 23, 59, 0), new DateTime(2028, 2, 29, 0, 0, 0), true], { "leap day rollover", new DateTime(2028, 2, 28, 23, 59, 0), new DateTime(2028, 2, 29, 0, 0, 0), true },
["DST spring forward day", new DateTime(2026, 3, 28, 23, 59, 0), new DateTime(2026, 3, 29, 0, 0, 0), true], { "DST spring forward day", new DateTime(2026, 3, 28, 23, 59, 0), new DateTime(2026, 3, 29, 0, 0, 0), true },
["DST fall back day", new DateTime(2026, 10, 24, 23, 59, 0), new DateTime(2026, 10, 25, 0, 0, 0), true] { "DST fall back day", new DateTime(2026, 10, 24, 23, 59, 0), new DateTime(2026, 10, 25, 0, 0, 0), true }
]; };
[Theory] [Theory]
[MemberData(nameof(DayBoundaryCases))] [MemberData(nameof(DayBoundaryCases))]
@@ -287,15 +287,15 @@ public class CostAccumulatorTests
CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
} }
public static IEnumerable<object[]> MonthBoundaryCases => public static TheoryData<string, DateTime, DateTime, bool> MonthBoundaryCases => new()
[ {
["same month, first day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 1, 0, 0, 0), false], { "same month, first day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 1, 0, 0, 0), false },
["same month, last day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 59), false], { "same month, last day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 59), false },
["next month", new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), true], { "next month", new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), true },
["clock moved into previous month", new DateTime(2026, 4, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 0), true], { "clock moved into previous month", new DateTime(2026, 4, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 0), true },
["year rollover", new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), true], { "year rollover", new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), true },
["leap day rollover", new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), true] { "leap day rollover", new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), true }
]; };
[Theory] [Theory]
[MemberData(nameof(MonthBoundaryCases))] [MemberData(nameof(MonthBoundaryCases))]
@@ -333,7 +333,7 @@ public class CostAccumulatorTests
// Assert // Assert
var snapshot = sut.GetSnapshot(); var snapshot = sut.GetSnapshot();
var expected = incrementPerCall * callsPerThread * threadCount; const double expected = incrementPerCall * callsPerThread * threadCount;
snapshot.CostMonthly.Should().BeApproximately(expected, 0.0001); snapshot.CostMonthly.Should().BeApproximately(expected, 0.0001);
} }
@@ -18,18 +18,18 @@ public class OtherPowerCalculationServiceTests
#region Basic calculation #region Basic calculation
public static IEnumerable<object[]> CalculationCases => public static TheoryData<string, double, double[], double, string> CalculationCases => new()
[ {
["two devices", 341.97, new[] { 8.55, 36.93 }, 296.49, "ok"], { "two devices", 341.97, [8.55, 36.93], 296.49, "ok" },
["no devices", 341.97, System.Array.Empty<double>(), 341.97, "ok"], { "no devices", 341.97, Array.Empty<double>(), 341.97, "ok" },
["devices exceed total", 341.97, new[] { 200.0, 180.0 }, 0.0, "device_sum_exceeds_total"], { "devices exceed total", 341.97, [200.0, 180.0], 0.0, "device_sum_exceeds_total" },
["devices equal total", 100.0, new[] { 60.0, 40.0 }, 0.0, "ok"], { "devices equal total", 100.0, [60.0, 40.0], 0.0, "ok" },
["zero power, no devices", 0.0, System.Array.Empty<double>(), 0.0, "ok"], { "zero power, no devices", 0.0, Array.Empty<double>(), 0.0, "ok" },
["negative total, no devices", -120.0, System.Array.Empty<double>(), 0.0, "device_sum_exceeds_total"], { "negative total, no devices", -120.0, Array.Empty<double>(), 0.0, "device_sum_exceeds_total" },
["negative device reading", 100.0, new[] { 150.0, -40.0 }, 0.0, "device_sum_exceeds_total"], { "negative device reading", 100.0, [150.0, -40.0], 0.0, "device_sum_exceeds_total" },
["very large values", 1_000_000.0, new[] { 250_000.0, 250_000.0 }, 500_000.0, "ok"], { "very large values", 1_000_000.0, [250_000.0, 250_000.0], 500_000.0, "ok" },
["very small values", 0.5, new[] { 0.25 }, 0.25, "ok"] { "very small values", 0.5, [0.25], 0.25, "ok" }
]; };
[Theory] [Theory]
[MemberData(nameof(CalculationCases))] [MemberData(nameof(CalculationCases))]
@@ -43,8 +43,8 @@ public class OtherPowerCalculationServiceTests
// Arrange // Arrange
var sut = CreateSut(smoothingWindowSize: 1); var sut = CreateSut(smoothingWindowSize: 1);
var devices = deviceWatts var devices = deviceWatts
.Select((watts, index) => ($"sensor.device{index}_power", watts)) .Select((watts, index) => (entityId: $"sensor.device{index}_power", watts: watts))
.ToDictionary(entry => entry.Item1, entry => entry.Item2); .ToDictionary(entry => entry.entityId, entry => entry.watts);
// Act // Act
var result = sut.Calculate(totalPowerWatts, devices); var result = sut.Calculate(totalPowerWatts, devices);
@@ -112,11 +112,10 @@ public class OtherPowerCalculationServiceTests
{ {
// Arrange // Arrange
var sut = CreateSut(smoothingWindowSize: 4); var sut = CreateSut(smoothingWindowSize: 4);
var devices = new Dictionary<string, double>();
// Act // Act
var result1 = sut.Calculate(341.97, devices); var result1 = sut.Calculate(341.97, new Dictionary<string, double>());
var result2 = sut.Calculate(115.0, devices); var result2 = sut.Calculate(115.0, new Dictionary<string, double>());
// Assert // Assert
result1.SmoothedOtherPowerWatts.Should().BeApproximately(341.97, 0.1); result1.SmoothedOtherPowerWatts.Should().BeApproximately(341.97, 0.1);
@@ -164,13 +163,12 @@ public class OtherPowerCalculationServiceTests
{ {
// Arrange // Arrange
var sut = CreateSut(smoothingWindowSize); var sut = CreateSut(smoothingWindowSize);
var devices = new Dictionary<string, double>();
// Act // Act
PowerCalculationResult? result = null; PowerCalculationResult? result = null;
for (var i = 0; i < 200; i++) for (var i = 0; i < 200; i++)
{ {
result = sut.Calculate(200.0, devices); result = sut.Calculate(200.0, new Dictionary<string, double>());
} }
// Assert // Assert
@@ -183,10 +181,9 @@ public class OtherPowerCalculationServiceTests
// Arrange // Arrange
var sut = CreateSut(smoothingWindowSize: 5); var sut = CreateSut(smoothingWindowSize: 5);
var samples = PowerMonitorTestData.CreatePowerSampleSeries(50); var samples = PowerMonitorTestData.CreatePowerSampleSeries(50);
var devices = new Dictionary<string, double>();
// Act // Act
var results = samples.Select(sample => sut.Calculate(sample, devices)).ToList(); var results = samples.Select(sample => sut.Calculate(sample, new Dictionary<string, double>())).ToList();
// Assert // Assert
results.Should().OnlyContain(r => r.SmoothedOtherPowerWatts >= samples.Min()); results.Should().OnlyContain(r => r.SmoothedOtherPowerWatts >= samples.Min());
@@ -202,13 +199,12 @@ public class OtherPowerCalculationServiceTests
{ {
// Arrange // Arrange
var sut = CreateSut(smoothingWindowSize: 10); var sut = CreateSut(smoothingWindowSize: 10);
var devices = new Dictionary<string, double>(); sut.Calculate(341.97, new Dictionary<string, double>());
sut.Calculate(341.97, devices); sut.Calculate(341.97, new Dictionary<string, double>());
sut.Calculate(341.97, devices);
// Act // Act
sut.Reset(); sut.Reset();
var result = sut.Calculate(115.0, devices); var result = sut.Calculate(115.0, new Dictionary<string, double>());
// Assert // Assert
result.SmoothedOtherPowerWatts.Should().BeApproximately(115.0, 0.1); result.SmoothedOtherPowerWatts.Should().BeApproximately(115.0, 0.1);
@@ -1,6 +1,5 @@
using FluentAssertions; using FluentAssertions;
using PowerMonitorManager; using PowerMonitorManager;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts; using PowerMonitorManager.Models.Consts;
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
@@ -17,18 +16,18 @@ public class PowerCostCalculationServiceTests
#region CalculateCostIncrement #region CalculateCostIncrement
public static IEnumerable<object[]> CostIncrementCases => public static TheoryData<string, double, double, int, double> CostIncrementCases => new()
[ {
["default polling interval", 341.97, 0.1791, 15, 0.0002551951125], { "default polling interval", 341.97, 0.1791, 15, 0.0002551951125 },
["one kilowatt for one hour", 1000.0, 1.0, PowerMonitorConsts.SecondsPerHour, 1.0], { "one kilowatt for one hour", 1000.0, 1.0, PowerMonitorConsts.SecondsPerHour, 1.0 },
["limit load for one minute", 5500.0, 0.25, 60, 0.0229166666666667], { "limit load for one minute", 5500.0, 0.25, 60, 0.0229166666666667 },
["very large load", 1_000_000.0, 0.5, 900, 125.0], { "very large load", 1_000_000.0, 0.5, 900, 125.0 },
["negative power", -500.0, 0.2, PowerMonitorConsts.SecondsPerHour, -0.1], { "negative power", -500.0, 0.2, PowerMonitorConsts.SecondsPerHour, -0.1 },
["zero power", 0.0, 0.1791, 15, 0.0], { "zero power", 0.0, 0.1791, 15, 0.0 },
["zero price", 341.97, 0.0, 15, 0.0], { "zero price", 341.97, 0.0, 15, 0.0 },
["zero interval", 1000.0, 0.2, 0, 0.0], { "zero interval", 1000.0, 0.2, 0, 0.0 },
["tiny values", 0.001, 0.0001, 1, 2.77777777777778e-14] { "tiny values", 0.001, 0.0001, 1, 2.77777777777778e-14 }
]; };
[Theory] [Theory]
[MemberData(nameof(CostIncrementCases))] [MemberData(nameof(CostIncrementCases))]
@@ -315,7 +314,7 @@ public class PowerCostCalculationServiceTests
var timestamps = PowerMonitorTestData.CreateSampleTimestamps(PowerMonitorTestData.FixedDayStart, 96); var timestamps = PowerMonitorTestData.CreateSampleTimestamps(PowerMonitorTestData.FixedDayStart, 96);
var wattSamples = PowerMonitorTestData.CreatePowerSampleSeries(96); var wattSamples = PowerMonitorTestData.CreatePowerSampleSeries(96);
var expectedPerSlot = timestamps var expectedPerSlot = timestamps
.Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds)) .Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh))
.ToArray(); .ToArray();
// Act // Act
@@ -347,7 +346,7 @@ public class PowerCostCalculationServiceTests
// Act // Act
foreach (var (start, pricePerKwh) in windows) foreach (var (start, pricePerKwh) in windows)
{ {
var watts = 500.0 + (start.Hour * 125.0); var watts = 500.0 + start.Hour * 125.0;
var result = PowerMonitorTestData.CreateCalculation( var result = PowerMonitorTestData.CreateCalculation(
totalWatts: watts, totalWatts: watts,
smoothedOtherWatts: watts / 4, smoothedOtherWatts: watts / 4,
@@ -16,18 +16,10 @@ public class PowerLimitEnforcementServiceTests
private const string BoilerSwitch = PowerMonitorTestData.BoilerSwitchEntityId; private const string BoilerSwitch = PowerMonitorTestData.BoilerSwitchEntityId;
private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId; private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId;
private readonly Mock<IHaContext> _haContextMock; private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock; private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new();
private readonly FakeTimeProvider _timeProvider; private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow);
private readonly PowerMonitorOptions _options; private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions();
public PowerLimitEnforcementServiceTests()
{
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<PowerLimitEnforcementService>>();
_timeProvider = new FakeTimeProvider(PowerMonitorTestData.FixedUtcNow);
_options = PowerMonitorTestData.CreateLimitEnforcementOptions();
}
private PowerLimitEnforcementService CreateSut() => private PowerLimitEnforcementService CreateSut() =>
new( new(
@@ -187,18 +179,18 @@ public class PowerLimitEnforcementServiceTests
#region Recovery #region Recovery
public static IEnumerable<object[]> RecoveryCases => public static TheoryData<string, int, double, bool, int> RecoveryCases => new()
[ {
["not yet due", 300, 3000.0, true, 0], { "not yet due", 300, 3000.0, true, 0 },
["one second before due", 599, 3000.0, true, 0], { "one second before due", 599, 3000.0, true, 0 },
["exactly due", 600, 3000.0, false, 1], { "exactly due", 600, 3000.0, false, 1 },
["just under limit", 601, 5499.99, false, 1], { "just under limit", 601, 5499.99, false, 1 },
["zero power", 900, 0.0, false, 1], { "zero power", 900, 0.0, false, 1 },
["negative power", 601, -10.0, false, 1], { "negative power", 601, -10.0, false, 1 },
["exactly at limit stays enforced", 601, 5500.0, true, 0], { "exactly at limit stays enforced", 601, 5500.0, true, 0 },
["above limit stays enforced", 601, 5800.0, true, 0], { "above limit stays enforced", 601, 5800.0, true, 0 },
["very high power stays enforced", 601, 25_000.0, true, 0] { "very high power stays enforced", 601, 25_000.0, true, 0 }
]; };
[Theory] [Theory]
[MemberData(nameof(RecoveryCases))] [MemberData(nameof(RecoveryCases))]
@@ -237,8 +229,7 @@ public class PowerLimitEnforcementServiceTests
sut.EnforceLimit(5800); sut.EnforceLimit(5800);
sut.IsLimitActive.Should().BeTrue(); sut.IsLimitActive.Should().BeTrue();
var immediatelyAfter = sut; sut.EnforceLimit(3000);
immediatelyAfter.EnforceLimit(3000);
// Assert - not enough time has passed for another check // Assert - not enough time has passed for another check
sut.IsLimitActive.Should().BeTrue(); sut.IsLimitActive.Should().BeTrue();
@@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging;
using Moq; using Moq;
using PowerMonitor.Models; using PowerMonitor.Models;
using PowerMonitorManager; using PowerMonitorManager;
using PowerMonitorManager.Models;
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
@@ -28,19 +27,17 @@ public class PowerMonitorEntityServiceTests
"button.powermonitor_trigger_limit_breach" "button.powermonitor_trigger_limit_breach"
]; ];
private readonly Mock<IEntityManager> _entityManagerMock; private readonly Mock<IEntityManager> _entityManagerMock = new();
private readonly Mock<ILogger<PowerMonitorEntityService>> _loggerMock;
private readonly PowerMonitorEntityService _sut; private readonly PowerMonitorEntityService _sut;
public PowerMonitorEntityServiceTests() public PowerMonitorEntityServiceTests()
{ {
_entityManagerMock = new Mock<IEntityManager>(); var loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
_loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>())).Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>())).Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())).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.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())).Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>())).Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>())).Returns(Task.CompletedTask);
_sut = new PowerMonitorEntityService(_entityManagerMock.Object, _loggerMock.Object); _sut = new PowerMonitorEntityService(_entityManagerMock.Object, loggerMock.Object);
} }
#region GetSystemEntitiesList #region GetSystemEntitiesList
@@ -49,7 +46,7 @@ public class PowerMonitorEntityServiceTests
public void GetSystemEntitiesList_ShouldReturnAll14SystemEntities() public void GetSystemEntitiesList_ShouldReturnAll14SystemEntities()
{ {
// Act // Act
var result = _sut.GetSystemEntitiesList(); var result = PowerMonitorEntityService.GetSystemEntitiesList();
// Assert // Assert
result.Should().HaveCount(14); result.Should().HaveCount(14);
@@ -73,7 +70,7 @@ public class PowerMonitorEntityServiceTests
public void GetSystemEntitiesList_ShouldContainExpectedEntityId(string entityId) public void GetSystemEntitiesList_ShouldContainExpectedEntityId(string entityId)
{ {
// Act // Act
var result = _sut.GetSystemEntitiesList(); var result = PowerMonitorEntityService.GetSystemEntitiesList();
// Assert // Assert
result.Should().Contain(entity => entity.EntityId == entityId); result.Should().Contain(entity => entity.EntityId == entityId);
@@ -83,7 +80,7 @@ public class PowerMonitorEntityServiceTests
public void GetSystemEntitiesList_AllEntities_ShouldHaveUniqueEntityIds() public void GetSystemEntitiesList_AllEntities_ShouldHaveUniqueEntityIds()
{ {
// Act // Act
var result = _sut.GetSystemEntitiesList(); var result = PowerMonitorEntityService.GetSystemEntitiesList();
// Assert // Assert
result.Select(entity => entity.EntityId).Should().OnlyHaveUniqueItems(); result.Select(entity => entity.EntityId).Should().OnlyHaveUniqueItems();
@@ -93,7 +90,7 @@ public class PowerMonitorEntityServiceTests
public void GetSystemEntitiesList_AllEntities_ShouldExposeCreationOptions() public void GetSystemEntitiesList_AllEntities_ShouldExposeCreationOptions()
{ {
// Act // Act
var result = _sut.GetSystemEntitiesList(); var result = PowerMonitorEntityService.GetSystemEntitiesList();
// Assert // Assert
result.Should().OnlyContain(entity => entity.Options != null && entity.Options.UniqueId == entity.EntityId); result.Should().OnlyContain(entity => entity.Options != null && entity.Options.UniqueId == entity.EntityId);
@@ -103,13 +100,13 @@ public class PowerMonitorEntityServiceTests
#region GetPowerDeviceEntitiesNames #region GetPowerDeviceEntitiesNames
public static IEnumerable<object[]> DeviceEntityCases => public static TheoryData<string, string, string, string> DeviceEntityCases => new()
[ {
["sonoff device", "sensor.sonoff_1002230e32_power", "Sonoff Power", "sonoff_1002230e32"], { "sonoff device", "sensor.sonoff_1002230e32_power", "Sonoff Power", "sonoff_1002230e32" },
["simple device", "sensor.tv_power", "TV Power", "tv"], { "simple device", "sensor.tv_power", "TV Power", "tv" },
["device with suffix in name", "sensor.akvariumas_power", "Akvariumas Power", "akvariumas"], { "device with suffix in name", "sensor.akvariumas_power", "Akvariumas Power", "akvariumas" },
["uppercase entity id", "sensor.TV_POWER", "TV Power", "TV"] { "uppercase entity id", "sensor.TV_POWER", "TV Power", "TV" }
]; };
[Theory] [Theory]
[MemberData(nameof(DeviceEntityCases))] [MemberData(nameof(DeviceEntityCases))]
@@ -127,21 +124,23 @@ public class PowerMonitorEntityServiceTests
// Assert // Assert
result.Should().HaveCount(4, $"scenario: {scenario}"); result.Should().HaveCount(4, $"scenario: {scenario}");
result.Select(entity => entity.EntityId).Should().BeEquivalentTo(new[] string[] expectedEntityIds =
{ [
$"sensor.powermonitor_{expectedDeviceName}_cost_15min", $"sensor.powermonitor_{expectedDeviceName}_cost_15min",
$"sensor.powermonitor_{expectedDeviceName}_cost_1h", $"sensor.powermonitor_{expectedDeviceName}_cost_1h",
$"sensor.powermonitor_{expectedDeviceName}_cost_daily", $"sensor.powermonitor_{expectedDeviceName}_cost_daily",
$"sensor.powermonitor_{expectedDeviceName}_cost_monthly" $"sensor.powermonitor_{expectedDeviceName}_cost_monthly"
}, $"scenario: {scenario}"); ];
result.Select(entity => entity.EntityId).Should().BeEquivalentTo(expectedEntityIds, $"scenario: {scenario}");
result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}"); result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}");
result.Select(entity => entity.Name).Should().BeEquivalentTo(new[] string[] expectedNames =
{ [
$"{friendlyName} cost (15 min)", $"{friendlyName} cost (15 min)",
$"{friendlyName} cost (1h)", $"{friendlyName} cost (1h)",
$"{friendlyName} cost (daily)", $"{friendlyName} cost (daily)",
$"{friendlyName} cost (monthly)" $"{friendlyName} cost (monthly)"
}, $"scenario: {scenario}"); ];
result.Select(entity => entity.Name).Should().BeEquivalentTo(expectedNames, $"scenario: {scenario}");
} }
[Fact] [Fact]
@@ -173,13 +172,14 @@ public class PowerMonitorEntityServiceTests
// Assert // Assert
result.Should().HaveCount(4); result.Should().HaveCount(4);
result.Should().BeEquivalentTo(new[] string[] expectedEntityIds =
{ [
$"sensor.powermonitor_{deviceName}_cost_15min", $"sensor.powermonitor_{deviceName}_cost_15min",
$"sensor.powermonitor_{deviceName}_cost_1h", $"sensor.powermonitor_{deviceName}_cost_1h",
$"sensor.powermonitor_{deviceName}_cost_daily", $"sensor.powermonitor_{deviceName}_cost_daily",
$"sensor.powermonitor_{deviceName}_cost_monthly" $"sensor.powermonitor_{deviceName}_cost_monthly"
}); ];
result.Should().BeEquivalentTo(expectedEntityIds);
} }
#endregion #endregion
@@ -510,18 +510,21 @@ public class PowerMonitorEntityServiceTests
#region Cancellation #region Cancellation
public static IEnumerable<object[]> CancelledOperations() public static TheoryData<string, Func<PowerMonitorEntityService, Task>> CancelledOperations()
{ {
var data = new TheoryData<string, Func<PowerMonitorEntityService, Task>>();
var cancelled = new CancellationToken(canceled: true); var cancelled = new CancellationToken(canceled: true);
var sensors = new List<PowerSensorInfo> { PowerMonitorTestData.CreateSensor("sensor.tv_power") }; List<PowerSensorInfo> sensors = [PowerMonitorTestData.CreateSensor("sensor.tv_power")];
var context = PowerMonitorTestData.CreateUpdateContext(); var context = PowerMonitorTestData.CreateUpdateContext();
yield return ["create system entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.CreateSystemEntitiesAsync(cancelled))]; data.Add("create system entities", sut => sut.CreateSystemEntitiesAsync(cancelled));
yield return ["create device entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.CreateDeviceEntitiesAsync(sensors, cancelled))]; data.Add("create device entities", sut => sut.CreateDeviceEntitiesAsync(sensors, cancelled));
yield return ["update entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.UpdateEntitiesAsync(context, cancelled))]; data.Add("update entities", sut => sut.UpdateEntitiesAsync(context, cancelled));
yield return ["reset entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.ResetEntitiesAsync(cancelled))]; data.Add("reset entities", sut => sut.ResetEntitiesAsync(cancelled));
yield return ["remove system entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.RemoveSystemEntitiesAsync(cancelled))]; data.Add("remove system entities", sut => sut.RemoveSystemEntitiesAsync(cancelled));
yield return ["remove device entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.RemoveDeviceEntitiesAsync(["tv"], cancelled))]; data.Add("remove device entities", sut => sut.RemoveDeviceEntitiesAsync(["tv"], cancelled));
return data;
} }
[Theory] [Theory]
@@ -6,26 +6,17 @@ namespace PowerMonitor.Manager.Tests;
public class PowerMonitorOptionsTests public class PowerMonitorOptionsTests
{ {
/// <summary>
/// Expected defaults for every public, configurable option. Only public properties are
/// inspected here - no private state is read through reflection.
/// </summary>
public static TheoryData<string, object> ExpectedDefaults => new()
{
{ nameof(PowerMonitorOptions.Enabled), false },
{ nameof(PowerMonitorOptions.MainMeterEntityId), string.Empty },
{ nameof(PowerMonitorOptions.PollIntervalSeconds), PowerMonitorConsts.DefaultPollIntervalSeconds },
{ nameof(PowerMonitorOptions.SmoothingWindowSize), PowerMonitorConsts.DefaultSmoothingWindowSize },
{ nameof(PowerMonitorOptions.AnomalyThresholdWatts), PowerMonitorConsts.DefaultAnomalyThresholdWatts },
{ nameof(PowerMonitorOptions.HighPowerThresholdWatts), PowerMonitorConsts.DefaultHighPowerThresholdWatts },
{ nameof(PowerMonitorOptions.EnforceLimitEnabled), true },
{ nameof(PowerMonitorOptions.PowerLimitWatts), PowerMonitorConsts.DefaultPowerLimitWatts },
{ nameof(PowerMonitorOptions.RecoverySeconds), PowerMonitorConsts.DefaultRecoverySeconds },
{ nameof(PowerMonitorOptions.LimitCooldownSeconds), PowerMonitorConsts.DefaultLimitCooldownSeconds }
};
[Theory] [Theory]
[MemberData(nameof(ExpectedDefaults))] [InlineData(nameof(PowerMonitorOptions.Enabled), false)]
[InlineData(nameof(PowerMonitorOptions.MainMeterEntityId), "")]
[InlineData(nameof(PowerMonitorOptions.PollIntervalSeconds), PowerMonitorConsts.DefaultPollIntervalSeconds)]
[InlineData(nameof(PowerMonitorOptions.SmoothingWindowSize), PowerMonitorConsts.DefaultSmoothingWindowSize)]
[InlineData(nameof(PowerMonitorOptions.AnomalyThresholdWatts), PowerMonitorConsts.DefaultAnomalyThresholdWatts)]
[InlineData(nameof(PowerMonitorOptions.HighPowerThresholdWatts), PowerMonitorConsts.DefaultHighPowerThresholdWatts)]
[InlineData(nameof(PowerMonitorOptions.EnforceLimitEnabled), true)]
[InlineData(nameof(PowerMonitorOptions.PowerLimitWatts), PowerMonitorConsts.DefaultPowerLimitWatts)]
[InlineData(nameof(PowerMonitorOptions.RecoverySeconds), PowerMonitorConsts.DefaultRecoverySeconds)]
[InlineData(nameof(PowerMonitorOptions.LimitCooldownSeconds), PowerMonitorConsts.DefaultLimitCooldownSeconds)]
public void Defaults_ShouldExposeExpectedValue(string propertyName, object expected) public void Defaults_ShouldExposeExpectedValue(string propertyName, object expected)
{ {
// Arrange // Arrange
@@ -40,12 +31,12 @@ public class PowerMonitorOptionsTests
actual.Should().Be(expected); actual.Should().Be(expected);
} }
public static TheoryData<string> CollectionProperties => new() public static TheoryData<string> CollectionProperties =>
{ [
nameof(PowerMonitorOptions.ExcludedSensorPatterns), nameof(PowerMonitorOptions.ExcludedSensorPatterns),
nameof(PowerMonitorOptions.EnforceSwitchOffEntityIds), nameof(PowerMonitorOptions.EnforceSwitchOffEntityIds),
nameof(PowerMonitorOptions.PauseAndRestoreEntityIds) nameof(PowerMonitorOptions.PauseAndRestoreEntityIds)
}; ];
[Theory] [Theory]
[MemberData(nameof(CollectionProperties))] [MemberData(nameof(CollectionProperties))]
@@ -59,7 +50,7 @@ public class PowerMonitorOptionsTests
// Assert // Assert
value.Should().BeOfType<string[]>(); value.Should().BeOfType<string[]>();
((string[])value!).Should().BeEmpty(); ((string[])value).Should().BeEmpty();
} }
[Fact] [Fact]
@@ -39,7 +39,7 @@ internal static class PowerMonitorTestData
/// <summary> /// <summary>
/// Realistic seven-device reading set used by the entity projection tests. /// Realistic seven-device reading set used by the entity projection tests.
/// </summary> /// </summary>
public static IReadOnlyDictionary<string, double> CreateDeviceReadings() => new Dictionary<string, double> private static Dictionary<string, double> CreateDeviceReadings() => new()
{ {
["sensor.sonoff_100215c534_power"] = 8.55, ["sensor.sonoff_100215c534_power"] = 8.55,
["sensor.sonoff_10018909cb_power"] = 36.93, ["sensor.sonoff_10018909cb_power"] = 36.93,
@@ -72,7 +72,7 @@ internal static class PowerMonitorTestData
}; };
} }
public static CostSnapshot CreateCostSnapshot( private static CostSnapshot CreateCostSnapshot(
double cost15Min = 0.001, double cost15Min = 0.001,
double cost1Hour = 0.004, double cost1Hour = 0.004,
double costDaily = 0.03, double costDaily = 0.03,
@@ -189,29 +189,34 @@ internal static class PowerMonitorTestData
/// used by the looping scenarios. /// used by the looping scenarios.
/// </summary> /// </summary>
public static IReadOnlyList<double> CreatePowerSampleSeries(int count = 96) => public static IReadOnlyList<double> CreatePowerSampleSeries(int count = 96) =>
Enumerable.Range(0, count) [
.Select(i => Math.Round(50.0 + (i * 37.5) + ((i % 7) * 0.5), 2)) .. Enumerable.Range(0, count)
.ToArray(); .Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2))
];
/// <summary> /// <summary>
/// Deterministic, strictly positive hourly tariff series (EUR/kWh). /// Deterministic, strictly positive hourly tariff series (EUR/kWh).
/// </summary> /// </summary>
public static IReadOnlyList<double> CreateTariffPriceSeries(int count = 24) => private static IReadOnlyList<double> CreateTariffPriceSeries(int count = 24) =>
Enumerable.Range(0, count) [
.Select(i => Math.Round(0.08 + (i * 0.03) + ((i % 5) * 0.0125), 4)) .. Enumerable.Range(0, count)
.ToArray(); .Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4))
];
public static IReadOnlyList<(DateTime Start, double PricePerKwh)> CreateHourlyTariffWindows(DateTime dayStart) public static IReadOnlyList<(DateTime Start, double PricePerKwh)> CreateHourlyTariffWindows(DateTime dayStart)
{ {
var prices = CreateTariffPriceSeries(); var prices = CreateTariffPriceSeries();
return Enumerable.Range(0, prices.Count) return
.Select(hour => (dayStart.AddHours(hour), prices[hour])) [
.ToArray(); .. Enumerable.Range(0, prices.Count)
.Select(hour => (dayStart.AddHours(hour), prices[hour]))
];
} }
public static IReadOnlyList<DateTime> CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15) => public static IReadOnlyList<DateTime> CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15) =>
Enumerable.Range(0, count) [
.. Enumerable.Range(0, count)
.Select(i => start.AddMinutes(i * intervalMinutes)) .Select(i => start.AddMinutes(i * intervalMinutes))
.ToArray(); ];
} }
@@ -5,20 +5,13 @@ using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
using PowerMonitorManager; using PowerMonitorManager;
using PowerMonitorManager.Models;
namespace PowerMonitor.Manager.Tests; namespace PowerMonitor.Manager.Tests;
public class PowerSensorDiscoveryServiceTests public class PowerSensorDiscoveryServiceTests
{ {
private readonly Mock<IHaContext> _haContextMock; private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock; private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock = new();
public PowerSensorDiscoveryServiceTests()
{
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<PowerSensorDiscoveryService>>();
}
private PowerSensorDiscoveryService CreateSut( private PowerSensorDiscoveryService CreateSut(
string mainMeterEntityId = PowerMonitorTestData.MainMeterEntityId, string mainMeterEntityId = PowerMonitorTestData.MainMeterEntityId,
@@ -47,12 +40,12 @@ public class PowerSensorDiscoveryServiceTests
params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities) => params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities) =>
_haContextMock _haContextMock
.Setup(h => h.GetAllEntities()) .Setup(h => h.GetAllEntities())
.Returns(entities.Select(entity => SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName)).ToList()); .Returns([.. entities.Select(entity => SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName))]);
private void SetupEntitiesWithoutState(params string[] entityIds) => private void SetupEntitiesWithoutState(params string[] entityIds) =>
_haContextMock _haContextMock
.Setup(h => h.GetAllEntities()) .Setup(h => h.GetAllEntities())
.Returns(entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId)).ToList()); .Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]);
#region Discovery #region Discovery
@@ -346,7 +339,7 @@ public class PowerSensorDiscoveryServiceTests
var sut = CreateSut(); var sut = CreateSut();
// Act // Act
var result = sut.IsPowerSensor(entity); var result = PowerSensorDiscoveryService.IsPowerSensor(entity);
// Assert // Assert
result.Should().Be(expected, $"scenario: {scenario}"); result.Should().Be(expected, $"scenario: {scenario}");
@@ -361,7 +354,7 @@ public class PowerSensorDiscoveryServiceTests
var sut = CreateSut(); var sut = CreateSut();
// Act // Act
var result = sut.IsPowerSensor(entity); var result = PowerSensorDiscoveryService.IsPowerSensor(entity);
// Assert // Assert
result.Should().BeFalse(); result.Should().BeFalse();
@@ -20,42 +20,42 @@ public class ExhaustFanControlServiceTests
private DateTimeOffset Now => _timeProvider.GetUtcNow(); private DateTimeOffset Now => _timeProvider.GetUtcNow();
public static IEnumerable<object[]> ShowerProgressFanStateCases => public static TheoryData<string, ShowerState, string?, bool> ShowerProgressFanStateCases => new()
[ {
["active while fan is off", ShowerState.Active, "off", true], { "active while fan is off", ShowerState.Active, "off", true },
["active while fan is on", ShowerState.Active, "on", false], { "active while fan is on", ShowerState.Active, "on", false },
["active while fan reports uppercase on", ShowerState.Active, "ON", false], { "active while fan reports uppercase on", ShowerState.Active, "ON", false },
["active while fan is unavailable", ShowerState.Active, "unavailable", true], { "active while fan is unavailable", ShowerState.Active, "unavailable", true },
["active while fan state is unknown", ShowerState.Active, "unknown", true], { "active while fan state is unknown", ShowerState.Active, "unknown", true },
["active while fan state is empty", ShowerState.Active, "", true], { "active while fan state is empty", ShowerState.Active, "", true },
["active while fan state is missing", ShowerState.Active, null!, true], { "active while fan state is missing", ShowerState.Active, null, true },
["suspected while fan is off", ShowerState.Suspected, "off", true], { "suspected while fan is off", ShowerState.Suspected, "off", true },
["suspected while fan is on", ShowerState.Suspected, "on", false], { "suspected while fan is on", ShowerState.Suspected, "on", false },
["idle does not touch the fan", ShowerState.Idle, "off", false], { "idle does not touch the fan", ShowerState.Idle, "off", false },
["declining does not turn the fan on", ShowerState.Declining, "off", false], { "declining does not turn the fan on", ShowerState.Declining, "off", false },
["completed does not turn the fan on", ShowerState.Completed, "off", false] { "completed does not turn the fan on", ShowerState.Completed, "off", false }
]; };
public static IEnumerable<object[]> FanRunAfterCases => public static TheoryData<string, int, int, bool> FanRunAfterCases => new()
[ {
["well before run-after duration", 10, 60, false], { "well before run-after duration", 10, 60, false },
["one second before run-after duration", 10, 599, false], { "one second before run-after duration", 10, 599, false },
["exactly at run-after duration", 10, 600, true], { "exactly at run-after duration", 10, 600, true },
["one second after run-after duration", 10, 601, true], { "one second after run-after duration", 10, 601, true },
["well after run-after duration", 10, 660, true], { "well after run-after duration", 10, 660, true },
["zero-minute run-after turns off immediately", 0, 0, true], { "zero-minute run-after turns off immediately", 0, 0, true },
["long run-after keeps fan running", 30, 300, false] { "long run-after keeps fan running", 30, 300, false }
]; };
public static IEnumerable<object[]> ResetCases => public static TheoryData<string, bool, string?, bool> ResetCases => new()
[ {
["fan on after we turned it on", true, "on", true], { "fan on after we turned it on", true, "on", true },
["fan reports uppercase on", true, "ON", true], { "fan reports uppercase on", true, "ON", true },
["fan already off again", true, "off", false], { "fan already off again", true, "off", false },
["fan unavailable", true, "unavailable", false], { "fan unavailable", true, "unavailable", false },
["fan state missing", true, null!, false], { "fan state missing", true, null, false },
["we never turned the fan on", false, "on", false] { "we never turned the fan on", false, "on", false }
]; };
[Theory] [Theory]
[MemberData(nameof(ShowerProgressFanStateCases))] [MemberData(nameof(ShowerProgressFanStateCases))]
@@ -13,28 +13,28 @@ public class HumidityRateCalculatorTests
private DateTimeOffset Now => _timeProvider.GetUtcNow(); private DateTimeOffset Now => _timeProvider.GetUtcNow();
public static IEnumerable<object[]> RateCases => public static TheoryData<string, int, double[], int[], double> RateCases => new()
[ {
["no readings", 5, Array.Empty<double>(), Array.Empty<int>(), 0.0], { "no readings", 5, Array.Empty<double>(), Array.Empty<int>(), 0.0 },
["single reading", 5, new[] { 52.9 }, new[] { 0 }, 0.0], { "single reading", 5, [52.9], [0], 0.0 },
["rising humidity", 5, new[] { 52.9, 62.9 }, new[] { 0, 60 }, 10.0], { "rising humidity", 5, [52.9, 62.9], [0, 60], 10.0 },
["falling humidity", 5, new[] { 62.9, 52.9 }, new[] { 0, 120 }, -5.0], { "falling humidity", 5, [62.9, 52.9], [0, 120], -5.0 },
["same timestamp", 5, new[] { 52.9, 62.9 }, new[] { 0, 0 }, 0.0], { "same timestamp", 5, [52.9, 62.9], [0, 0], 0.0 },
["flat humidity", 5, new[] { 55.0, 55.0, 55.0 }, new[] { 0, 60, 120 }, 0.0], { "flat humidity", 5, [55.0, 55.0, 55.0], [0, 60, 120], 0.0 },
["linear three readings", 5, new[] { 50.0, 55.0, 60.0 }, new[] { 0, 60, 120 }, 5.0], { "linear three readings", 5, [50.0, 55.0, 60.0], [0, 60, 120], 5.0 },
["window drops stalest reading", 3, new[] { 52.9, 57.9, 62.9, 64.9 }, new[] { 0, 60, 120, 180 }, 3.5], { "window drops stalest reading", 3, [52.9, 57.9, 62.9, 64.9], [0, 60, 120, 180], 3.5 },
["window keeps only last two readings", 2, new[] { 50.0, 55.0, 60.0 }, new[] { 0, 60, 120 }, 5.0], { "window keeps only last two readings", 2, [50.0, 55.0, 60.0], [0, 60, 120], 5.0 },
["single-sample window always returns zero", 1, new[] { 50.0, 55.0, 60.0 }, new[] { 0, 60, 120 }, 0.0], { "single-sample window always returns zero", 1, [50.0, 55.0, 60.0], [0, 60, 120], 0.0 },
["zero-sized window always returns zero", 0, new[] { 50.0, 55.0, 60.0 }, new[] { 0, 60, 120 }, 0.0], { "zero-sized window always returns zero", 0, [50.0, 55.0, 60.0], [0, 60, 120], 0.0 },
["gap larger than window", 5, new[] { 20.0, 26.0 }, new[] { 0, 3_600 }, 0.1], { "gap larger than window", 5, [20.0, 26.0], [0, 3_600], 0.1 },
["out of order timestamps", 5, new[] { 60.0, 50.0 }, new[] { 120, 0 }, 0.0], { "out of order timestamps", 5, [60.0, 50.0], [120, 0], 0.0 },
["very large rise", 5, new[] { 0.0, 10_000.0 }, new[] { 0, 60 }, 10_000.0], { "very large rise", 5, [0.0, 10_000.0], [0, 60], 10_000.0 },
["negative humidity values", 5, new[] { -20.0, 0.0 }, new[] { 0, 60 }, 20.0], { "negative humidity values", 5, [-20.0, 0.0], [0, 60], 20.0 },
["tiny rise", 5, new[] { 50.0, 50.001 }, new[] { 0, 60 }, 0.001], { "tiny rise", 5, [50.0, 50.001], [0, 60], 0.001 },
["shower spike over sixty seconds", 5, new[] { 52.9, 59.9, 64.9 }, new[] { 0, 30, 60 }, 12.0], { "shower spike over sixty seconds", 5, [52.9, 59.9, 64.9], [0, 30, 60], 12.0 },
["middle readings do not affect the window endpoints", 3, new[] { 40.0, 80.0, 60.0, 45.0 }, new[] { 0, 30, 60, 90 }, -35.0], { "middle readings do not affect the window endpoints", 3, [40.0, 80.0, 60.0, 45.0], [0, 30, 60, 90], -35.0 },
["small change over fifteen minutes", 5, new[] { 50.0, 50.6 }, new[] { 0, 900 }, 0.04] { "small change over fifteen minutes", 5, [50.0, 50.6], [0, 900], 0.04 }
]; };
[Theory] [Theory]
[MemberData(nameof(RateCases))] [MemberData(nameof(RateCases))]
@@ -15,43 +15,43 @@ public class ShowerDetectionServiceTests
private DateTimeOffset Now => _timeProvider.GetUtcNow(); private DateTimeOffset Now => _timeProvider.GetUtcNow();
public static IEnumerable<object[]> IdleThresholdCases => public static TheoryData<string, double, double, ShowerState> IdleThresholdCases => new()
[ {
["both thresholds met exactly", 52.0, 44.0, ShowerState.Suspected], { "both thresholds met exactly", 52.0, 44.0, ShowerState.Suspected },
["rate one step under threshold", 51.98, 44.0, ShowerState.Idle], { "rate one step under threshold", 51.98, 44.0, ShowerState.Idle },
["differential one step under threshold", 52.0, 44.02, ShowerState.Idle], { "differential one step under threshold", 52.0, 44.02, ShowerState.Idle },
["well above both thresholds", 60.0, 52.0, ShowerState.Suspected], { "well above both thresholds", 60.0, 52.0, ShowerState.Suspected },
["negative differential", 52.0, 60.0, ShowerState.Idle], { "negative differential", 52.0, 60.0, ShowerState.Idle },
["zero rate with large differential", 50.0, 42.0, ShowerState.Idle], { "zero rate with large differential", 50.0, 42.0, ShowerState.Idle },
["negative rate with large differential", 45.0, 37.0, ShowerState.Idle], { "negative rate with large differential", 45.0, 37.0, ShowerState.Idle },
["very large humidity spike", 1000.0, 500.0, ShowerState.Suspected] { "very large humidity spike", 1000.0, 500.0, ShowerState.Suspected }
]; };
public static IEnumerable<object[]> ConfirmationCases => public static TheoryData<string, double, double, int, ShowerState> ConfirmationCases => new()
[ {
["confirmation window reached", 66.0, 49.5, 120, ShowerState.Active], { "confirmation window reached", 66.0, 49.5, 120, ShowerState.Active },
["confirmation window not yet reached", 66.0, 49.5, 119, ShowerState.Suspected], { "confirmation window not yet reached", 66.0, 49.5, 119, ShowerState.Suspected },
["same instant as the spike", 66.0, 49.5, 0, ShowerState.Suspected], { "same instant as the spike", 66.0, 49.5, 0, ShowerState.Suspected },
["peak humidity exactly at threshold", 58.0, 49.0, 120, ShowerState.Active], { "peak humidity exactly at threshold", 58.0, 49.0, 120, ShowerState.Active },
["peak humidity just below threshold", 57.5, 49.0, 120, ShowerState.Suspected], { "peak humidity just below threshold", 57.5, 49.0, 120, ShowerState.Suspected },
["differential exactly at threshold", 60.0, 52.0, 120, ShowerState.Active], { "differential exactly at threshold", 60.0, 52.0, 120, ShowerState.Active },
["differential just below threshold", 66.0, 58.02, 120, ShowerState.Suspected], { "differential just below threshold", 66.0, 58.02, 120, ShowerState.Suspected },
["very large humidity at confirmation", 1000.0, 900.0, 120, ShowerState.Active] { "very large humidity at confirmation", 1000.0, 900.0, 120, ShowerState.Active }
]; };
public static IEnumerable<object[]> RecoveryBoundaryCases => public static TheoryData<string, double, ShowerState> RecoveryBoundaryCases => new()
[ {
["differential well under threshold", 52.0, ShowerState.Completed], { "differential well under threshold", 52.0, ShowerState.Completed },
["differential exactly at threshold", 50.0, ShowerState.Completed], { "differential exactly at threshold", 50.0, ShowerState.Completed },
["differential just above threshold", 49.98, ShowerState.Declining] { "differential just above threshold", 49.98, ShowerState.Declining }
]; };
public static IEnumerable<object[]> MaxDurationCases => public static TheoryData<string, int, ShowerState> MaxDurationCases => new()
[ {
["one second before max duration", 3_599, ShowerState.Active], { "one second before max duration", 3_599, ShowerState.Active },
["exactly at max duration", 3_600, ShowerState.Declining], { "exactly at max duration", 3_600, ShowerState.Declining },
["one second past max duration", 3_601, ShowerState.Declining] { "one second past max duration", 3_601, ShowerState.Declining }
]; };
[Fact] [Fact]
public void InitialState_IsIdle() public void InitialState_IsIdle()
@@ -13,7 +13,7 @@ namespace ShowerMonitor.Manager.Tests;
internal static class ShowerMonitorTestData internal static class ShowerMonitorTestData
{ {
/// <summary>Fixed base time used by all timestamp-sensitive tests.</summary> /// <summary>Fixed base time used by all timestamp-sensitive tests.</summary>
public static readonly DateTimeOffset BaseTimestamp = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); private static readonly DateTimeOffset BaseTimestamp = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
/// <summary>Creates a fake clock positioned at <see cref="BaseTimestamp"/> unless overridden.</summary> /// <summary>Creates a fake clock positioned at <see cref="BaseTimestamp"/> unless overridden.</summary>
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? start = null) => new(start ?? BaseTimestamp); public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? start = null) => new(start ?? BaseTimestamp);
@@ -58,8 +58,7 @@ internal static class ShowerMonitorTestData
/// <summary>Builds a sample series from (humidity, offset-in-seconds) pairs.</summary> /// <summary>Builds a sample series from (humidity, offset-in-seconds) pairs.</summary>
public static IReadOnlyList<HumiditySample> CreateHumiditySeries( public static IReadOnlyList<HumiditySample> CreateHumiditySeries(
params (double Humidity, int OffsetSeconds)[] samples) => params (double Humidity, int OffsetSeconds)[] samples) =>
samples.Select(sample => new HumiditySample(sample.Humidity, TimeSpan.FromSeconds(sample.OffsetSeconds))) [.. samples.Select(sample => new HumiditySample(sample.Humidity, TimeSpan.FromSeconds(sample.OffsetSeconds)))];
.ToArray();
/// <summary> /// <summary>
/// Generates evenly spaced samples along a constant humidity slope, useful for /// Generates evenly spaced samples along a constant humidity slope, useful for
@@ -70,9 +69,8 @@ internal static class ShowerMonitorTestData
double ratePerMinute, double ratePerMinute,
int sampleCount, int sampleCount,
int intervalSeconds = 60) => int intervalSeconds = 60) =>
Enumerable.Range(0, sampleCount) [.. Enumerable.Range(0, sampleCount)
.Select(i => new HumiditySample( .Select(i => new HumiditySample(
startHumidity + (ratePerMinute * i * intervalSeconds / 60.0), startHumidity + ratePerMinute * i * intervalSeconds / 60.0,
TimeSpan.FromSeconds(i * intervalSeconds))) TimeSpan.FromSeconds(i * intervalSeconds)))];
.ToArray();
} }