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