From 5777e641f6c65a7d90a97189bc957f882ee8254f Mon Sep 17 00:00:00 2001 From: ExQz Date: Sun, 29 Nov 2026 21:30:13 +0200 Subject: [PATCH] Add shared test data builders and Qodana configuration - Extract per-monitor *TestData helper classes and rework tests to use them - Add boiler run-time tracker abstraction (implementation pending) - Drop unused NordPool init/update-result types and stale PLAN.md - Add qodana.yaml with the inspection set to keep the analysis focused --- .../BatteryMonitor.Manager.Tests.csproj | 10 +- .../BatteryMonitorTestData.cs | 244 +++++++ .../BatteryNotificationServiceTests.cs | 233 ++++-- .../BatterySensorDiscoveryServiceTests.cs | 303 ++++---- .../BatteryMonitor.Manager.csproj | 6 +- .../BoilerControlServiceTests.cs | 211 +++--- .../BoilerMonitor.Manager.Tests.csproj | 18 +- .../BoilerMonitorConfigTests.cs | 174 ++--- .../BoilerMonitorEntityServiceTests.cs | 691 ++++++++++++------ .../BoilerMonitorOptionsTests.cs | 36 +- .../BoilerMonitorTestData.cs | 271 +++++++ .../WaterReadyServiceTests.cs | 413 +++++------ BoilerMonitor.Manager/BoilerConfigReader.cs | 3 +- .../BoilerMonitor.Manager.csproj | 6 +- .../BoilerMonitorEntityService.cs | 2 +- .../BoilerMonitorServiceRegistration.cs | 3 +- BoilerMonitor.Manager/BoilerRunTimeTracker.cs | 32 + .../BoilerMonitor.Models.csproj | 2 +- HomeAssistant.Entities/EntityManager.cs | 65 +- .../HomeAssistant.Entities.csproj | 16 +- .../HomeAssistant.Models.csproj | 2 +- .../HomeAssistant.Server.csproj | 16 +- HomeAssistant.Server/MqttRecreateApp.cs | 2 +- HomeAssistant.Server/appsettings.json | 18 +- HomeAssistant.Server/program.cs | 2 +- HomeAssistantSDK.sln | 9 + .../LeakMonitor.Manager.Tests.csproj | 10 +- .../LeakMonitorInitTests.cs | 362 +++++++-- .../LeakMonitorTestData.cs | 248 +++++++ .../LeakNotificationServiceTests.cs | 336 +++++++-- .../LeakMonitor.Manager.csproj | 6 +- .../LightControlServiceTests.cs | 147 ++-- .../LightMonitor.Manager.Tests.csproj | 10 +- .../LightMonitorInitTests.cs | 281 ++++--- .../LightMonitorTestData.cs | 179 +++++ .../PresenceServiceTests.cs | 196 +++-- .../LightMonitor.Manager.csproj | 4 +- .../LightMonitor.Models.csproj | 2 +- Mappings/Mappings.csproj | 2 +- .../CheapestIntervalsFinderTests.cs | 444 +++++------ .../CompactNordPoolDayPriceTests.cs | 105 ++- .../NordPool.Manager.Tests.csproj | 12 +- .../NordPoolEntityServiceTests.cs | 422 +++++++++-- NordPool.Manager.Tests/NordPoolInitTests.cs | 44 +- .../NordPoolPriceServiceTests.cs | 307 ++++++-- NordPool.Manager.Tests/NordPoolTestData.cs | 48 ++ NordPool.Manager/Interface/INordPoolInit.cs | 7 - .../Interface/INordPoolPriceService.cs | 3 +- .../Models/CheapestIntervalsUpdateResult.cs | 11 - NordPool.Manager/NordPool.Manager.csproj | 8 +- NordPool.Manager/NordPoolEntityService.cs | 6 +- NordPool.Manager/NordPoolInit.cs | 96 +-- NordPool.Manager/NordPoolPriceService.cs | 22 +- NordPool.Models/NordPool.Models.csproj | 2 +- PLAN.md | 190 ----- .../CostAccumulatorTests.cs | 328 ++++++--- .../OtherPowerCalculationServiceTests.cs | 203 +++-- .../PowerCostCalculationServiceTests.cs | 526 ++++++++++--- .../PowerLimitEnforcementServiceTests.cs | 398 ++++++---- .../PowerMonitor.Manager.Tests.csproj | 12 +- .../PowerMonitorEntityServiceTests.cs | 557 +++++++++----- .../PowerMonitorOptionsTests.cs | 159 ++-- .../PowerMonitorTestData.cs | 217 ++++++ .../PowerSensorDiscoveryServiceTests.cs | 288 +++++--- .../Interface/IPowerMonitorEntityService.cs | 4 +- .../Models/PowerMonitorOptions.cs | 2 +- .../PowerMonitor.Manager.csproj | 4 +- .../PowerMonitorEntityService.cs | 28 +- PowerMonitor.Manager/PowerMonitorInit.cs | 44 +- .../PowerMonitorServiceRegistration.cs | 5 - .../PowerMonitor.Models.csproj | 2 +- .../ExhaustFanControlServiceTests.cs | 339 ++++++--- .../HumidityRateCalculatorTests.cs | 161 ++-- .../ShowerDetectionServiceTests.cs | 604 +++++++++++---- .../ShowerMonitor.Manager.Tests.csproj | 12 +- .../ShowerMonitorTestData.cs | 78 ++ .../ShowerMonitor.Manager.csproj | 6 +- .../ShowerMonitor.Models.csproj | 2 +- qodana.yaml | 81 ++ 79 files changed, 7162 insertions(+), 3196 deletions(-) create mode 100644 BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs create mode 100644 BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs create mode 100644 BoilerMonitor.Manager/BoilerRunTimeTracker.cs create mode 100644 LeakMonitor.Manager.Tests/LeakMonitorTestData.cs create mode 100644 LightMonitor.Manager.Tests/LightMonitorTestData.cs create mode 100644 NordPool.Manager.Tests/NordPoolTestData.cs delete mode 100644 NordPool.Manager/Interface/INordPoolInit.cs delete mode 100644 NordPool.Manager/Models/CheapestIntervalsUpdateResult.cs delete mode 100644 PLAN.md create mode 100644 PowerMonitor.Manager.Tests/PowerMonitorTestData.cs create mode 100644 ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs create mode 100644 qodana.yaml diff --git a/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj b/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj index 92c8040..56f1320 100644 --- a/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj +++ b/BatteryMonitor.Manager.Tests/BatteryMonitor.Manager.Tests.csproj @@ -8,18 +8,18 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + diff --git a/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs b/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs new file mode 100644 index 0000000..a358b02 --- /dev/null +++ b/BatteryMonitor.Manager.Tests/BatteryMonitorTestData.cs @@ -0,0 +1,244 @@ +using System.Globalization; +using System.Text.Json; +using BatteryMonitor.Models; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; + +namespace BatteryMonitor.Manager.Tests; + +/// +/// Shared, deterministic builders and datasets used by the BatteryMonitor tests. +/// Keeping entity/state construction and generated inputs here means the test +/// classes only describe the scenario under test. +/// +internal static class BatteryMonitorTestData +{ + public const string DefaultFriendlyName = "Battery Device"; + + /// + /// Describes one entity exposed through . + /// + public sealed record EntitySpec + { + public required string EntityId { get; init; } + + public string? State { get; init; } = "50"; + + public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass; + + public string? FriendlyName { get; init; } = DefaultFriendlyName; + + /// When false the context returns no for the entity. + public bool HasState { get; init; } = true; + } + + /// A battery device-class sensor. + public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName) + { + return new EntitySpec + { + EntityId = entityId, + State = state, + FriendlyName = friendlyName + }; + } + + /// A sensor with an arbitrary (or missing) device class. + public static EntitySpec Sensor(string entityId, string? deviceClass, string? state, string? friendlyName = DefaultFriendlyName) + { + return new EntitySpec + { + EntityId = entityId, + DeviceClass = deviceClass, + State = state, + FriendlyName = friendlyName + }; + } + + public static EntityState CreateEntityState(EntitySpec spec) + { + var attributes = new Dictionary(StringComparer.Ordinal); + + if (spec.DeviceClass is not null) + { + attributes["device_class"] = spec.DeviceClass; + } + + if (spec.FriendlyName is not null) + { + attributes["friendly_name"] = spec.FriendlyName; + } + + return new EntityState + { + State = spec.State, + AttributesJson = JsonSerializer.SerializeToElement(attributes) + }; + } + + /// + /// Wires and + /// on the mock and returns the created entities in declaration order. + /// + public static IReadOnlyList ConfigureHaContext(Mock haContextMock, params EntitySpec[] entities) + { + var entityList = new List(entities.Length); + + foreach (var spec in entities) + { + if (spec.HasState) + { + haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec)); + } + + entityList.Add(new Entity(haContextMock.Object, spec.EntityId)); + } + + haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList); + + return entityList; + } + + public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null) + { + return new BatterySensorInfo + { + EntityId = entityId, + FriendlyName = friendlyName ?? entityId, + BatteryLevel = batteryLevel + }; + } + + public static List CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors) + { + return sensors + .Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel)) + .ToList(); + } + + public static List CreateSensorInfos(params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors) + { + return sensors + .Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName)) + .ToList(); + } + + /// + /// Generates battery sensors with every integer level in 0..count-1. + /// + 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(); + } + + /// + /// Generates notification devices with deterministic, non-monotonic levels so + /// ordering behaviour is exercised over more than a handful of rows. + /// + public static IReadOnlyList CreateGeneratedSensorInfos(int count) + { + return Enumerable.Range(0, count) + .Select(i => CreateSensorInfo( + $"sensor.generated_{i:D3}", + (i * 37) % 101, + $"Generated Device {i:D3}")) + .ToList(); + } + + /// + /// (threshold, state, expected) rows straddling the strict level < threshold + /// boundary, including zero/negative thresholds and int min/max thresholds. + /// + public static TheoryData ThresholdBoundaryRows { get; } = new() + { + { 5, "4", true }, + { 5, "5", false }, + { 5, "6", false }, + { 5, "0", true }, + { 5, "-3", true }, + { 5, "4.9", true }, + { 5, "5.0", false }, + { 5, "100", false }, + { 1, "0.5", true }, + { 1, "1", false }, + { 20, "19", true }, + { 20, "19.99", true }, + { 20, "20", false }, + { 0, "-1", true }, + { 0, "0", false }, + { 0, "1", false }, + { -5, "-6", true }, + { -5, "-5", false }, + { -5, "-4", false }, + { 100, "99.9", true }, + { 100, "100", false }, + { 101, "100", true }, + { int.MaxValue, "100", true }, + { int.MinValue, "-2147483648", false }, + { int.MinValue, "-2147483649", true } + }; + + /// + /// States that must never produce a , including + /// whitespace/malformed strings and a null state. + /// + public static TheoryData UnusableStateRows { get; } = new() + { + "unavailable", + "unknown", + "UNAVAILABLE", + "UNKNOWN", + "", + " ", + "\t", + "not_a_number", + "3%", + "--1", + "low", + "1 2", + (string?)null + }; + + /// + /// Cross-product of every excluded keyword (lower and upper case) plus + /// non-excluded look-alikes that must not be filtered. + /// + public static TheoryData ExcludedEntityIdRows() + { + var data = new TheoryData(); + + foreach (var keyword in BatteryMonitorConsts.ExcludedKeywords) + { + data.Add($"sensor.my_{keyword}_battery_level", true); + data.Add($"SENSOR.MY_{keyword.ToUpperInvariant()}_BATTERY_LEVEL", true); + } + + data.Add("sensor.iphone", true); + data.Add("sensor.x_phone_x", true); + data.Add("sensor.bathroom_battery", false); + data.Add("sensor.boiler_temp_battery", false); + data.Add("sensor.aquarium_leak_sensor_battery", false); + data.Add("sensor.temperature", false); + data.Add("", false); + data.Add(" ", false); + + return data; + } + + /// Device counts used to exercise notification payload generation. + public static TheoryData NotifyDeviceCounts { get; } = new() + { + 1, + 2, + 3, + 5, + 10, + 50 + }; +} diff --git a/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs b/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs index 17eb02e..dd7583d 100644 --- a/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs +++ b/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using FluentAssertions; using Microsoft.Extensions.Logging; using Moq; @@ -5,50 +6,55 @@ using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using BatteryMonitor.Models; using BatteryMonitorManager; +using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData; namespace BatteryMonitor.Manager.Tests; public class BatteryNotificationServiceTests { - private readonly Mock _haContextMock; - private readonly Mock> _loggerMock; - - public BatteryNotificationServiceTests() - { - _haContextMock = new Mock(); - _loggerMock = new Mock>(); - } + private readonly Mock _haContextMock = new(); + private readonly Mock> _loggerMock = new(); private BatteryNotificationService CreateSut() { return new BatteryNotificationService(_haContextMock.Object, _loggerMock.Object); } + private void VerifyCallService(string service, Times times) + { + _haContextMock.Verify(h => h.CallService( + BatteryMonitorConsts.PersistentNotificationDomain, + service, + It.IsAny(), + It.IsAny()), times); + } + #region NotifyLowBattery - [Fact] - public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate() + [Theory] + [MemberData(nameof(NotifyDeviceCounts), MemberType = typeof(BatteryMonitorTestData))] + public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount) { - var devices = new List - { - new() { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", BatteryLevel = 3 }, - new() { EntityId = "sensor.bedroom_battery", FriendlyName = "Bedroom Battery", BatteryLevel = 1 } - }; + var devices = CreateSensorInfos( + Enumerable.Range(0, deviceCount) + .Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5))) + .ToArray()); var sut = CreateSut(); sut.NotifyLowBattery(devices); - _haContextMock.Verify(h => h.CallService( - BatteryMonitorConsts.PersistentNotificationDomain, - BatteryMonitorConsts.PersistentNotificationCreateService, - It.IsAny(), - It.IsAny()), Times.Once); + VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Once()); + VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Never()); } - [Fact] - public void NotifyLowBattery_WithEmptyList_ShouldNotCallService() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void NotifyLowBattery_WithEmptyList_ShouldNotCallService(bool useArray) { - var devices = new List(); + IReadOnlyList devices = useArray + ? Array.Empty() + : new List(); var sut = CreateSut(); sut.NotifyLowBattery(devices); @@ -58,6 +64,59 @@ public class BatteryNotificationServiceTests It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + _loggerMock.Invocations.Should().BeEmpty(); + } + + [Fact] + public void NotifyLowBattery_ShouldSendTitleNotificationIdAndDeviceSummary() + { + object? payload = null; + _haContextMock + .Setup(h => h.CallService( + BatteryMonitorConsts.PersistentNotificationDomain, + BatteryMonitorConsts.PersistentNotificationCreateService, + It.IsAny(), + It.IsAny())) + .Callback((_, _, _, data) => payload = data); + + var sut = CreateSut(); + sut.NotifyLowBattery(CreateSensorInfos( + ("sensor.a", "Device A", 4), + ("sensor.b", "Device B", 1))); + + payload.Should().NotBeNull(); + + using var document = JsonDocument.Parse(JsonSerializer.Serialize(payload)); + var root = document.RootElement; + root.GetProperty("title").GetString().Should().Be(BatteryMonitorConsts.NotificationTitle); + root.GetProperty("notification_id").GetString().Should().Be(BatteryMonitorConsts.NotificationId); + + var message = root.GetProperty("message").GetString(); + message.Should().Contain("Device A").And.Contain("Device B"); + message.Should().Contain("1%").And.Contain("4%"); + } + + [Fact] + public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount() + { + var devices = CreateSensorInfos( + ("sensor.a", "Device A", 2), + ("sensor.b", "Device B", 3)); + + var sut = CreateSut(); + sut.NotifyLowBattery(devices); + + _loggerMock.Verify( + l => l.Log( + LogLevel.Information, + It.IsAny(), + It.Is((state, _) => string.Equals( + state!.ToString(), + "Sent low battery notification for 2 device(s)", + StringComparison.Ordinal)), + It.IsAny(), + It.IsAny>()), + Times.Once); } #endregion @@ -70,11 +129,25 @@ public class BatteryNotificationServiceTests var sut = CreateSut(); sut.DismissNotification(); - _haContextMock.Verify(h => h.CallService( - BatteryMonitorConsts.PersistentNotificationDomain, - BatteryMonitorConsts.PersistentNotificationDismissService, - It.IsAny(), - It.IsAny()), Times.Once); + VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Once()); + VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never()); + } + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(5)] + public void DismissNotification_WhenCalledRepeatedly_ShouldDismissEachTime(int calls) + { + var sut = CreateSut(); + + for (var i = 0; i < calls; i++) + { + sut.DismissNotification(); + } + + VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls)); + VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never()); } #endregion @@ -84,41 +157,88 @@ public class BatteryNotificationServiceTests [Fact] public void BuildNotificationMessage_ShouldOrderByBatteryLevel() { - var devices = new List - { - new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 4 }, - new() { EntityId = "sensor.b", FriendlyName = "Device B", BatteryLevel = 1 }, - new() { EntityId = "sensor.c", FriendlyName = "Device C", BatteryLevel = 3 } - }; + var devices = CreateSensorInfos( + ("sensor.a", "Device A", 4), + ("sensor.b", "Device B", 1), + ("sensor.c", "Device C", 3)); var message = BatteryNotificationService.BuildNotificationMessage(devices); var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); + lines.Should().HaveCount(4); lines[1].Should().Contain("Device B"); lines[2].Should().Contain("Device C"); lines[3].Should().Contain("Device A"); } + [Fact] + public void BuildNotificationMessage_ShouldKeepInsertionOrderForEqualLevels() + { + var devices = CreateSensorInfos( + ("sensor.first", "First Device", 4), + ("sensor.second", "Second Device", 4), + ("sensor.third", "Third Device", 1)); + + var message = BatteryNotificationService.BuildNotificationMessage(devices); + + var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); + lines.Should().HaveCount(4); + lines[1].Should().Contain("Third Device"); + lines[2].Should().Contain("First Device"); + lines[3].Should().Contain("Second Device"); + } + + [Fact] + public void BuildNotificationMessage_WithGeneratedDevices_ShouldOrderByAscendingLevel() + { + var devices = CreateGeneratedSensorInfos(50); + + var message = BatteryNotificationService.BuildNotificationMessage(devices); + + var expectedLines = devices + .OrderBy(d => d.BatteryLevel) + .Select(d => $"- **{d.FriendlyName}**: {d.BatteryLevel:F0}%"); + + var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); + lines.Should().HaveCount(devices.Count + 1); + lines.Skip(1).Should().Equal(expectedLines); + } + [Fact] public void BuildNotificationMessage_ShouldContainTitle() { - var devices = new List - { - new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 2 } - }; + var devices = CreateSensorInfos(("sensor.a", "Device A", 2)); var message = BatteryNotificationService.BuildNotificationMessage(devices); message.Should().Contain("low battery"); } + [Theory] + [InlineData("Bathroom Battery", 3, "- **Bathroom Battery**: 3%")] + [InlineData("Test Device", 1, "- **Test Device**: 1%")] + [InlineData("Empty Battery", 0, "- **Empty Battery**: 0%")] + [InlineData("Negative Battery", -7, "- **Negative Battery**: -7%")] + [InlineData("Rounded Down", 12.4, "- **Rounded Down**: 12%")] + [InlineData("Rounded Up", 12.6, "- **Rounded Up**: 13%")] + [InlineData("Full Battery", 100, "- **Full Battery**: 100%")] + [InlineData("", 5, "- ****: 5%")] + [InlineData(" ", 4, "- ** **: 4%")] + public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, double batteryLevel, string expectedLine) + { + var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel)); + + var message = BatteryNotificationService.BuildNotificationMessage(devices); + + var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); + lines.Should().HaveCount(2); + lines[1].Should().Be(expectedLine); + } + [Fact] public void BuildNotificationMessage_ShouldContainDeviceNameAndLevel() { - var devices = new List - { - new() { EntityId = "sensor.a", FriendlyName = "Bathroom Battery", BatteryLevel = 3 } - }; + var devices = CreateSensorInfos(("sensor.a", "Bathroom Battery", 3)); var message = BatteryNotificationService.BuildNotificationMessage(devices); @@ -129,15 +249,36 @@ public class BatteryNotificationServiceTests [Fact] public void BuildNotificationMessage_WithSingleDevice_ShouldFormatCorrectly() { - var devices = new List - { - new() { EntityId = "sensor.a", FriendlyName = "Test Device", BatteryLevel = 1 } - }; + var devices = CreateSensorInfos(("sensor.a", "Test Device", 1)); var message = BatteryNotificationService.BuildNotificationMessage(devices); message.Should().Contain("- **Test Device**: 1%"); } + [Fact] + public void BuildNotificationMessage_WithDuplicateDevices_ShouldListEveryDevice() + { + var devices = CreateSensorInfos( + ("sensor.duplicate_battery", "Duplicate Battery", 2), + ("sensor.duplicate_battery", "Duplicate Battery", 2)); + + var message = BatteryNotificationService.BuildNotificationMessage(devices); + + var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); + lines.Should().HaveCount(3); + lines[1].Should().Be("- **Duplicate Battery**: 2%"); + lines[2].Should().Be("- **Duplicate Battery**: 2%"); + } + + [Fact] + public void BuildNotificationMessage_WithNoDevices_ShouldContainOnlyHeader() + { + var message = BatteryNotificationService.BuildNotificationMessage(Array.Empty()); + + message.Should().Be("The following devices have low battery:"); + message.Should().NotContain("- **"); + } + #endregion } diff --git a/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs b/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs index d9566c2..ffdac4e 100644 --- a/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs +++ b/BatteryMonitor.Manager.Tests/BatterySensorDiscoveryServiceTests.cs @@ -1,11 +1,12 @@ -using System.Text.Json; +using System.Globalization; using FluentAssertions; using Microsoft.Extensions.Logging; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using BatteryMonitorManager; using BatteryMonitor.Models; +using BatteryMonitorManager; +using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData; namespace BatteryMonitor.Manager.Tests; @@ -25,33 +26,9 @@ public class BatterySensorDiscoveryServiceTests return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object); } - private void SetupEntities(params (string entityId, string? deviceClass, string? state, string? friendlyName)[] entities) + private IReadOnlyList SetupEntities(params EntitySpec[] entities) { - var entityList = new List(); - - foreach (var (entityId, deviceClass, state, friendlyName) in entities) - { - var attributes = new Dictionary(); - if (deviceClass is not null) - { - attributes["device_class"] = deviceClass; - } - - if (friendlyName is not null) - { - attributes["friendly_name"] = friendlyName; - } - - var attributesJson = JsonSerializer.SerializeToElement(attributes); - var entityState = new EntityState { AttributesJson = attributesJson, State = state }; - - _haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState); - - var entity = new Entity(_haContextMock.Object, entityId); - entityList.Add(entity); - } - - _haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList); + return ConfigureHaContext(_haContextMock, entities); } #region Discovery @@ -60,9 +37,9 @@ public class BatterySensorDiscoveryServiceTests public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices() { SetupEntities( - ("sensor.bathroom_battery", "battery", "3", "Bathroom Battery"), - ("sensor.bedroom_battery", "battery", "80", "Bedroom Battery"), - ("sensor.boiler_temp_battery", "battery", "2", "Boiler Temp Battery") + Battery("sensor.bathroom_battery", "3", "Bathroom Battery"), + Battery("sensor.bedroom_battery", "80", "Bedroom Battery"), + Battery("sensor.boiler_temp_battery", "2", "Boiler Temp Battery") ); var sut = CreateSut(); @@ -71,134 +48,110 @@ public class BatterySensorDiscoveryServiceTests result.Should().HaveCount(2); result.Should().Contain(s => s.EntityId == "sensor.bathroom_battery"); result.Should().Contain(s => s.EntityId == "sensor.boiler_temp_battery"); + result.Select(s => s.EntityId).Should().NotContain("sensor.bedroom_battery"); } - [Fact] - public void DiscoverLowBatterySensors_ShouldExcludePhoneDevices() + [Theory] + [InlineData("sensor.erikas_iphone_battery_level", "Erika's iPhone Battery")] + [InlineData("sensor.home_phone_battery_state", "Home Phone Battery")] + [InlineData("sensor.marius_watch_battery_level", "Marius Watch Battery")] + [InlineData("sensor.sm_s936b_battery_level", "Galaxy S24 Battery")] + [InlineData("sensor.sm_a536b_battery_level", "Galaxy A53 Battery")] + [InlineData("sensor.pixel_8_battery_level", "Pixel 8 Battery")] + [InlineData("sensor.oneplus_battery_level", "OnePlus Battery")] + [InlineData("sensor.ipad_battery_level", "iPad Battery")] + [InlineData("sensor.galaxy_s24_battery", "Galaxy S24 Battery")] + [InlineData("SENSOR.SM_S936B_BATTERY_LEVEL", "Galaxy S24 Battery")] + public void DiscoverLowBatterySensors_ShouldExcludePersonalDevices(string excludedEntityId, string friendlyName) { SetupEntities( - ("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"), - ("sensor.erikas_iphone_battery_level", "battery", "1", "Erika's iPhone Battery"), - ("sensor.home_phone_battery_state", "battery", "3", "Home Phone Battery") + Battery("sensor.bathroom_battery", "2", "Bathroom Battery"), + Battery(excludedEntityId, "1", friendlyName) ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); - result.Should().HaveCount(1); - result.First().EntityId.Should().Be("sensor.bathroom_battery"); + result.Should().ContainSingle(); + result[0].EntityId.Should().Be("sensor.bathroom_battery"); } - [Fact] - public void DiscoverLowBatterySensors_ShouldExcludeWatchDevices() + [Theory] + [InlineData("binary_sensor.bathroom_battery", "battery")] + [InlineData("sensor.bathroom_temperature", "temperature")] + [InlineData("sensor.bathroom_humidity", "humidity")] + [InlineData("sensor.no_device_class", null)] + [InlineData("sensorx.bathroom_battery", "battery")] + [InlineData("switch.bathroom_battery", "battery")] + public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId, string? deviceClass) { SetupEntities( - ("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"), - ("sensor.marius_watch_battery_level", "battery", "1", "Marius Watch Battery") + Sensor(entityId, deviceClass, "2", "Ignored Entity"), + Battery("sensor.bedroom_battery", "3", "Bedroom Battery") ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); - result.Should().HaveCount(1); - result.First().EntityId.Should().Be("sensor.bathroom_battery"); + result.Should().ContainSingle(); + result[0].EntityId.Should().Be("sensor.bedroom_battery"); } - [Fact] - public void DiscoverLowBatterySensors_ShouldExcludeGalaxyDevices() + [Theory] + [MemberData(nameof(UnusableStateRows), MemberType = typeof(BatteryMonitorTestData))] + public void DiscoverLowBatterySensors_ShouldSkipUnusableStates(string? state) { SetupEntities( - ("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"), - ("sensor.sm_s936b_battery_level", "battery", "1", "Galaxy S24 Battery") + Battery("sensor.bathroom_battery", state, "Bathroom Battery"), + Battery("sensor.bedroom_battery", "3", "Bedroom Battery") ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); - result.Should().HaveCount(1); - result.First().EntityId.Should().Be("sensor.bathroom_battery"); + result.Should().ContainSingle(); + result[0].EntityId.Should().Be("sensor.bedroom_battery"); } [Fact] - public void DiscoverLowBatterySensors_ShouldIgnoreNonSensorDomain() + public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor() { SetupEntities( - ("binary_sensor.bathroom_battery", "battery", "2", "Bathroom Battery"), - ("sensor.bedroom_battery", "battery", "3", "Bedroom Battery") + new EntitySpec { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false }, + Battery("sensor.bedroom_battery", "3", "Bedroom Battery") ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); - result.Should().HaveCount(1); - result.First().EntityId.Should().Be("sensor.bedroom_battery"); + result.Should().ContainSingle(); + result[0].EntityId.Should().Be("sensor.bedroom_battery"); } - [Fact] - public void DiscoverLowBatterySensors_ShouldIgnoreNonBatteryDeviceClass() + [Theory] + [MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))] + public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent, string state, bool expectedIncluded) { - SetupEntities( - ("sensor.bathroom_temperature", "temperature", "2", "Bathroom Temperature"), - ("sensor.bedroom_battery", "battery", "3", "Bedroom Battery") - ); + SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery")); var sut = CreateSut(); - var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + var result = sut.DiscoverLowBatterySensors(thresholdPercent); - result.Should().HaveCount(1); - result.First().EntityId.Should().Be("sensor.bedroom_battery"); - } + result.Should().HaveCount(expectedIncluded ? 1 : 0); - [Fact] - public void DiscoverLowBatterySensors_ShouldSkipUnavailableState() - { - SetupEntities( - ("sensor.bathroom_battery", "battery", "unavailable", "Bathroom Battery"), - ("sensor.bedroom_battery", "battery", "3", "Bedroom Battery") - ); - - var sut = CreateSut(); - var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); - - result.Should().HaveCount(1); - result.First().EntityId.Should().Be("sensor.bedroom_battery"); - } - - [Fact] - public void DiscoverLowBatterySensors_ShouldSkipUnknownState() - { - SetupEntities( - ("sensor.bathroom_battery", "battery", "unknown", "Bathroom Battery"), - ("sensor.bedroom_battery", "battery", "3", "Bedroom Battery") - ); - - var sut = CreateSut(); - var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); - - result.Should().HaveCount(1); - } - - [Fact] - public void DiscoverLowBatterySensors_ShouldSkipNonParsableState() - { - SetupEntities( - ("sensor.bathroom_battery", "battery", "not_a_number", "Bathroom Battery"), - ("sensor.bedroom_battery", "battery", "3", "Bedroom Battery") - ); - - var sut = CreateSut(); - var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); - - result.Should().HaveCount(1); - result.First().EntityId.Should().Be("sensor.bedroom_battery"); + if (expectedIncluded) + { + result[0].EntityId.Should().Be("sensor.boundary_battery"); + result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture)); + } } [Fact] public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty() { SetupEntities( - ("sensor.temperature", "temperature", "22", "Temperature"), - ("switch.some_switch", null, "on", "Switch") + Sensor("sensor.temperature", "temperature", "22", "Temperature"), + Sensor("switch.some_switch", null, "on", "Switch") ); var sut = CreateSut(); @@ -211,8 +164,9 @@ public class BatterySensorDiscoveryServiceTests public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty() { SetupEntities( - ("sensor.bathroom_battery", "battery", "50", "Bathroom Battery"), - ("sensor.bedroom_battery", "battery", "80", "Bedroom Battery") + Battery("sensor.bathroom_battery", "5", "Bathroom Battery"), + Battery("sensor.bedroom_battery", "50", "Bedroom Battery"), + Battery("sensor.boiler_temp_battery", "100", "Boiler Temp Battery") ); var sut = CreateSut(); @@ -222,77 +176,109 @@ public class BatterySensorDiscoveryServiceTests } [Fact] - public void DiscoverLowBatterySensors_ShouldRespectCustomThreshold() + public void DiscoverLowBatterySensors_WhenThereAreNoEntities_ShouldReturnEmpty() { - SetupEntities( - ("sensor.bathroom_battery", "battery", "15", "Bathroom Battery"), - ("sensor.bedroom_battery", "battery", "25", "Bedroom Battery") - ); + SetupEntities(); var sut = CreateSut(); - var result = sut.DiscoverLowBatterySensors(20); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); - result.Should().HaveCount(1); - result.First().EntityId.Should().Be("sensor.bathroom_battery"); + result.Should().NotBeNull(); + result.Should().BeEmpty(); } [Fact] - public void DiscoverLowBatterySensors_ShouldPopulateFriendlyName() + public void DiscoverLowBatterySensors_WithDuplicateSensorIds_ShouldReportEachOccurrence() { SetupEntities( - ("sensor.bathroom_battery", "battery", "2", "Bathroom Battery") + Battery("sensor.duplicate_battery", "2", "Duplicate Battery"), + Battery("sensor.duplicate_battery", "2", "Duplicate Battery") ); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); - result.Should().HaveCount(1); - result.First().FriendlyName.Should().Be("Bathroom Battery"); - result.First().BatteryLevel.Should().Be(2); + result.Should().HaveCount(2); + result.Should().OnlyContain(s => s.EntityId == "sensor.duplicate_battery"); } - [Fact] - public void DiscoverLowBatterySensors_ShouldUseEntityIdWhenNoFriendlyName() + [Theory] + [InlineData("Bathroom Battery", "Bathroom Battery")] + [InlineData("", "")] + [InlineData(" ", " ")] + [InlineData(null, "sensor.bathroom_battery")] + public void DiscoverLowBatterySensors_ShouldResolveFriendlyName(string? friendlyName, string expectedFriendlyName) { - SetupEntities( - ("sensor.bathroom_battery", "battery", "2", null) - ); + SetupEntities(Battery("sensor.bathroom_battery", "2", friendlyName)); var sut = CreateSut(); var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); - result.Should().HaveCount(1); - result.First().FriendlyName.Should().Be("sensor.bathroom_battery"); + result.Should().ContainSingle(); + result[0].EntityId.Should().Be("sensor.bathroom_battery"); + result[0].FriendlyName.Should().Be(expectedFriendlyName); + result[0].BatteryLevel.Should().Be(2); + } + + [Fact] + public void DiscoverLowBatterySensors_ShouldPreserveFractionalBatteryLevel() + { + SetupEntities(Battery("sensor.bathroom_battery", "2.5", "Bathroom Battery")); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent); + + result.Should().ContainSingle(); + result[0].FriendlyName.Should().Be("Bathroom Battery"); + result[0].BatteryLevel.Should().Be(2.5); + } + + [Fact] + public void DiscoverLowBatterySensors_WithGeneratedSensors_ShouldReturnOnlySensorsBelowThreshold() + { + SetupEntities(CreateGeneratedBatteryEntities(101)); + + var sut = CreateSut(); + var result = sut.DiscoverLowBatterySensors(7); + + result.Should().HaveCount(7); + result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i)); + result.Select(s => s.FriendlyName).Should().OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal)); } #endregion #region IsBatterySensor - [Fact] - public void IsBatterySensor_WithBatteryDeviceClass_ShouldReturnTrue() + [Theory] + [InlineData("sensor.bathroom_battery", "battery", true)] + [InlineData("SENSOR.bathroom_battery", "battery", true)] + [InlineData("Sensor.Bathroom_Battery", "BATTERY", true)] + [InlineData("sensor.bathroom_battery", "Battery", true)] + [InlineData("binary_sensor.bathroom_battery", "battery", false)] + [InlineData("binary_sensor.sm_s936b_battery_level", "battery", false)] + [InlineData("sensor.bathroom_temperature", "temperature", false)] + [InlineData("sensor.no_device_class", null, false)] + [InlineData("sensor.bathroom_battery", "", false)] + [InlineData("sensorx.bathroom_battery", "battery", false)] + [InlineData("sensor", "battery", false)] + [InlineData("switch.bathroom_battery", "battery", false)] + public void IsBatterySensor_ShouldClassifyEntities(string entityId, string? deviceClass, bool expected) { - SetupEntities(("sensor.bathroom_battery", "battery", "50", "Bathroom Battery")); + SetupEntities(Sensor(entityId, deviceClass, "50", "Some Entity")); + + var entity = new Entity(_haContextMock.Object, entityId); + + BatterySensorDiscoveryService.IsBatterySensor(entity).Should().Be(expected); + } + + [Fact] + public void IsBatterySensor_WhenEntityHasNoState_ShouldReturnFalse() + { + SetupEntities(new EntitySpec { EntityId = "sensor.bathroom_battery", HasState = false }); + var entity = new Entity(_haContextMock.Object, "sensor.bathroom_battery"); - BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeTrue(); - } - - [Fact] - public void IsBatterySensor_WithNonSensorDomain_ShouldReturnFalse() - { - SetupEntities(("binary_sensor.bathroom_battery", "battery", "50", "Bathroom Battery")); - var entity = new Entity(_haContextMock.Object, "binary_sensor.bathroom_battery"); - - BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse(); - } - - [Fact] - public void IsBatterySensor_WithNonBatteryDeviceClass_ShouldReturnFalse() - { - SetupEntities(("sensor.bathroom_temperature", "temperature", "22", "Bathroom Temperature")); - var entity = new Entity(_haContextMock.Object, "sensor.bathroom_temperature"); - BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse(); } @@ -301,18 +287,7 @@ public class BatterySensorDiscoveryServiceTests #region IsExcludedDevice [Theory] - [InlineData("sensor.erikas_iphone_battery_level", true)] - [InlineData("sensor.home_phone_battery_state", true)] - [InlineData("sensor.marius_watch_battery_level", true)] - [InlineData("sensor.sm_s936b_battery_level", true)] - [InlineData("sensor.sm_a536b_battery_level", true)] - [InlineData("sensor.pixel_8_battery_level", true)] - [InlineData("sensor.oneplus_battery_level", true)] - [InlineData("sensor.ipad_battery_level", true)] - [InlineData("sensor.galaxy_s24_battery", true)] - [InlineData("sensor.bathroom_battery", false)] - [InlineData("sensor.boiler_temp_battery", false)] - [InlineData("sensor.aquarium_leak_sensor_battery", false)] + [MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))] public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected) { BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected); diff --git a/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj b/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj index da25952..851e118 100644 --- a/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj +++ b/BatteryMonitor.Manager/BatteryMonitor.Manager.csproj @@ -19,9 +19,9 @@ - - - + + + diff --git a/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs index ae70aeb..d04403b 100644 --- a/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs @@ -8,13 +8,9 @@ namespace BoilerMonitor.Manager.Tests; public class BoilerControlServiceTests { - private readonly BoilerControlService _sut; + private readonly Mock> _loggerMock = new(); - public BoilerControlServiceTests() - { - var loggerMock = new Mock>(); - _sut = new BoilerControlService(loggerMock.Object); - } + private BoilerControlService CreateSut() => new(_loggerMock.Object); #region TurnOn scenarios @@ -23,10 +19,15 @@ public class BoilerControlServiceTests [InlineData("OFF")] [InlineData("Off")] [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("off ")] [InlineData("unavailable")] + [InlineData("unknown")] + [InlineData("0")] public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState) { - var result = _sut.DetermineAction( + var result = CreateSut().DetermineAction( isNowCheap: true, waterReady: false, currentSwitchState: switchState, budgetExhausted: false, budgetOverride: false); @@ -34,60 +35,53 @@ public class BoilerControlServiceTests } [Theory] - [InlineData("off")] - [InlineData(null)] - public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOn(string? switchState) + [InlineData("off", BoilerAction.TurnOn)] + [InlineData(null, BoilerAction.TurnOn)] + [InlineData("unavailable", BoilerAction.TurnOn)] + [InlineData("on", BoilerAction.NoChange)] + [InlineData("On", BoilerAction.NoChange)] + [InlineData("ON", BoilerAction.NoChange)] + public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOnOnlyIfNotAlreadyOn( + string? switchState, + BoilerAction expectedAction) { - var result = _sut.DetermineAction( + var result = CreateSut().DetermineAction( isNowCheap: true, waterReady: false, currentSwitchState: switchState, budgetExhausted: true, budgetOverride: true); - result.Should().Be(BoilerAction.TurnOn); + result.Should().Be(expectedAction); } #endregion #region TurnOff scenarios - [Fact] - public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff() + [Theory] + [InlineData("on")] + [InlineData("ON")] + [InlineData("On")] + [InlineData("oN")] + public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState) { - var result = _sut.DetermineAction( - isNowCheap: false, waterReady: false, currentSwitchState: "on", + var result = CreateSut().DetermineAction( + isNowCheap: false, waterReady: false, currentSwitchState: switchState, budgetExhausted: false, budgetOverride: false); result.Should().Be(BoilerAction.TurnOff); } - [Fact] - public void DetermineAction_WhenWaterReadyAndSwitchIsOn_ShouldReturnTurnOff() - { - var result = _sut.DetermineAction( - isNowCheap: true, waterReady: true, currentSwitchState: "on", - budgetExhausted: false, budgetOverride: false); - - result.Should().Be(BoilerAction.TurnOff); - } - - [Fact] - public void DetermineAction_WhenBudgetExhaustedAndNoOverride_ShouldReturnTurnOff() - { - var result = _sut.DetermineAction( - isNowCheap: true, waterReady: false, currentSwitchState: "on", - budgetExhausted: true, budgetOverride: false); - - result.Should().Be(BoilerAction.TurnOff); - } - [Theory] - [InlineData("on")] - [InlineData("ON")] - [InlineData("On")] - public void DetermineAction_WhenNotCheapAndSwitchIsOnCaseInsensitive_ShouldReturnTurnOff(string switchState) + [InlineData(true, false, false)] // water ready + [InlineData(false, true, false)] // budget exhausted, no override + [InlineData(true, true, true)] // water ready wins over the budget override + public void DetermineAction_WhenCheapButShouldNotHeatAndSwitchIsOn_ShouldReturnTurnOff( + bool waterReady, + bool budgetExhausted, + bool budgetOverride) { - var result = _sut.DetermineAction( - isNowCheap: false, waterReady: false, currentSwitchState: switchState, - budgetExhausted: false, budgetOverride: false); + var result = CreateSut().DetermineAction( + isNowCheap: true, waterReady: waterReady, currentSwitchState: "on", + budgetExhausted: budgetExhausted, budgetOverride: budgetOverride); result.Should().Be(BoilerAction.TurnOff); } @@ -96,56 +90,107 @@ public class BoilerControlServiceTests #region NoChange scenarios - [Fact] - public void DetermineAction_WhenCheapAndNotReadyAndAlreadyOn_ShouldReturnNoChange() + [Theory] + [InlineData(true, false, "on", false, false)] + [InlineData(false, false, "off", false, false)] + [InlineData(false, false, null, false, false)] + [InlineData(false, false, "unavailable", false, false)] + [InlineData(true, true, "off", false, false)] + [InlineData(true, true, null, false, false)] + [InlineData(true, false, "off", true, false)] + [InlineData(true, false, "off ", true, false)] + [InlineData(true, true, "off", true, true)] + public void DetermineAction_WhenDesiredStateMatchesCurrentState_ShouldReturnNoChange( + bool isNowCheap, + bool waterReady, + string? switchState, + bool budgetExhausted, + bool budgetOverride) { - var result = _sut.DetermineAction( - isNowCheap: true, waterReady: false, currentSwitchState: "on", - budgetExhausted: false, budgetOverride: false); - - result.Should().Be(BoilerAction.NoChange); - } - - [Fact] - public void DetermineAction_WhenNotCheapAndAlreadyOff_ShouldReturnNoChange() - { - var result = _sut.DetermineAction( - isNowCheap: false, waterReady: false, currentSwitchState: "off", - budgetExhausted: false, budgetOverride: false); - - result.Should().Be(BoilerAction.NoChange); - } - - [Fact] - public void DetermineAction_WhenBudgetExhaustedAndAlreadyOff_ShouldReturnNoChange() - { - var result = _sut.DetermineAction( - isNowCheap: true, waterReady: false, currentSwitchState: "off", - budgetExhausted: true, budgetOverride: false); + var result = CreateSut().DetermineAction( + isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride); result.Should().Be(BoilerAction.NoChange); } #endregion - #region Comprehensive theory covering all key combinations + #region Comprehensive truth tables + + /// + /// 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). + /// + public static IEnumerable SwitchOnActionMatrix => + [ + [false, false, false, false, BoilerAction.TurnOff], + [false, false, false, true, BoilerAction.TurnOff], + [false, false, true, false, BoilerAction.TurnOff], + [false, false, true, true, BoilerAction.TurnOff], + [false, true, false, false, BoilerAction.TurnOff], + [false, true, false, true, BoilerAction.TurnOff], + [false, true, true, false, BoilerAction.TurnOff], + [false, true, true, true, BoilerAction.TurnOff], + [true, false, false, false, BoilerAction.NoChange], + [true, false, false, true, BoilerAction.NoChange], + [true, false, true, false, BoilerAction.TurnOff], + [true, false, true, true, BoilerAction.NoChange], + [true, true, false, false, BoilerAction.TurnOff], + [true, true, false, true, BoilerAction.TurnOff], + [true, true, true, false, BoilerAction.TurnOff], + [true, true, true, true, BoilerAction.TurnOff] + ]; [Theory] - [InlineData(true, false, "off", false, false, BoilerAction.TurnOn)] - [InlineData(true, false, "on", false, false, BoilerAction.NoChange)] - [InlineData(true, true, "on", false, false, BoilerAction.TurnOff)] - [InlineData(true, true, "off", false, false, BoilerAction.NoChange)] - [InlineData(false, false, "on", false, false, BoilerAction.TurnOff)] - [InlineData(false, false, "off", false, false, BoilerAction.NoChange)] - [InlineData(true, false, "on", true, false, BoilerAction.TurnOff)] - [InlineData(true, false, "off", true, false, BoilerAction.NoChange)] - [InlineData(true, false, "off", true, true, BoilerAction.TurnOn)] - [InlineData(true, false, "on", true, true, BoilerAction.NoChange)] - public void DetermineAction_AllCombinations_ShouldReturnExpectedAction( - bool isNowCheap, bool waterReady, string switchState, - bool budgetExhausted, bool budgetOverride, BoilerAction expectedAction) + [MemberData(nameof(SwitchOnActionMatrix))] + public void DetermineAction_AllCombinationsWhileSwitchIsOn_ShouldReturnExpectedAction( + bool isNowCheap, + bool waterReady, + bool budgetExhausted, + bool budgetOverride, + BoilerAction expectedAction) { - var result = _sut.DetermineAction(isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride); + var result = CreateSut().DetermineAction( + isNowCheap, waterReady, currentSwitchState: "on", budgetExhausted, budgetOverride); + + result.Should().Be(expectedAction); + } + + /// + /// 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). + /// + public static IEnumerable SwitchOffActionMatrix => + [ + [false, false, false, false, BoilerAction.NoChange], + [false, false, false, true, BoilerAction.NoChange], + [false, false, true, false, BoilerAction.NoChange], + [false, false, true, true, BoilerAction.NoChange], + [false, true, false, false, BoilerAction.NoChange], + [false, true, false, true, BoilerAction.NoChange], + [false, true, true, false, BoilerAction.NoChange], + [false, true, true, true, BoilerAction.NoChange], + [true, false, false, false, BoilerAction.TurnOn], + [true, false, false, true, BoilerAction.TurnOn], + [true, false, true, false, BoilerAction.NoChange], + [true, false, true, true, BoilerAction.TurnOn], + [true, true, false, false, BoilerAction.NoChange], + [true, true, false, true, BoilerAction.NoChange], + [true, true, true, false, BoilerAction.NoChange], + [true, true, true, true, BoilerAction.NoChange] + ]; + + [Theory] + [MemberData(nameof(SwitchOffActionMatrix))] + public void DetermineAction_AllCombinationsWhileSwitchIsOff_ShouldReturnExpectedAction( + bool isNowCheap, + bool waterReady, + bool budgetExhausted, + bool budgetOverride, + BoilerAction expectedAction) + { + var result = CreateSut().DetermineAction( + isNowCheap, waterReady, currentSwitchState: "off", budgetExhausted, budgetOverride); result.Should().Be(expectedAction); } diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj b/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj index 0d09cbf..0d523c5 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj +++ b/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj @@ -8,22 +8,22 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - + + + + + diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs index c9aead4..6a041df 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs @@ -5,129 +5,67 @@ namespace BoilerMonitor.Manager.Tests; public class BoilerMonitorConfigTests { - [Fact] - public void IsFullyConfigured_WhenAllFieldsSet_ShouldReturnTrue() - { - var config = new BoilerMonitorConfig - { - BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", - BoilerSwitchEntityId = "switch.sonoff_1002230e32", - PollIntervalSeconds = 30, - HeatingPowerThresholdWatts = 5.0 - }; + private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId; + private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId; - config.IsFullyConfigured.Should().BeTrue(); + public static IEnumerable ConfigurationCases => + [ + ["fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true], + ["minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true], + ["poll interval of one second", PowerEntityId, SwitchEntityId, 1, 5.0, true], + ["maximum poll interval", PowerEntityId, SwitchEntityId, int.MaxValue, 5.0, true], + ["smallest positive threshold", PowerEntityId, SwitchEntityId, 30, double.Epsilon, true], + ["maximum threshold", PowerEntityId, SwitchEntityId, 30, double.MaxValue, true], + ["infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true], + + ["power entity id null", (string?)null, SwitchEntityId, 30, 5.0, false], + ["power entity id empty", "", SwitchEntityId, 30, 5.0, false], + ["power entity id whitespace", " ", SwitchEntityId, 30, 5.0, false], + ["power entity id tabs and newlines", "\t\n", SwitchEntityId, 30, 5.0, false], + ["switch entity id null", PowerEntityId, (string?)null, 30, 5.0, false], + ["switch entity id empty", PowerEntityId, "", 30, 5.0, false], + ["switch entity id whitespace", PowerEntityId, " ", 30, 5.0, false], + ["both entity ids null", (string?)null, (string?)null, 30, 5.0, false], + + ["poll interval null", PowerEntityId, SwitchEntityId, (int?)null, 5.0, false], + ["poll interval zero", PowerEntityId, SwitchEntityId, 0, 5.0, false], + ["poll interval negative", PowerEntityId, SwitchEntityId, -1, 5.0, false], + ["poll interval minimum value", PowerEntityId, SwitchEntityId, int.MinValue, 5.0, false], + + ["threshold null", PowerEntityId, SwitchEntityId, 30, (double?)null, false], + ["threshold zero", PowerEntityId, SwitchEntityId, 30, 0.0, false], + ["threshold negative", PowerEntityId, SwitchEntityId, 30, -1.0, false], + ["threshold minimum value", PowerEntityId, SwitchEntityId, 30, double.MinValue, false], + ["threshold NaN", PowerEntityId, SwitchEntityId, 30, double.NaN, false], + ["threshold negative infinity", PowerEntityId, SwitchEntityId, 30, double.NegativeInfinity, false] + ]; + + [Theory] + [MemberData(nameof(ConfigurationCases))] + public void IsFullyConfigured_ShouldValidateEveryRequiredField( + string scenario, + string? powerEntityId, + string? switchEntityId, + int? pollIntervalSeconds, + double? heatingPowerThresholdWatts, + bool expected) + { + var config = BoilerMonitorTestData.CreateConfig( + boilerPowerEntityId: powerEntityId, + boilerSwitchEntityId: switchEntityId, + pollIntervalSeconds: pollIntervalSeconds, + heatingPowerThresholdWatts: heatingPowerThresholdWatts); + + config.IsFullyConfigured.Should().Be(expected, scenario); } [Fact] - public void IsFullyConfigured_WhenPowerEntityMissing_ShouldReturnFalse() + public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding() { - var config = new BoilerMonitorConfig - { - BoilerPowerEntityId = null, - BoilerSwitchEntityId = "switch.sonoff_1002230e32", - PollIntervalSeconds = 30, - HeatingPowerThresholdWatts = 5.0 - }; + var config = BoilerMonitorTestData.CreateConfig( + boilerPowerEntityId: " sensor.sonoff_1002230e32_power ", + boilerSwitchEntityId: "SWITCH.SONOFF_1002230E32"); - config.IsFullyConfigured.Should().BeFalse(); - } - - [Fact] - public void IsFullyConfigured_WhenSwitchEntityMissing_ShouldReturnFalse() - { - var config = new BoilerMonitorConfig - { - BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", - BoilerSwitchEntityId = null, - PollIntervalSeconds = 30, - HeatingPowerThresholdWatts = 5.0 - }; - - config.IsFullyConfigured.Should().BeFalse(); - } - - [Fact] - public void IsFullyConfigured_WhenPollIntervalMissing_ShouldReturnFalse() - { - var config = new BoilerMonitorConfig - { - BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", - BoilerSwitchEntityId = "switch.sonoff_1002230e32", - PollIntervalSeconds = null, - HeatingPowerThresholdWatts = 5.0 - }; - - config.IsFullyConfigured.Should().BeFalse(); - } - - [Fact] - public void IsFullyConfigured_WhenThresholdMissing_ShouldReturnFalse() - { - var config = new BoilerMonitorConfig - { - BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", - BoilerSwitchEntityId = "switch.sonoff_1002230e32", - PollIntervalSeconds = 30, - HeatingPowerThresholdWatts = null - }; - - config.IsFullyConfigured.Should().BeFalse(); - } - - [Fact] - public void IsFullyConfigured_WhenPowerEntityIsWhitespace_ShouldReturnFalse() - { - var config = new BoilerMonitorConfig - { - BoilerPowerEntityId = " ", - BoilerSwitchEntityId = "switch.sonoff_1002230e32", - PollIntervalSeconds = 30, - HeatingPowerThresholdWatts = 5.0 - }; - - config.IsFullyConfigured.Should().BeFalse(); - } - - [Fact] - public void IsFullyConfigured_WhenPollIntervalIsZero_ShouldReturnFalse() - { - var config = new BoilerMonitorConfig - { - BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", - BoilerSwitchEntityId = "switch.sonoff_1002230e32", - PollIntervalSeconds = 0, - HeatingPowerThresholdWatts = 5.0 - }; - - config.IsFullyConfigured.Should().BeFalse(); - } - - [Fact] - public void IsFullyConfigured_WhenThresholdIsZero_ShouldReturnFalse() - { - var config = new BoilerMonitorConfig - { - BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", - BoilerSwitchEntityId = "switch.sonoff_1002230e32", - PollIntervalSeconds = 30, - HeatingPowerThresholdWatts = 0.0 - }; - - config.IsFullyConfigured.Should().BeFalse(); - } - - [Fact] - public void IsFullyConfigured_WhenPollIntervalIsNegative_ShouldReturnFalse() - { - var config = new BoilerMonitorConfig - { - BoilerPowerEntityId = "sensor.sonoff_1002230e32_power", - BoilerSwitchEntityId = "switch.sonoff_1002230e32", - PollIntervalSeconds = -1, - HeatingPowerThresholdWatts = 5.0 - }; - - config.IsFullyConfigured.Should().BeFalse(); + config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content"); } } diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs index 4f6f697..8567e67 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs @@ -1,283 +1,436 @@ +using System.Text.Json; using BoilerMonitorManager; using FluentAssertions; using HomeAssistant.Entities.Interfaces; +using HomeAssistant.Models; using Microsoft.Extensions.Logging; using Moq; using NetDaemon.HassModel; -using NetDaemon.HassModel.Entities; using static BoilerMonitor.Models.BoilerMonitorConsts; namespace BoilerMonitor.Manager.Tests; public class BoilerMonitorEntityServiceTests { - private readonly Mock _entityManagerMock; - private readonly Mock _haContextMock; - private readonly Mock> _loggerMock; - private readonly BoilerMonitorEntityService _sut; + /// Every entity that CleanupEntitiesAsync is expected to remove. + private static readonly string[] CleanableEntityIds = + [ + ConfigPowerEntityId, + ConfigSwitchEntityId, + ConfigPollIntervalEntityId, + ConfigHeatingThresholdEntityId, + StatusEntityId, + WaterReadyEntityId, + SkipPriceCapEntityId, + TodayRuntimeEntityId, + RemainingTimeEntityId, + BudgetPercentageEntityId, + BudgetExhaustedEntityId, + SessionCountEntityId, + BudgetOverrideEntityId, + AutoManagementEntityId + ]; + + private readonly Mock _entityManagerMock = new(); + private readonly Mock _haContextMock = new(); + private readonly Mock> _loggerMock = new(); public BoilerMonitorEntityServiceTests() { - _entityManagerMock = new Mock(); - _haContextMock = new Mock(); - _loggerMock = new Mock>(); - _sut = new BoilerMonitorEntityService( - _entityManagerMock.Object, - _haContextMock.Object, - _loggerMock.Object); + _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())) + .Returns(Task.CompletedTask); } - private void SetupEntityState(string entityId, string? state) - { - if (state is null) - { - _haContextMock.Setup(h => h.GetState(entityId)).Returns((EntityState?)null); - } - else - { - _haContextMock.Setup(h => h.GetState(entityId)) - .Returns(new EntityState { State = state }); - } - } + private BoilerMonitorEntityService CreateSut() => new( + _entityManagerMock.Object, + _haContextMock.Object, + _loggerMock.Object); #region ReadPersistedState + [Theory] + [MemberData(nameof(BoilerMonitorTestData.RuntimeStateSamples), MemberType = typeof(BoilerMonitorTestData))] + public void ReadPersistedState_WhenRuntimeStateVaries_ShouldParseOrReject( + string? runtimeState, + TimeSpan? expectedRunTime) + { + _haContextMock.SetupEntityStates( + BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: runtimeState, sessionCount: "2")); + + var result = CreateSut().ReadPersistedState(); + + if (expectedRunTime is null) + { + result.Should().BeNull(); + return; + } + + result.Should().NotBeNull(); + result!.AccumulatedRunTime.Should().Be(expectedRunTime.Value); + result.SessionCount.Should().Be(2); + } + + [Theory] + [MemberData(nameof(BoilerMonitorTestData.SessionCountStateSamples), MemberType = typeof(BoilerMonitorTestData))] + public void ReadPersistedState_WhenSessionCountStateVaries_ShouldParseOrReject( + string? sessionCountState, + int? expectedSessionCount) + { + _haContextMock.SetupEntityStates( + BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: "3600", sessionCount: sessionCountState)); + + var result = CreateSut().ReadPersistedState(); + + if (expectedSessionCount is null) + { + result.Should().BeNull(); + return; + } + + result.Should().NotBeNull(); + result!.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(1)); + result.SessionCount.Should().Be(expectedSessionCount.Value); + } + [Fact] public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues() { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "7200"); - SetupEntityState(SessionCountEntityId, "3"); - SetupEntityState(SkipPriceCapEntityId, "ON"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); + _haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates( + todayRuntime: "7200", sessionCount: "3", skipPriceCap: "ON", budgetOverride: "OFF")); - // Act - var result = _sut.ReadPersistedState(); + var result = CreateSut().ReadPersistedState(); - // Assert result.Should().NotBeNull(); - result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(7200)); + result!.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(2)); result.SessionCount.Should().Be(3); result.SkipPriceCapState.Should().Be("ON"); result.BudgetOverrideState.Should().Be("OFF"); } - [Fact] - public void ReadPersistedState_WithZeroRuntime_ShouldReturnZeroValues() + [Theory] + [InlineData("ON")] + [InlineData("on")] + [InlineData(" On ")] + [InlineData("")] + [InlineData(null)] + public void ReadPersistedState_ShouldReturnRawSwitchStates(string? switchState) { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "0"); - SetupEntityState(SessionCountEntityId, "0"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); + _haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates( + skipPriceCap: switchState, budgetOverride: switchState)); - // Act - var result = _sut.ReadPersistedState(); + var result = CreateSut().ReadPersistedState(); - // Assert result.Should().NotBeNull(); - result!.AccumulatedRunTime.Should().Be(TimeSpan.Zero); - result.SessionCount.Should().Be(0); + result!.SkipPriceCapState.Should().Be(switchState); + result.BudgetOverrideState.Should().Be(switchState); } [Fact] - public void ReadPersistedState_WhenRuntimeIsUnavailable_ShouldReturnNull() + public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull() { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "unavailable"); - SetupEntityState(SessionCountEntityId, "3"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); + _haContextMock.SetupEntityStates( + BoilerMonitorTestData.CreatePersistedEntityStates(todayRuntime: null, sessionCount: null)); - // Act - var result = _sut.ReadPersistedState(); + CreateSut().ReadPersistedState().Should().BeNull(); + } - // Assert - result.Should().BeNull(); + #endregion + + #region ReadPersistedCooldownTimestamp + + [Fact] + public void ReadPersistedCooldownTimestamp_WithValidIsoString_ShouldReturnTimestamp() + { + var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(30); + _haContextMock.SetupEntityState( + WaterReadyEntityId, + BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O"))); + + var result = CreateSut().ReadPersistedCooldownTimestamp(); + + result.Should().Be(cooldownSince); } [Fact] - public void ReadPersistedState_WhenRuntimeIsUnknown_ShouldReturnNull() + public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp() { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "unknown"); - SetupEntityState(SessionCountEntityId, "2"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); + var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero); + _haContextMock.SetupEntityState( + WaterReadyEntityId, + BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z")); - // Act - var result = _sut.ReadPersistedState(); + var result = CreateSut().ReadPersistedCooldownTimestamp(); - // Assert - result.Should().BeNull(); + result.Should().Be(cooldownSince); } [Fact] - public void ReadPersistedState_WhenSessionCountIsUnavailable_ShouldReturnNull() + public void ReadPersistedCooldownTimestamp_WhenEntityDoesNotExist_ShouldReturnNull() { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "3600"); - SetupEntityState(SessionCountEntityId, "unavailable"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); + _haContextMock.SetupEntityState(WaterReadyEntityId, null); - // Act - var result = _sut.ReadPersistedState(); - - // Assert - result.Should().BeNull(); + CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull(); } [Fact] - public void ReadPersistedState_WhenRuntimeEntityDoesNotExist_ShouldReturnNull() + public void ReadPersistedCooldownTimestamp_WhenEntityHasNoAttributes_ShouldReturnNull() { - // Arrange - SetupEntityState(TodayRuntimeEntityId, null); - SetupEntityState(SessionCountEntityId, "2"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); + _haContextMock.SetupEntityState(WaterReadyEntityId, BoilerMonitorTestData.CreateEntityState("yes")); - // Act - var result = _sut.ReadPersistedState(); - - // Assert - result.Should().BeNull(); + CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull(); } [Fact] - public void ReadPersistedState_WhenSessionCountEntityDoesNotExist_ShouldReturnNull() + public void ReadPersistedCooldownTimestamp_WhenAttributeIsMissing_ShouldReturnNull() { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "3600"); - SetupEntityState(SessionCountEntityId, null); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); + _haContextMock.SetupEntityState( + WaterReadyEntityId, + BoilerMonitorTestData.CreateEntityStateWithAttributes( + new Dictionary { ["friendly_name"] = "Boiler water ready" })); - // Act - var result = _sut.ReadPersistedState(); - - // Assert - result.Should().BeNull(); - } - - [Fact] - public void ReadPersistedState_WhenRuntimeIsNonNumeric_ShouldReturnNull() - { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "not_a_number"); - SetupEntityState(SessionCountEntityId, "2"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); - - // Act - var result = _sut.ReadPersistedState(); - - // Assert - result.Should().BeNull(); - } - - [Fact] - public void ReadPersistedState_WhenSessionCountIsNonNumeric_ShouldReturnNull() - { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "3600"); - SetupEntityState(SessionCountEntityId, "abc"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); - - // Act - var result = _sut.ReadPersistedState(); - - // Assert - result.Should().BeNull(); - } - - [Fact] - public void ReadPersistedState_WhenRuntimeIsNegative_ShouldReturnNull() - { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "-100"); - SetupEntityState(SessionCountEntityId, "2"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); - - // Act - var result = _sut.ReadPersistedState(); - - // Assert - result.Should().BeNull(); - } - - [Fact] - public void ReadPersistedState_WhenSessionCountIsNegative_ShouldReturnNull() - { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "3600"); - SetupEntityState(SessionCountEntityId, "-1"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); - - // Act - var result = _sut.ReadPersistedState(); - - // Assert - result.Should().BeNull(); - } - - [Fact] - public void ReadPersistedState_WhenSwitchEntitiesAreNull_ShouldStillReturnWithNullSwitchStates() - { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "1800"); - SetupEntityState(SessionCountEntityId, "1"); - SetupEntityState(SkipPriceCapEntityId, null); - SetupEntityState(BudgetOverrideEntityId, null); - - // Act - var result = _sut.ReadPersistedState(); - - // Assert - result.Should().NotBeNull(); - result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800)); - result.SessionCount.Should().Be(1); - result.SkipPriceCapState.Should().BeNull(); - result.BudgetOverrideState.Should().BeNull(); + CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull(); } [Theory] - [InlineData("")] // empty string - [InlineData(" ")] // whitespace - public void ReadPersistedState_WhenRuntimeIsEmptyOrWhitespace_ShouldReturnNull(string state) + [InlineData(null)] + [InlineData(42)] + [InlineData(true)] + [InlineData("")] + [InlineData(" ")] + [InlineData("not-a-timestamp")] + [InlineData("2026-13-45T99:99:99")] + [InlineData("unavailable")] + public void ReadPersistedCooldownTimestamp_WhenAttributeIsNotAValidTimestamp_ShouldReturnNull(object? cooldownSince) { - // Arrange - SetupEntityState(TodayRuntimeEntityId, state); - SetupEntityState(SessionCountEntityId, "2"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); + _haContextMock.SetupEntityState( + WaterReadyEntityId, + BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince)); - // Act - var result = _sut.ReadPersistedState(); - - // Assert - result.Should().BeNull(); + CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull(); } [Fact] - public void ReadPersistedState_WithDecimalRuntime_ShouldParseCorrectly() + public void ReadPersistedCooldownTimestamp_WhenHaContextThrows_ShouldReturnNull() { - // Arrange - SetupEntityState(TodayRuntimeEntityId, "134.66"); - SetupEntityState(SessionCountEntityId, "1"); - SetupEntityState(SkipPriceCapEntityId, "OFF"); - SetupEntityState(BudgetOverrideEntityId, "OFF"); + _haContextMock.Setup(h => h.GetState(WaterReadyEntityId)) + .Throws(new InvalidOperationException("Home Assistant unavailable")); - // Act - var result = _sut.ReadPersistedState(); + CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull(); + } - // Assert - result.Should().NotBeNull(); - result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(134.66)); - result.SessionCount.Should().Be(1); + #endregion + + #region UpdateEntitiesAsync + + [Theory] + [InlineData(true, "yes")] + [InlineData(false, "no")] + public async Task UpdateEntitiesAsync_ShouldWriteWaterReadyState(bool waterReady, string expectedState) + { + await CreateSut().UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(waterReady: waterReady)); + + _entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, expectedState), Times.Once); + } + + [Fact] + public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting() + { + var context = BoilerMonitorTestData.CreateUpdateContext( + todayRunTime: TimeSpan.FromSeconds(3723.9), + remainingTime: TimeSpan.FromSeconds(42.9), + budgetPercentage: 150.0, + budgetExhausted: true, + sessionCount: 4, + waterReady: true); + + await CreateSut().UpdateEntitiesAsync(context); + + _entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusConfigured), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, "3723"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, "42"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, "100"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, "on"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, "4"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), Times.Exactly(5)); + } + + [Theory] + [InlineData(-0.1, "0")] + [InlineData(0.0, "0")] + [InlineData(49.9, "49")] + [InlineData(99.999, "99")] + [InlineData(100.0, "100")] + [InlineData(100.1, "100")] + [InlineData(1_000.0, "100")] + public async Task UpdateEntitiesAsync_ShouldClampAndTruncateBudgetPercentage( + double budgetPercentage, + string expectedState) + { + await CreateSut().UpdateEntitiesAsync( + BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage)); + + _entityManagerMock.Verify( + em => em.SetEntityState(BudgetPercentageEntityId, expectedState), Times.Once); + } + + [Theory] + [InlineData(-60, "0")] + [InlineData(0, "0")] + [InlineData(1, "1")] + [InlineData(59, "59")] + [InlineData(3600, "3600")] + public async Task UpdateEntitiesAsync_ShouldClampAndTruncateRemainingTime(int seconds, string expectedState) + { + await CreateSut().UpdateEntitiesAsync( + BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds))); + + _entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, expectedState), Times.Once); + } + + [Theory] + [InlineData(0.0, "0")] + [InlineData(0.9, "0")] + [InlineData(59.9, "59")] + [InlineData(60.0, "60")] + [InlineData(86_400.0, "86400")] + public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState) + { + await CreateSut().UpdateEntitiesAsync( + BoilerMonitorTestData.CreateUpdateContext(todayRunTime: TimeSpan.FromSeconds(seconds))); + + _entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once); + } + + [Fact] + public async Task UpdateEntitiesAsync_WhenSwitchStateIsNull_ShouldWriteUnknownWaterReadyAttributes() + { + object? capturedAttributes = null; + _entityManagerMock + .Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny())) + .Callback((_, attributes) => capturedAttributes = attributes) + .Returns(Task.CompletedTask); + + await CreateSut().UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext( + waterReady: false, + boilerSwitchState: null, + boilerPowerWatts: 1234.5)); + + capturedAttributes.Should().NotBeNull(); + var attributes = JsonSerializer.SerializeToElement(capturedAttributes!); + attributes.GetProperty("boiler_switch_state").GetString().Should().Be("unknown"); + attributes.GetProperty("boiler_power_watts").GetDouble().Should().Be(1234.5); + attributes.GetProperty("cooldown_since").ValueKind.Should().Be(JsonValueKind.Null); + attributes.GetProperty("last_updated").GetString().Should().NotBeNullOrEmpty(); + } + + [Fact] + public async Task UpdateEntitiesAsync_WhenCooldownIsActive_ShouldSerializeCooldownTimestamp() + { + var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(15); + object? capturedAttributes = null; + _entityManagerMock + .Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny())) + .Callback((_, attributes) => capturedAttributes = attributes) + .Returns(Task.CompletedTask); + + await CreateSut().UpdateEntitiesAsync( + BoilerMonitorTestData.CreateUpdateContext(cooldownSince: cooldownSince)); + + var attributes = JsonSerializer.SerializeToElement(capturedAttributes!); + attributes.GetProperty("cooldown_since").GetString().Should().Be(cooldownSince.ToString("O")); + } + + #endregion + + #region CreateEntitiesAsync + + [Fact] + public async Task CreateEntitiesAsync_ShouldCreateEveryBoilerMonitorEntityOnce() + { + var createdEntityIds = new List(); + _entityManagerMock + .Setup(em => em.CreateEntityAsync(It.IsAny())) + .Callback(entity => createdEntityIds.Add(entity.EntityId)) + .Returns(Task.CompletedTask); + + await CreateSut().CreateEntitiesAsync(); + + createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems(); + createdEntityIds.Should().Contain(new[] + { + ConfigPowerEntityId, + ConfigSwitchEntityId, + ConfigPollIntervalEntityId, + ConfigHeatingThresholdEntityId, + CleanupButtonEntityId, + WaterReadyEntityId, + TodayRuntimeEntityId, + BudgetExhaustedEntityId, + AutoManagementEntityId + }); + } + + [Fact] + public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldStillAttemptEveryEntity() + { + _entityManagerMock + .Setup(em => em.CreateEntityAsync(It.Is( + entity => entity.EntityId == CleanupButtonEntityId))) + .ThrowsAsync(new InvalidOperationException("MQTT unavailable")); + + var act = () => CreateSut().CreateEntitiesAsync(); + + await act.Should().NotThrowAsync(); + _entityManagerMock.Invocations + .Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync)) + .Should().Be(15); + } + + #endregion + + #region ResetEntitiesAsync + + public static TheoryData ResetEntityStates => new() + { + { StatusEntityId, StatusAwaitingConfiguration }, + { WaterReadyEntityId, "unknown" }, + { SkipPriceCapEntityId, "OFF" }, + { TodayRuntimeEntityId, "0" }, + { RemainingTimeEntityId, "0" }, + { BudgetPercentageEntityId, "0" }, + { BudgetExhaustedEntityId, "off" }, + { SessionCountEntityId, "0" }, + { BudgetOverrideEntityId, "OFF" }, + { AutoManagementEntityId, "ON" } + }; + + [Theory] + [MemberData(nameof(ResetEntityStates))] + public async Task ResetEntitiesAsync_ShouldWriteExpectedDefaultState(string entityId, string expectedState) + { + await CreateSut().ResetEntitiesAsync(); + + _entityManagerMock.Verify(em => em.SetEntityState(entityId, expectedState), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(10)); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), Times.Exactly(5)); + } + + [Fact] + public async Task ResetEntitiesAsync_WhenEntityManagerThrows_ShouldNotThrow() + { + _entityManagerMock + .Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("MQTT unavailable")); + + var act = () => CreateSut().ResetEntitiesAsync(); + + await act.Should().NotThrowAsync(); } #endregion @@ -287,55 +440,111 @@ public class BoilerMonitorEntityServiceTests [Fact] public async Task ResetTransientEntitiesAsync_ShouldResetStatusAndWaterReady() { - // Arrange - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + await CreateSut().ResetTransientEntitiesAsync(); - // Act - await _sut.ResetTransientEntitiesAsync(); - - // Assert _entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusAwaitingConfiguration), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, "unknown"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny()), Times.Once); + } + + public static TheoryData UntouchedByTransientResetEntityIds => new() + { + TodayRuntimeEntityId, + SessionCountEntityId, + BudgetPercentageEntityId, + BudgetExhaustedEntityId, + RemainingTimeEntityId, + SkipPriceCapEntityId, + BudgetOverrideEntityId, + AutoManagementEntityId, + ConfigPowerEntityId, + ConfigSwitchEntityId + }; + + [Theory] + [MemberData(nameof(UntouchedByTransientResetEntityIds))] + public async Task ResetTransientEntitiesAsync_ShouldNotResetPersistentOrSwitchEntities(string entityId) + { + await CreateSut().ResetTransientEntitiesAsync(); + + _entityManagerMock.Verify(em => em.SetEntityState(entityId, It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.SetEntityAttributes(entityId, It.IsAny()), Times.Never); + } + + #endregion + + #region CleanupEntitiesAsync + + [Fact] + public async Task CleanupEntitiesAsync_ShouldRemoveEveryEntityExceptCleanupButton() + { + await CreateSut().CleanupEntitiesAsync(); + + foreach (var entityId in CleanableEntityIds) + { + _entityManagerMock.Verify(em => em.RemoveEntity(entityId), Times.Once); + } + + _entityManagerMock.Verify(em => em.RemoveEntity(CleanupButtonEntityId), Times.Never); + _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Exactly(CleanableEntityIds.Length)); } [Fact] - public async Task ResetTransientEntitiesAsync_ShouldNotResetRuntimeEntities() + public async Task CleanupEntitiesAsync_WhenRemoveFails_ShouldRethrow() { - // Arrange - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + _entityManagerMock + .Setup(em => em.RemoveEntity(It.IsAny())) + .Throws(new InvalidOperationException("MQTT unavailable")); - // Act - await _sut.ResetTransientEntitiesAsync(); + var act = () => CreateSut().CleanupEntitiesAsync(); - // Assert - _entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, It.IsAny()), Times.Never); - _entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, It.IsAny()), Times.Never); - _entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, It.IsAny()), Times.Never); - _entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, It.IsAny()), Times.Never); - _entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, It.IsAny()), Times.Never); + await act.Should().ThrowAsync(); } + #endregion + + #region SetStatusAsync and cancellation + [Fact] - public async Task ResetTransientEntitiesAsync_ShouldNotResetSwitchEntities() + public async Task SetStatusAsync_ShouldWriteStatusEntity() { - // Arrange - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + await CreateSut().SetStatusAsync(StatusConfigured); - // Act - await _sut.ResetTransientEntitiesAsync(); + _entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusConfigured), Times.Once); + } - // Assert - _entityManagerMock.Verify(em => em.SetEntityState(SkipPriceCapEntityId, It.IsAny()), Times.Never); - _entityManagerMock.Verify(em => em.SetEntityState(BudgetOverrideEntityId, It.IsAny()), Times.Never); + public enum CancelableOperation + { + CreateEntities, + ResetEntities, + UpdateEntities, + ResetTransientEntities, + CleanupEntities + } + + [Theory] + [InlineData(CancelableOperation.CreateEntities)] + [InlineData(CancelableOperation.ResetEntities)] + [InlineData(CancelableOperation.UpdateEntities)] + [InlineData(CancelableOperation.ResetTransientEntities)] + [InlineData(CancelableOperation.CleanupEntities)] + public async Task Operation_WhenCancellationIsAlreadyRequested_ShouldThrowAndNotTouchEntityManager( + CancelableOperation operation) + { + var canceledToken = new CancellationToken(canceled: true); + var sut = CreateSut(); + Func act = operation switch + { + CancelableOperation.CreateEntities => () => sut.CreateEntitiesAsync(canceledToken), + CancelableOperation.ResetEntities => () => sut.ResetEntitiesAsync(canceledToken), + CancelableOperation.UpdateEntities => () => sut.UpdateEntitiesAsync( + BoilerMonitorTestData.CreateUpdateContext(), canceledToken), + CancelableOperation.ResetTransientEntities => () => sut.ResetTransientEntitiesAsync(canceledToken), + _ => () => sut.CleanupEntitiesAsync(canceledToken) + }; + + await act.Should().ThrowAsync(); + _entityManagerMock.Invocations.Should().BeEmpty(); } #endregion diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs index 853e5e2..1b49c61 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs @@ -13,17 +13,47 @@ public class BoilerMonitorOptionsTests options.Enabled.Should().BeTrue(); } + [Fact] + public void Defaults_ShouldHaveCleanupEntitiesOnStartupTrue() + { + var options = new BoilerMonitorOptions(); + + options.CleanupEntitiesOnStartup.Should().BeTrue(); + } + [Fact] public void SectionName_ShouldBeBoilerMonitor() { BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor"); } - [Fact] - public void Enabled_WhenSetToFalse_ShouldReturnFalse() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Enabled_WhenSet_ShouldReturnConfiguredValue(bool enabled) { - var options = new BoilerMonitorOptions { Enabled = false }; + var options = BoilerMonitorTestData.CreateOptions(enabled: enabled); + + options.Enabled.Should().Be(enabled); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void CleanupEntitiesOnStartup_WhenSet_ShouldReturnConfiguredValue(bool cleanupEntitiesOnStartup) + { + var options = BoilerMonitorTestData.CreateOptions(cleanupEntitiesOnStartup: cleanupEntitiesOnStartup); + + options.CleanupEntitiesOnStartup.Should().Be(cleanupEntitiesOnStartup); + } + + [Fact] + public void Options_WhenBothFlagsDisabled_ShouldPreserveEachValueIndependently() + { + var options = BoilerMonitorTestData.CreateOptions(enabled: false, cleanupEntitiesOnStartup: false); options.Enabled.Should().BeFalse(); + options.CleanupEntitiesOnStartup.Should().BeFalse(); + BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor"); } } diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs new file mode 100644 index 0000000..945aeaf --- /dev/null +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs @@ -0,0 +1,271 @@ +using System.Text.Json; +using BoilerMonitor.Models; +using BoilerMonitorManager.Models; +using Microsoft.Extensions.Time.Testing; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using static BoilerMonitor.Models.BoilerMonitorConsts; + +namespace BoilerMonitor.Manager.Tests; + +/// +/// Shared, deterministic fixtures used by the BoilerMonitor tests: config/options builders, +/// entity-state sets, parse samples and a fixed clock. Keeping them here avoids copy-pasted +/// setup and makes every timestamp/DST assertion independent of the real clock. +/// +internal static class BoilerMonitorTestData +{ + public const string PowerEntityId = "sensor.sonoff_1002230e32_power"; + public const string SwitchEntityId = "switch.sonoff_1002230e32"; + + /// Fixed "now" (UTC) used by every time based test. + public static readonly DateTimeOffset BaseTime = new(2026, 3, 31, 12, 0, 0, TimeSpan.Zero); + + public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null) => + new(utcNow ?? BaseTime); + + public static BoilerMonitorConfig CreateConfig( + string? boilerPowerEntityId = PowerEntityId, + string? boilerSwitchEntityId = SwitchEntityId, + int? pollIntervalSeconds = DefaultPollIntervalSeconds, + double? heatingPowerThresholdWatts = DefaultHeatingPowerThresholdWatts) => + new() + { + BoilerPowerEntityId = boilerPowerEntityId, + BoilerSwitchEntityId = boilerSwitchEntityId, + PollIntervalSeconds = pollIntervalSeconds, + HeatingPowerThresholdWatts = heatingPowerThresholdWatts + }; + + public static BoilerMonitorOptions CreateOptions( + bool enabled = true, + bool cleanupEntitiesOnStartup = true) => + new() + { + Enabled = enabled, + CleanupEntitiesOnStartup = cleanupEntitiesOnStartup + }; + + public static PersistedBoilerState CreatePersistedState( + TimeSpan? accumulatedRunTime = null, + int sessionCount = 3, + string? skipPriceCapState = "ON", + string? budgetOverrideState = "OFF") => + new() + { + AccumulatedRunTime = accumulatedRunTime ?? TimeSpan.FromHours(2), + SessionCount = sessionCount, + SkipPriceCapState = skipPriceCapState, + BudgetOverrideState = budgetOverrideState + }; + + public static BoilerMonitorUpdateContext CreateUpdateContext( + TimeSpan? todayRunTime = null, + TimeSpan? remainingTime = null, + double budgetPercentage = 50.0, + bool budgetExhausted = false, + int sessionCount = 1, + double budgetHours = 2.0, + bool waterReady = false, + string? boilerSwitchState = "on", + double? boilerPowerWatts = 0.0, + DateTimeOffset? cooldownSince = null, + bool isNowCheap = true) => + new() + { + TodayRunTime = todayRunTime ?? TimeSpan.FromHours(1), + RemainingTime = remainingTime ?? TimeSpan.FromHours(1), + BudgetPercentage = budgetPercentage, + BudgetExhausted = budgetExhausted, + SessionCount = sessionCount, + BudgetHours = budgetHours, + IsCurrentlyHeating = false, + WaterReady = waterReady, + BoilerSwitchState = boilerSwitchState, + BoilerPowerWatts = boilerPowerWatts, + CooldownSince = cooldownSince, + IsNowCheap = isNowCheap, + NextCheapIntervalStart = null + }; + + /// + /// The four entity states ReadPersistedState reads, with valid defaults. + /// A null value means the entity does not exist in Home Assistant. + /// + public static Dictionary CreatePersistedEntityStates( + string? todayRuntime = "7200", + string? sessionCount = "3", + string? skipPriceCap = "OFF", + string? budgetOverride = "OFF") => + new() + { + [TodayRuntimeEntityId] = todayRuntime, + [SessionCountEntityId] = sessionCount, + [SkipPriceCapEntityId] = skipPriceCap, + [BudgetOverrideEntityId] = budgetOverride + }; + + public static EntityState CreateEntityState(string state) => new() { State = state }; + + public static EntityState CreateEntityStateWithAttributes(IReadOnlyDictionary attributes) => + new() { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) }; + + public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince) => + CreateEntityStateWithAttributes(new Dictionary { ["cooldown_since"] = cooldownSince }); + + public static void SetupEntityStates( + this Mock haContextMock, + IReadOnlyDictionary states) + { + foreach (var (entityId, state) in states) + { + var entityState = state is null ? null : CreateEntityState(state); + haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState); + } + } + + public static void SetupEntityState( + this Mock haContextMock, + string entityId, + EntityState? entityState) => + haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState); + + /// + /// Entity-state samples for the today-runtime sensor: valid values with the expected + /// , plus unavailable/negative/overflow values that must be rejected. + /// + public static IEnumerable RuntimeStateSamples() + { + yield return ["7200", TimeSpan.FromHours(2)]; + yield return ["0", TimeSpan.Zero]; + yield return ["134.66", TimeSpan.FromSeconds(134.66)]; + yield return ["1E3", TimeSpan.FromSeconds(1000)]; + yield return ["0.001", TimeSpan.FromSeconds(0.001)]; + yield return [" 60 ", TimeSpan.FromSeconds(60)]; + yield return ["86400", TimeSpan.FromDays(1)]; + yield return ["1e9", TimeSpan.FromSeconds(1e9)]; + + yield return [(string?)null, (TimeSpan?)null]; + yield return ["", (TimeSpan?)null]; + yield return [" ", (TimeSpan?)null]; + yield return ["\t", (TimeSpan?)null]; + yield return ["unavailable", (TimeSpan?)null]; + yield return ["unknown", (TimeSpan?)null]; + yield return ["Unavailable", (TimeSpan?)null]; + yield return ["not_a_number", (TimeSpan?)null]; + yield return ["NaN", (TimeSpan?)null]; + yield return ["Infinity", (TimeSpan?)null]; + yield return ["1e308", (TimeSpan?)null]; + yield return ["-1", (TimeSpan?)null]; + yield return ["-0.001", (TimeSpan?)null]; + } + + /// + /// Entity-state samples for the session-count sensor, including the int boundaries. + /// + public static IEnumerable SessionCountStateSamples() + { + yield return ["0", 0]; + yield return ["3", 3]; + yield return [" 2 ", 2]; + yield return ["+4", 4]; + yield return ["2147483647", int.MaxValue]; + + yield return [(string?)null, (int?)null]; + yield return ["", (int?)null]; + yield return [" ", (int?)null]; + yield return ["\t", (int?)null]; + yield return ["unavailable", (int?)null]; + yield return ["unknown", (int?)null]; + yield return ["abc", (int?)null]; + yield return ["1.5", (int?)null]; + yield return ["-1", (int?)null]; + yield return ["2147483648", (int?)null]; + yield return ["1e3", (int?)null]; + } + + /// + /// Water-ready detection samples around the heating threshold, including negative, + /// zero, exact-boundary, huge and NaN readings. + /// + public static IEnumerable 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]; + } + + /// + /// Elapsed-time sweep showing that the water-ready cooldown never expires on its own. + /// + public static IEnumerable GeneratedElapsedTimes() + { + foreach (var hours in new[] { 1, 2, 6, 12, 23, 24, 25, 48, 168 }) + { + yield return [TimeSpan.FromHours(hours)]; + } + } + + /// + /// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end + /// timestamps carrying non-zero offsets. + /// + public static IEnumerable CooldownRestoreSamples() + { + yield return ["30 minutes ago", BaseTime, BaseTime - TimeSpan.FromMinutes(30), true]; + yield return ["5 hours ago", BaseTime, BaseTime - TimeSpan.FromHours(5), true]; + yield return ["exactly at today's UTC midnight", BaseTime, TodayMidnight(), true]; + yield return ["one tick after today's UTC midnight", BaseTime, TodayMidnight().AddTicks(1), true]; + yield return ["one tick before today's UTC midnight", BaseTime, TodayMidnight().AddTicks(-1), false]; + yield return ["one second before today's UTC midnight", BaseTime, TodayMidnight().AddSeconds(-1), false]; + yield return ["yesterday same time", BaseTime, BaseTime.AddDays(-1), false]; + yield return ["two days ago", BaseTime, BaseTime.AddDays(-2), false]; + yield return ["future timestamp", BaseTime, BaseTime.AddHours(1), true]; + yield return ["maximum timestamp", BaseTime, DateTimeOffset.MaxValue, true]; + + // Europe DST starts 2026-03-29 02:00 CET → 03:00 CEST. + // now = 03:30+02:00 = 01:30Z, so UTC midnight is 2026-03-29T00:00Z. + yield return + [ + "DST spring-forward, same UTC day", + new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)), + new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)), + true + ]; + yield return + [ + "DST spring-forward, previous UTC day", + new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)), + new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)), + false + ]; + + // Europe DST ends 2026-10-25 03:00 CEST → 02:00 CET. The 02:30 wall-clock hour occurs twice. + // now = 03:30+01:00 = 02:30Z, timestamp 02:30+02:00 = 00:30Z is still "today" in UTC. + yield return + [ + "DST fall-back, ambiguous local hour", + new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)), + new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)), + true + ]; + + yield return + [ + "crossing midnight between restore and now", + new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero), + new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero), + false + ]; + } + + private static DateTimeOffset TodayMidnight() => + new(BaseTime.Date, TimeSpan.Zero); +} diff --git a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs index bb4d06e..1ffb881 100644 --- a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs @@ -11,15 +11,10 @@ public class WaterReadyServiceTests { private const double Threshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts; private const double HighPowerWatts = 2150.0; + private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired; - private readonly Mock> _loggerMock; - private readonly FakeTimeProvider _timeProvider; - - public WaterReadyServiceTests() - { - _loggerMock = new Mock>(); - _timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); - } + private readonly Mock> _loggerMock = new(); + private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider(); private WaterReadyService CreateSut() => new(_loggerMock.Object, _timeProvider); @@ -30,26 +25,36 @@ public class WaterReadyServiceTests return sut; } - private static bool TriggerWaterReady(WaterReadyService sut, double powerWatts = 0.0) + private static bool FeedReadings( + WaterReadyService sut, + int count, + string? switchState = "on", + double? powerWatts = 0.0, + double heatingThresholdWatts = Threshold) { var result = false; - for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++) + for (var i = 0; i < count; i++) { - result = sut.IsWaterReady("on", powerWatts, Threshold); + result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts); } + return result; } #region Heating observation prerequisite - [Fact] - public void IsWaterReady_SwitchOnLowPowerButNeverObservedHeating_ShouldReturnFalse() + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(10)] + public void IsWaterReady_WhenHeatingWasNeverObserved_ShouldAlwaysReturnFalse(int readingCount) { var sut = CreateSut(); - var result = sut.IsWaterReady("on", 0.0, Threshold); + var result = FeedReadings(sut, readingCount); result.Should().BeFalse(); + sut.IsInCooldown.Should().BeFalse(); } [Fact] @@ -57,7 +62,7 @@ public class WaterReadyServiceTests { var sut = CreateSutWithHeatingObserved(); - var result = TriggerWaterReady(sut); + var result = FeedReadings(sut, RequiredReadings); result.Should().BeTrue(); } @@ -66,11 +71,21 @@ public class WaterReadyServiceTests public void RecordHeatingObserved_ShouldEnableDetection() { var sut = CreateSut(); + sut.RecordHeatingObserved(); - var result = TriggerWaterReady(sut); + FeedReadings(sut, RequiredReadings).Should().BeTrue(); + } - result.Should().BeTrue(); + [Fact] + public void RecordHeatingObserved_WhenCalledRepeatedly_ShouldStayEnabled() + { + var sut = CreateSut(); + + sut.RecordHeatingObserved(); + sut.RecordHeatingObserved(); + + FeedReadings(sut, RequiredReadings).Should().BeTrue(); } [Fact] @@ -79,7 +94,7 @@ public class WaterReadyServiceTests var sut = CreateSutWithHeatingObserved(); sut.NotifyTurnedOn(); - var result = sut.IsWaterReady("on", 0.0, Threshold); + var result = FeedReadings(sut, 10); result.Should().BeFalse("heating observation was reset by NotifyTurnedOn"); } @@ -91,20 +106,32 @@ public class WaterReadyServiceTests sut.NotifyTurnedOn(); sut.RecordHeatingObserved(); - var result = TriggerWaterReady(sut); + var result = FeedReadings(sut, RequiredReadings); result.Should().BeTrue(); } + [Fact] + public void ResetCooldown_ShouldKeepHeatingObservationEnabled() + { + var sut = CreateSutWithHeatingObserved(); + FeedReadings(sut, RequiredReadings).Should().BeTrue(); + + sut.ResetCooldown(); + + FeedReadings(sut, RequiredReadings).Should().BeTrue( + "ResetCooldown clears the cooldown and counter, not the heating observation"); + } + [Fact] public void IsWaterReady_AfterResetAndReObservedHeating_ShouldTriggerAgain() { var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); + FeedReadings(sut, RequiredReadings); sut.ResetCooldown(); sut.RecordHeatingObserved(); - var result = TriggerWaterReady(sut); + var result = FeedReadings(sut, RequiredReadings); result.Should().BeTrue("detection should work again after reset + new heating observation"); } @@ -113,112 +140,99 @@ public class WaterReadyServiceTests #region Debouncing (consecutive readings) - [Fact] - public void IsWaterReady_SingleBelowThresholdReading_ShouldReturnFalse() + [Theory] + [InlineData(1, false)] + [InlineData(2, true)] + [InlineData(3, true)] + [InlineData(10, true)] + public void IsWaterReady_ShouldRequireConsecutiveBelowThresholdReadings(int readingCount, bool expected) { var sut = CreateSutWithHeatingObserved(); - var result = sut.IsWaterReady("on", 0.0, Threshold); + var result = FeedReadings(sut, readingCount); - result.Should().BeFalse("only 1 consecutive reading, need {0}", - BoilerMonitorConsts.ConsecutiveReadingsRequired); + result.Should().Be(expected); } - [Fact] - public void IsWaterReady_ConsecutiveBelowThresholdReadings_ShouldReturnTrue() + [Theory] + [InlineData(HighPowerWatts)] + [InlineData(Threshold)] + [InlineData(double.MaxValue)] + public void IsWaterReady_WhenReadingIsAtOrAboveThreshold_ShouldResetConsecutiveCount(double powerWatts) { var sut = CreateSutWithHeatingObserved(); + FeedReadings(sut, RequiredReadings - 1).Should().BeFalse(); - var result = TriggerWaterReady(sut); + sut.IsWaterReady("on", powerWatts, Threshold).Should().BeFalse("power is not below the threshold"); - result.Should().BeTrue(); + FeedReadings(sut, 1).Should().BeFalse("the counter was reset by the above-threshold reading"); + FeedReadings(sut, RequiredReadings - 1).Should().BeTrue(); } - [Fact] - public void IsWaterReady_BelowThresholdResetByAboveThreshold_ShouldRequireConsecutiveAgain() + [Theory] + [InlineData(0)] + [InlineData(1)] + public void IsWaterReady_NotifyTurnedOn_ShouldResetConsecutiveCount(int belowThresholdBeforeTurnOn) { var sut = CreateSutWithHeatingObserved(); + FeedReadings(sut, belowThresholdBeforeTurnOn); - sut.IsWaterReady("on", 0.0, Threshold); - sut.IsWaterReady("on", HighPowerWatts, Threshold); - var result = sut.IsWaterReady("on", 0.0, Threshold); - - result.Should().BeFalse("counter was reset by above-threshold reading"); - } - - [Fact] - public void IsWaterReady_NotifyTurnedOn_ShouldResetConsecutiveCount() - { - var sut = CreateSutWithHeatingObserved(); - - sut.IsWaterReady("on", 0.0, Threshold); sut.NotifyTurnedOn(); sut.RecordHeatingObserved(); - var result = sut.IsWaterReady("on", 0.0, Threshold); - result.Should().BeFalse("NotifyTurnedOn reset the consecutive counter"); + FeedReadings(sut, RequiredReadings - 1).Should().BeFalse("NotifyTurnedOn reset the consecutive counter"); + FeedReadings(sut, 1).Should().BeTrue(); + } + + [Fact] + public void IsWaterReady_InterleavedReadings_ShouldOnlyTriggerAfterLastConsecutiveLowReading() + { + var sut = CreateSutWithHeatingObserved(); + + var results = new[] + { + sut.IsWaterReady("on", 0.0, Threshold), + sut.IsWaterReady("on", HighPowerWatts, Threshold), + sut.IsWaterReady("on", 0.0, Threshold), + sut.IsWaterReady("on", 0.0, Threshold) + }; + + results.Should().Equal(false, false, false, true); } #endregion #region Basic state checks - [Fact] - public void IsWaterReady_SwitchOnAndPowerAtThreshold_ShouldReturnFalse() + [Theory] + [InlineData("off")] + [InlineData("OFF")] + [InlineData(" off")] + [InlineData("on ")] + [InlineData("unknown")] + [InlineData("unavailable")] + [InlineData("yes")] + [InlineData("1")] + public void IsWaterReady_WhenSwitchIsNotOn_ShouldReturnFalse(string switchState) { var sut = CreateSutWithHeatingObserved(); - var result = sut.IsWaterReady("on", Threshold, Threshold); + var result = FeedReadings(sut, 10, switchState); result.Should().BeFalse(); } - [Fact] - public void IsWaterReady_SwitchOnAndHighPower_ShouldReturnFalse() + [Theory] + [InlineData("on", null)] + [InlineData(null, 0.0)] + [InlineData(null, null)] + [InlineData("", null)] + [InlineData("", 0.0)] + public void IsWaterReady_WhenSwitchStateOrPowerIsNull_ShouldReturnFalse(string? switchState, double? powerWatts) { var sut = CreateSutWithHeatingObserved(); - var result = sut.IsWaterReady("on", HighPowerWatts, Threshold); - - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_SwitchOff_ShouldReturnFalse() - { - var sut = CreateSutWithHeatingObserved(); - - var result = sut.IsWaterReady("off", 0.0, Threshold); - - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_NullSwitchState_ShouldReturnFalse() - { - var sut = CreateSutWithHeatingObserved(); - - var result = sut.IsWaterReady(null, 0.0, Threshold); - - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_NullPowerWatts_ShouldReturnFalse() - { - var sut = CreateSutWithHeatingObserved(); - - var result = sut.IsWaterReady("on", null, Threshold); - - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_BothNull_ShouldReturnFalse() - { - var sut = CreateSut(); - - var result = sut.IsWaterReady(null, null, Threshold); + var result = FeedReadings(sut, 10, switchState, powerWatts); result.Should().BeFalse(); } @@ -226,33 +240,49 @@ public class WaterReadyServiceTests [Theory] [InlineData("ON")] [InlineData("On")] - [InlineData("on")] + [InlineData("oN")] public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState) { var sut = CreateSutWithHeatingObserved(); - var result = false; - for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++) - { - result = sut.IsWaterReady(switchState, 0.0, Threshold); - } + var result = FeedReadings(sut, RequiredReadings, switchState); result.Should().BeTrue(); } + [Theory] + [MemberData(nameof(BoilerMonitorTestData.PowerReadingSamples), MemberType = typeof(BoilerMonitorTestData))] + public void IsWaterReady_PowerAroundThreshold_ShouldFollowThresholdRule( + string scenario, + double powerWatts, + bool expectedBelowThreshold) + { + var sut = CreateSutWithHeatingObserved(); + + var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts); + + result.Should().Be( + expectedBelowThreshold, + $"{scenario}: readings below {Threshold}W are counted as 'not heating'"); + } + [Theory] [InlineData(9.9, 10.0, true)] [InlineData(10.0, 10.0, false)] [InlineData(10.1, 10.0, false)] - public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(double powerWatts, double threshold, bool expected) + [InlineData(0.0, 0.0, false)] + [InlineData(-10.0, -5.0, true)] + [InlineData(-0.001, 0.0, true)] + [InlineData(0.0, -5.0, false)] + [InlineData(10.0, 0.0, false)] + public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue( + double powerWatts, + double heatingThresholdWatts, + bool expected) { var sut = CreateSutWithHeatingObserved(); - var result = false; - for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++) - { - result = sut.IsWaterReady("on", powerWatts, threshold); - } + var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts, heatingThresholdWatts: heatingThresholdWatts); result.Should().Be(expected); } @@ -261,60 +291,37 @@ public class WaterReadyServiceTests #region Cooldown period - [Fact] - public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfSwitchState() + [Theory] + [InlineData("off", 0.0)] + [InlineData("off", null)] + [InlineData(null, 0.0)] + [InlineData(null, null)] + [InlineData("on", HighPowerWatts)] + [InlineData("unknown", 12.0)] + public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfInputs(string? switchState, double? powerWatts) { var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); + FeedReadings(sut, RequiredReadings).Should().BeTrue(); - var result = sut.IsWaterReady("off", 0.0, Threshold); + var result = sut.IsWaterReady(switchState, powerWatts, Threshold); result.Should().BeTrue(); } - [Fact] - public void IsWaterReady_DuringCooldown_ShouldReturnTrueEvenWithNullState() + [Theory] + [MemberData(nameof(BoilerMonitorTestData.GeneratedElapsedTimes), MemberType = typeof(BoilerMonitorTestData))] + public void IsWaterReady_CooldownDoesNotExpireByTime_ShouldStayActive(TimeSpan elapsed) { var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); + FeedReadings(sut, RequiredReadings); + var triggeredAt = sut.WaterReadySince; - var result = sut.IsWaterReady(null, null, Threshold); - - result.Should().BeTrue(); - } - - [Fact] - public void IsWaterReady_CooldownDoesNotExpireByTime_ShouldStayActiveAfterHours() - { - var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); - _timeProvider.Advance(TimeSpan.FromHours(12)); - - var result = sut.IsWaterReady("off", 0.0, Threshold); - - result.Should().BeTrue("cooldown only clears via explicit ResetCooldown, not by elapsed time"); - } - - [Fact] - public void IsWaterReady_CooldownClearedOnlyByExplicitReset_ShouldResumeAfterReset() - { - var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); - _timeProvider.Advance(TimeSpan.FromHours(5)); - sut.IsInCooldown.Should().BeTrue(); - - sut.ResetCooldown(); - - sut.IsWaterReady("off", 0.0, Threshold).Should().BeFalse(); - } - - [Fact] - public void IsInCooldown_WhenCooldownActive_ShouldReturnTrue() - { - var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); + _timeProvider.Advance(elapsed); sut.IsInCooldown.Should().BeTrue(); + sut.IsWaterReady("off", 0.0, Threshold).Should().BeTrue( + "cooldown only clears via explicit ResetCooldown, not by elapsed time"); + sut.WaterReadySince.Should().Be(triggeredAt); } [Fact] @@ -326,67 +333,65 @@ public class WaterReadyServiceTests } [Fact] - public void IsInCooldown_DoesNotExpireByTime_ShouldRemainTrueAfterHours() + public void ResetCooldown_ShouldClearActiveCooldownAndAllowDetectionToResume() { var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); - _timeProvider.Advance(TimeSpan.FromHours(8)); - - sut.IsInCooldown.Should().BeTrue(); - } - - [Fact] - public void ResetCooldown_ShouldClearActiveCooldown() - { - var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); + FeedReadings(sut, RequiredReadings); sut.IsInCooldown.Should().BeTrue(); sut.ResetCooldown(); sut.IsInCooldown.Should().BeFalse(); + sut.WaterReadySince.Should().BeNull(); + sut.IsWaterReady("off", 0.0, Threshold).Should().BeFalse(); + FeedReadings(sut, RequiredReadings - 1).Should().BeFalse(); + FeedReadings(sut, 1).Should().BeTrue(); } [Fact] - public void ResetCooldown_ShouldAllowNormalDetectionToResume() + public void ResetCooldown_WhenNoCooldownIsActive_ShouldBeANoOp() { - var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); + var sut = CreateSut(); + sut.ResetCooldown(); - var result = sut.IsWaterReady("off", 0.0, Threshold); - - result.Should().BeFalse(); + sut.IsInCooldown.Should().BeFalse(); + sut.WaterReadySince.Should().BeNull(); + FeedReadings(sut, 10).Should().BeFalse("heating was never observed"); } [Fact] public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp() { var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); + FeedReadings(sut, RequiredReadings); var originalTimestamp = sut.WaterReadySince; _timeProvider.Advance(TimeSpan.FromHours(2)); - sut.IsWaterReady("on", 0.0, Threshold); + sut.IsWaterReady("on", 0.0, Threshold).Should().BeTrue(); sut.WaterReadySince.Should().Be(originalTimestamp); } - [Fact] - public void IsWaterReady_HighPowerDoesNotTriggerCooldown_ShouldReturnFalse() + [Theory] + [InlineData(Threshold)] + [InlineData(HighPowerWatts)] + [InlineData(double.MaxValue)] + public void IsWaterReady_PowerAtOrAboveThreshold_ShouldNotStartCooldown(double powerWatts) { var sut = CreateSutWithHeatingObserved(); - sut.IsWaterReady("on", HighPowerWatts, Threshold); + FeedReadings(sut, RequiredReadings, powerWatts: powerWatts).Should().BeFalse(); sut.IsInCooldown.Should().BeFalse(); + sut.WaterReadySince.Should().BeNull(); } [Fact] public void NotifyTurnedOn_DuringActiveCooldown_ShouldNotClearCooldown() { var sut = CreateSutWithHeatingObserved(); - TriggerWaterReady(sut); + FeedReadings(sut, RequiredReadings); sut.NotifyTurnedOn(); @@ -397,60 +402,22 @@ public class WaterReadyServiceTests #region Cooldown persistence - [Fact] - public void RestoreCooldownState_ShouldResumeActiveCooldown() + [Theory] + [MemberData(nameof(BoilerMonitorTestData.CooldownRestoreSamples), MemberType = typeof(BoilerMonitorTestData))] + public void RestoreCooldownState_ShouldRestoreOnlyTimestampsFromTodayUtc( + string scenario, + DateTimeOffset now, + DateTimeOffset cooldownSince, + bool expectedRestored) { - var sut = CreateSut(); - var cooldownStart = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(30); + var timeProvider = BoilerMonitorTestData.CreateTimeProvider(now); + var sut = new WaterReadyService(_loggerMock.Object, timeProvider); - sut.RestoreCooldownState(cooldownStart); + sut.RestoreCooldownState(cooldownSince); - sut.IsInCooldown.Should().BeTrue(); - sut.IsWaterReady("off", 0.0, Threshold).Should().BeTrue(); - } - - [Fact] - public void RestoreCooldownState_WithYesterdayTimestamp_ShouldNotActivateCooldown() - { - var sut = CreateSut(); - var yesterday = _timeProvider.GetUtcNow().AddDays(-1); - - sut.RestoreCooldownState(yesterday); - - sut.IsInCooldown.Should().BeFalse(); - } - - [Fact] - public void RestoreCooldownState_WithTodayTimestamp_ShouldRestoreCooldown() - { - var sut = CreateSut(); - var earlierToday = _timeProvider.GetUtcNow() - TimeSpan.FromHours(5); - - sut.RestoreCooldownState(earlierToday); - - sut.IsInCooldown.Should().BeTrue(); - } - - [Fact] - public void RestoreCooldownState_WithExactlyMidnightTimestamp_ShouldRestoreCooldown() - { - var sut = CreateSut(); - var todayMidnight = new DateTimeOffset(_timeProvider.GetUtcNow().Date, TimeSpan.Zero); - - sut.RestoreCooldownState(todayMidnight); - - sut.IsInCooldown.Should().BeTrue("timestamp at today's midnight is not before today"); - } - - [Fact] - public void RestoreCooldownState_ShouldPreserveOriginalTimestamp() - { - var sut = CreateSut(); - var cooldownStart = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(30); - - sut.RestoreCooldownState(cooldownStart); - - sut.WaterReadySince.Should().Be(cooldownStart); + sut.IsInCooldown.Should().Be(expectedRestored, scenario); + sut.WaterReadySince.Should().Be(expectedRestored ? cooldownSince : null, scenario); + sut.IsWaterReady("off", 0.0, Threshold).Should().Be(expectedRestored, scenario); } [Fact] @@ -459,7 +426,7 @@ public class WaterReadyServiceTests var sut = CreateSutWithHeatingObserved(); var beforeTrigger = _timeProvider.GetUtcNow(); - TriggerWaterReady(sut); + FeedReadings(sut, RequiredReadings).Should().BeTrue(); sut.WaterReadySince.Should().Be(beforeTrigger); } diff --git a/BoilerMonitor.Manager/BoilerConfigReader.cs b/BoilerMonitor.Manager/BoilerConfigReader.cs index c12279e..d8b2aea 100644 --- a/BoilerMonitor.Manager/BoilerConfigReader.cs +++ b/BoilerMonitor.Manager/BoilerConfigReader.cs @@ -29,7 +29,7 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger - - - + + + diff --git a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs index 9eb8845..163c0a1 100644 --- a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs @@ -384,7 +384,7 @@ public sealed class BoilerMonitorEntityService( { boiler_switch_state = ctx.BoilerSwitchState ?? "unknown", boiler_power_watts = ctx.BoilerPowerWatts, - cooldown_since = ctx.CooldownSince?.ToString("O"), + cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture), friendly_name = "Boiler water ready", last_updated = timestamp }).ConfigureAwait(false); diff --git a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs index 39f3c29..8e5019d 100644 --- a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs +++ b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs @@ -23,7 +23,8 @@ public static class BoilerMonitorServiceRegistration .AddNetDaemonApp() .AddSingleton() .AddTransient() - .AddSingleton(); + .AddSingleton() + .AddSingleton(); return services; } diff --git a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs new file mode 100644 index 0000000..1f70a79 --- /dev/null +++ b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs @@ -0,0 +1,32 @@ +using BoilerMonitorManager.Interface; +using BoilerMonitorManager.Models; + +namespace BoilerMonitorManager; + +public class BoilerRunTimeTracker : IBoilerRunTimeTracker +{ + public void RecordPollResult(bool isHeating, TimeSpan pollInterval) + { + + } + + public RunTimeSnapshot GetSnapshot() + { + return new RunTimeSnapshot + { + AccumulatedRunTime = TimeSpan.Zero, + SessionCount = 0, + IsInSession = false + }; + } + + public void Reset() + { + + } + + public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount) + { + + } +} \ No newline at end of file diff --git a/BoilerMonitor.Models/BoilerMonitor.Models.csproj b/BoilerMonitor.Models/BoilerMonitor.Models.csproj index cd6e963..119fc66 100644 --- a/BoilerMonitor.Models/BoilerMonitor.Models.csproj +++ b/BoilerMonitor.Models/BoilerMonitor.Models.csproj @@ -12,7 +12,7 @@ - + diff --git a/HomeAssistant.Entities/EntityManager.cs b/HomeAssistant.Entities/EntityManager.cs index 0f666ea..e2bee8a 100644 --- a/HomeAssistant.Entities/EntityManager.cs +++ b/HomeAssistant.Entities/EntityManager.cs @@ -1,16 +1,30 @@ using HomeAssistant.Entities.Interfaces; using HomeAssistant.Models; +using HomeAssistantGenerated; +using Microsoft.Extensions.Options; using NetDaemon.Extensions.MqttEntityManager; +using NetDaemon.HassModel; namespace HomeAssistant.Entities; -public class EntityManager(IMqttEntityManager entityManager) : IEntityManager +public class EntityManager( + IMqttEntityManager entityManager, + IHaContext haContext, + IOptions mqttConfiguration) : IEntityManager { + /// + /// Every topic owned by an entity created through : + /// state, attributes, availability, set and config. + /// The discovery config topic comes last: an empty retained payload on it is what removes the + /// entity from Home Assistant. + /// + private static readonly string[] CleanupTopicSuffixes = ["state", "attributes", "availability", "set", "config"]; + public async Task CreateEntitiesAsync(ICollection entities) { await Task.WhenAll(entities.Select(CreateEntityAsync)); } - + public async Task CreateEntityAsync(EntityCreateModel createModel) { if (createModel.EntityId != null) @@ -23,14 +37,53 @@ public class EntityManager(IMqttEntityManager entityManager) : IEntityManager { await entityManager.SetStateAsync(entityId, state); } - + public async Task SetEntityAttributes(string entityId, object attributes) { await entityManager.SetAttributesAsync(entityId, attributes); } - public async Task RemoveEntity(string entityId) + /// + /// Removes the entity from Home Assistant and clears every retained MQTT message it owns at the broker. + /// + /// publishes the empty discovery payload without the + /// retain flag, so Home Assistant forgets the entity but the broker keeps the retained config and + /// re-discovers the entity after a Home Assistant restart or MQTT reload. Publishing an empty + /// retained payload through Home Assistant's mqtt.publish service clears the retained + /// messages and removes the entity for good. + /// + /// + public Task RemoveEntity(string entityId) { - await entityManager.RemoveAsync(entityId); + var rootTopic = BuildRootTopic(entityId, mqttConfiguration.Value.DiscoveryPrefix); + + foreach (var suffix in CleanupTopicSuffixes) + { + haContext.CallService("mqtt", "publish", null, new MqttPublishParameters + { + Topic = $"{rootTopic}/{suffix}", + Payload = string.Empty, + Retain = true + }); + } + + // IHaContext.CallService is fire-and-forget; the calls are queued in order on the HA websocket. + return Task.CompletedTask; } -} \ No newline at end of file + + private static string BuildRootTopic(string entityId, string discoveryPrefix) + { + var separatorIndex = entityId.IndexOf('.'); + if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1) + { + throw new ArgumentException( + $"Entity id '{entityId}' is not in the 'domain.object_id' format.", + nameof(entityId)); + } + + var domain = entityId[..separatorIndex]; + var objectId = entityId[(separatorIndex + 1)..]; + + return $"{discoveryPrefix}/{domain}/{objectId}"; + } +} diff --git a/HomeAssistant.Entities/HomeAssistant.Entities.csproj b/HomeAssistant.Entities/HomeAssistant.Entities.csproj index e4c528e..f584221 100644 --- a/HomeAssistant.Entities/HomeAssistant.Entities.csproj +++ b/HomeAssistant.Entities/HomeAssistant.Entities.csproj @@ -7,14 +7,14 @@ - - - - - - - - + + + + + + + + diff --git a/HomeAssistant.Models/HomeAssistant.Models.csproj b/HomeAssistant.Models/HomeAssistant.Models.csproj index 797aa7e..29d04a7 100644 --- a/HomeAssistant.Models/HomeAssistant.Models.csproj +++ b/HomeAssistant.Models/HomeAssistant.Models.csproj @@ -7,7 +7,7 @@ - + diff --git a/HomeAssistant.Server/HomeAssistant.Server.csproj b/HomeAssistant.Server/HomeAssistant.Server.csproj index 0c489d6..5fb99f8 100644 --- a/HomeAssistant.Server/HomeAssistant.Server.csproj +++ b/HomeAssistant.Server/HomeAssistant.Server.csproj @@ -37,14 +37,14 @@ - - - - - - - - + + + + + + + + diff --git a/HomeAssistant.Server/MqttRecreateApp.cs b/HomeAssistant.Server/MqttRecreateApp.cs index b59d4a5..fcb5276 100644 --- a/HomeAssistant.Server/MqttRecreateApp.cs +++ b/HomeAssistant.Server/MqttRecreateApp.cs @@ -181,7 +181,7 @@ public sealed class MqttRecreateApp try { _logger.LogInformation("Recreating PowerMonitor MQTT entities"); - await entityService.CleanupEntitiesAsync().ConfigureAwait(false); + await entityService.RemoveSystemEntitiesAsync().ConfigureAwait(false); await Task.Delay(TimeSpan.FromSeconds(1)); await entityService.CreateSystemEntitiesAsync().ConfigureAwait(false); await entityService.ResetEntitiesAsync().ConfigureAwait(false); diff --git a/HomeAssistant.Server/appsettings.json b/HomeAssistant.Server/appsettings.json index da9b965..eaed12b 100644 --- a/HomeAssistant.Server/appsettings.json +++ b/HomeAssistant.Server/appsettings.json @@ -1,17 +1,7 @@ { "Serilog": { "MinimumLevel": { - "Default": "Warning", - "Override": { - "System.Net.Http.HttpClient": "Warning", - "NordPoolManager": "Information", - "PowerMonitorManager": "Information", - "BoilerMonitorManager": "Information", - "ShowerMonitorManager": "Information", - "LightMonitorManager": "Information", - "BatteryMonitorManager": "Information", - "LeakMonitorManager": "Information" - } + "Default": "Warning" }, "WriteTo": [ { @@ -41,7 +31,7 @@ "MainHomeHumidityEntityId": "sensor.main_home_humidity", "BathroomTemperatureEntityId": "sensor.bathroom_temperature", "ExhaustFanEntityId": "switch.exhaust_fan", - "PollIntervalSeconds": 30, + "PollIntervalSeconds": 5, "SpikeRateThreshold": 4.0, "MinDifferentialHumidity": 8.0, "PeakHumidityThreshold": 58.0, @@ -70,13 +60,13 @@ "NotificationCooldownMinutes": 5 }, "PowerMonitor": { - "Enabled": true, + "Enabled": false, "MainMeterEntityId": "sensor.sonoff_100267d63f_power", "PollIntervalSeconds": 1, "SmoothingWindowSize": 10, "AnomalyThresholdWatts": 500, "HighPowerThresholdWatts": 6000, - "EnforceLimitEnabled": true, + "EnforceLimitEnabled": false, "PowerLimitWatts": 5500, "RecoverySeconds": 600, "LimitCooldownSeconds": 30, diff --git a/HomeAssistant.Server/program.cs b/HomeAssistant.Server/program.cs index 0e6b696..2550e67 100644 --- a/HomeAssistant.Server/program.cs +++ b/HomeAssistant.Server/program.cs @@ -45,7 +45,7 @@ try .AddAutoMapper(config => { config.LicenseKey = - "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxNzk1NDc4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiY3RtXzAxa2F2ZWR3ZHJkNzg0dmZ6NWdqMmVuYzRmIiwic3ViX2lkIjoiLSIsImVkaXRpb24iOiIwIiwidHlwZSI6IjIifQ.n1iwRUZXd60e8zM5_242OERaBGi-ZxOVllchr1rfDlkl6iV0cpflZrT2cwpJSha7xYGJ9gfpe1JWATplQeX_RvvUM6ZxkS1BiJdZkCtu8cMLnXZ1Py6A-myFVLBJA06crl6DJkBa3yCGMsQUaoPQbg5AAxYzrx9JfjxArnyRC1HjI4_6ZMn0zxsaRXQAODF7yPo9TNrtyaQ75bLh3nv9ankzHJ6gibKIbNxiq9m-X_5ejd0NHXSst2ckTf5Eyfevv6Rmi45H_Ry5ePXxLdTNkdqHR6MqLbVZ8cpNBt69NajsBTodGy29UfZg0iiwB3s9ztnnobxvSM2KZ4-WsVKAYA"; + "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODMwMDM4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiMDE5YWI2ZTYxY2VjN2Y4YWFkMzIxOGZkNDg3ZGE4MDYiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiIsInRlcm1fZW5kIjoiMTgyNzQ0NjQwMCJ9.VgEgdxh9xBudubLZr90mUiCORAhLx00Fz7lw1bUMhLWICjBposFrBWrgccKb_irFis_6qUyi567VbsmbjTDxAp9-f0QI0VW4_Zr9wcNeCrDzE0U-DKdcWoMpHoJYUf62tMscGcgVJEKgMX27KLWWqAQzcJm8X-O072A7pW1_x_xkAorFOIfahKXdECnUUdHpPUdrClUbxfWS-wkkKBP0AnrnYY1N2FGlqsJj5_ro1Mmcpijx0sxUKSl1FKaHmx6pOHq-rvJEF7Vvi35vO4HQYFnyP-hN2fQSkgK-Eg8LG6BqBLDXK33VlI6WMO0nOUG62KWAI7jXPSZhrSjBZfxy0g"; config.AddProfile(); config.AddProfile(); }) diff --git a/HomeAssistantSDK.sln b/HomeAssistantSDK.sln index 7d7ab10..c8e946f 100644 --- a/HomeAssistantSDK.sln +++ b/HomeAssistantSDK.sln @@ -54,6 +54,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeakMonitor.Manager", "Leak EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeakMonitor.Manager.Tests", "LeakMonitor.Manager.Tests\LeakMonitor.Manager.Tests.csproj", "{D56BE1F2-830C-43DB-87A8-A659192984FC}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Managers", "Managers", "{785A4330-F9E1-457E-9080-0F77BC4BC67F}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -384,5 +386,12 @@ Global {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0} = {95E98121-7DA4-4085-A8E3-B0430628452F} {590B5855-07CB-4D04-8602-04ECE53D2A2B} = {48492269-2B47-43FE-BC14-A901054EE5AE} {D56BE1F2-830C-43DB-87A8-A659192984FC} = {95E98121-7DA4-4085-A8E3-B0430628452F} + {C844BDD9-584D-4D72-8EDE-AEB3E7429FC1} = {785A4330-F9E1-457E-9080-0F77BC4BC67F} + {488964A2-C7A2-45C9-9CDB-98515AFD7242} = {785A4330-F9E1-457E-9080-0F77BC4BC67F} + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7} = {785A4330-F9E1-457E-9080-0F77BC4BC67F} + {9165EDEF-2FE2-4578-849B-B4D4089416DA} = {785A4330-F9E1-457E-9080-0F77BC4BC67F} + {C7470849-2B14-4E4E-AE96-5A509CACA5AA} = {785A4330-F9E1-457E-9080-0F77BC4BC67F} + {4DEE2DDD-E964-48AF-B6C2-EF61152845BA} = {785A4330-F9E1-457E-9080-0F77BC4BC67F} + {8D05B406-B94B-4D6B-8221-831485AF6702} = {785A4330-F9E1-457E-9080-0F77BC4BC67F} EndGlobalSection EndGlobal diff --git a/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj b/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj index b254b3c..3c92fef 100644 --- a/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj +++ b/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj @@ -8,18 +8,18 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + diff --git a/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs b/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs index e28285a..499137a 100644 --- a/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs +++ b/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs @@ -1,3 +1,4 @@ +using FluentAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; @@ -12,101 +13,344 @@ namespace LeakMonitor.Manager.Tests; public class LeakMonitorInitTests { - private readonly Mock _haContextMock; - private readonly Mock _notificationServiceMock; - private readonly Mock> _loggerMock; - private readonly LeakMonitorOptions _options; + private readonly Mock _haContextMock = new(); + private readonly Mock _notificationServiceMock = new(); + private readonly Mock> _loggerMock = new(); + private readonly LeakMonitorTestData.TrackingObservable _stateChanges = new(); public LeakMonitorInitTests() { - _haContextMock = new Mock(); - _notificationServiceMock = new Mock(); - _loggerMock = new Mock>(); - _options = new LeakMonitorOptions - { - Enabled = true, - SensorEntityIds = ["binary_sensor.aquarium_leak_sensor", "binary_sensor.boiler_moisture"] - }; + _haContextMock.Setup(h => h.StateAllChanges()).Returns(_stateChanges); } - private LeakMonitorInit CreateSut() + private LeakMonitorInit CreateSut(LeakMonitorOptions? options = null) { return new LeakMonitorInit( _haContextMock.Object, _notificationServiceMock.Object, _loggerMock.Object, - Options.Create(_options)); + Options.Create(options ?? LeakMonitorTestData.CreateOptions())); + } + + private void VerifyNotifications(Times expected) + { + _notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny()), expected); + _notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny()), expected); + } + + private void VerifyLogged(LogLevel level, Times times) + { + _loggerMock.Verify( + l => l.Log( + level, + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny>()), + times); } #region HandleStateChange - [Fact] - public void HandleStateChange_WaterDetected_ShouldSendLeakAlert() + [Theory] + [MemberData(nameof(LeakMonitorTestData.WaterDetectedCases), MemberType = typeof(LeakMonitorTestData))] + public void HandleStateChange_WhenWaterDetected_ShouldSendLeakAlert(string sensorEntityId, string? newState) { var sut = CreateSut(); - var change = CreateStateChange("off", LeakMonitorConsts.WaterDetectedState); + var change = LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterClearedState, + newState); - sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change); + sut.HandleStateChange(sensorEntityId, change); - _notificationServiceMock.Verify( - n => n.SendLeakAlert("binary_sensor.aquarium_leak_sensor"), - Times.Once); + _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); + _notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny()), Times.Never()); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.WaterClearedCases), MemberType = typeof(LeakMonitorTestData))] + public void HandleStateChange_WhenWaterCleared_ShouldDismissLeakAlert(string sensorEntityId, string? newState) + { + var sut = CreateSut(); + var change = LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterDetectedState, + newState); + + sut.HandleStateChange(sensorEntityId, change); + + _notificationServiceMock.Verify(n => n.DismissLeakAlert(sensorEntityId), Times.Once()); + _notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny()), Times.Never()); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.NonActionableStateCases), MemberType = typeof(LeakMonitorTestData))] + public void HandleStateChange_WhenStateIsNotActionable_ShouldNotNotify(string? newState) + { + var sut = CreateSut(); + var change = LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterDetectedState, + newState); + + sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change); + + VerifyNotifications(Times.Never()); } [Fact] - public void HandleStateChange_WaterCleared_ShouldDismissLeakAlert() + public void HandleStateChange_WhenDetectionRepeats_ShouldForwardEveryDetection() { + // Deduplication is the notification service's job (cooldown); the init handler + // forwards each "on" event it receives. var sut = CreateSut(); - var change = CreateStateChange("on", LeakMonitorConsts.WaterClearedState); + var change = LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterDetectedState, + LeakMonitorConsts.WaterDetectedState); - sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change); + sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change); + sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change); _notificationServiceMock.Verify( - n => n.DismissLeakAlert("binary_sensor.aquarium_leak_sensor"), - Times.Once); + n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), + Times.Exactly(2)); + _notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny()), Times.Never()); } - [Fact] - public void HandleStateChange_UnknownState_ShouldNotNotify() + [Theory] + [MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))] + public void HandleStateChange_WithBlankSensorId_ShouldForwardTheIdVerbatim(string sensorEntityId) { var sut = CreateSut(); - var change = CreateStateChange("off", "unavailable"); + var change = LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterClearedState, + LeakMonitorConsts.WaterDetectedState); - sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change); + sut.HandleStateChange(sensorEntityId, change); - _notificationServiceMock.Verify( - n => n.SendLeakAlert(It.IsAny()), - Times.Never); - _notificationServiceMock.Verify( - n => n.DismissLeakAlert(It.IsAny()), - Times.Never); - } - - [Fact] - public void HandleStateChange_CaseInsensitive_ShouldDetectWater() - { - var sut = CreateSut(); - var change = CreateStateChange("off", "ON"); - - sut.HandleStateChange("binary_sensor.boiler_moisture", change); - - _notificationServiceMock.Verify( - n => n.SendLeakAlert("binary_sensor.boiler_moisture"), - Times.Once); + _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); } #endregion - private StateChange CreateStateChange(string? oldState, string? newState) - { - var entity = new Entity(_haContextMock.Object, "binary_sensor.test"); - var oldEntityState = oldState is not null - ? new EntityState { State = oldState } - : null; - var newEntityState = newState is not null - ? new EntityState { State = newState } - : null; + #region InitializeAsync - return new StateChange(entity, oldEntityState, newEntityState); + [Fact] + public void InitializeAsync_WhenNoSensorsConfigured_ShouldNotSubscribeAndLogWarning() + { + var sut = CreateSut(LeakMonitorTestData.CreateOptions(sensorEntityIds: [])); + + sut.Should().NotBeNull(); + _stateChanges.SubscriptionCount.Should().Be(0); + _haContextMock.Verify(h => h.StateAllChanges(), Times.Never()); + VerifyNotifications(Times.Never()); + VerifyLogged(LogLevel.Warning, Times.Once()); } + + [Fact] + public void InitializeAsync_WhenSensorsConfigured_ShouldSubscribeToEachSensor() + { + CreateSut(); + + _stateChanges.SubscriptionCount.Should().Be(LeakMonitorTestData.DefaultSensorIds.Length); + _haContextMock.Verify( + h => h.StateAllChanges(), + Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))] + public void InitializeAsync_WithBlankSensorId_ShouldStillSubscribeAndForward(string sensorEntityId) + { + var sut = CreateSut(LeakMonitorTestData.CreateOptions(sensorEntityIds: [sensorEntityId])); + + _stateChanges.SubscriptionCount.Should().Be(1); + + _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterClearedState, + LeakMonitorConsts.WaterDetectedState)); + + _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); + } + + [Fact] + public void InitializeAsync_WithNullSensorEntry_ShouldStillSubscribeRemainingSensors() + { + CreateSut(LeakMonitorTestData.CreateOptions( + sensorEntityIds: [null!, LeakMonitorTestData.BoilerSensorId])); + + _stateChanges.SubscriptionCount.Should().Be(2); + + _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + LeakMonitorTestData.BoilerSensorId, + LeakMonitorConsts.WaterClearedState, + LeakMonitorConsts.WaterDetectedState)); + + _notificationServiceMock.Verify( + n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId), + Times.Once()); + _notificationServiceMock.Verify( + n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), + Times.Never()); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.WaterDetectedCases), MemberType = typeof(LeakMonitorTestData))] + public void InitializeAsync_WhenSubscribedSensorDetectsWater_ShouldSendLeakAlert( + string sensorEntityId, + string? newState) + { + CreateSut(); + + _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterClearedState, + newState)); + + _notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once()); + _notificationServiceMock.Verify( + n => n.SendLeakAlert(It.Is(id => id != sensorEntityId)), + Times.Never()); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.WaterClearedCases), MemberType = typeof(LeakMonitorTestData))] + public void InitializeAsync_WhenSubscribedSensorClearsWater_ShouldDismissLeakAlert( + string sensorEntityId, + string? newState) + { + CreateSut(); + + _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + sensorEntityId, + LeakMonitorConsts.WaterDetectedState, + newState)); + + _notificationServiceMock.Verify(n => n.DismissLeakAlert(sensorEntityId), Times.Once()); + _notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny()), Times.Never()); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.NonActionableStateCases), MemberType = typeof(LeakMonitorTestData))] + public void InitializeAsync_WhenSubscribedSensorReportsNonActionableState_ShouldNotNotify(string? newState) + { + CreateSut(); + + _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterDetectedState, + newState)); + + VerifyNotifications(Times.Never()); + } + + [Fact] + public void InitializeAsync_WhenStateIsUnchanged_ShouldNotNotify() + { + CreateSut(); + + _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterDetectedState, + LeakMonitorConsts.WaterDetectedState)); + + VerifyNotifications(Times.Never()); + } + + [Fact] + public void InitializeAsync_WhenUnrelatedEntityChanges_ShouldNotNotify() + { + CreateSut(); + + _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + "binary_sensor.unrelated_motion", + LeakMonitorConsts.WaterClearedState, + LeakMonitorConsts.WaterDetectedState)); + + VerifyNotifications(Times.Never()); + } + + [Fact] + public void InitializeAsync_WhenDetectionSequenceArrives_ShouldNotifyPerTransition() + { + CreateSut(); + + foreach (var change in LeakMonitorTestData.CreateStateChangeSequence( + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorTestData.DetectionSequence)) + { + _stateChanges.Publish(change); + } + + _notificationServiceMock.Verify( + n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId), + Times.Exactly(2)); + _notificationServiceMock.Verify( + n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId), + Times.Exactly(2)); + } + + [Fact] + public void InitializeAsync_WhenNotificationServiceThrows_ShouldLogErrorAndKeepMonitoring() + { + _notificationServiceMock + .Setup(n => n.SendLeakAlert(It.IsAny())) + .Throws(new InvalidOperationException("notification failed")); + + CreateSut(); + + var act = () => _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterClearedState, + LeakMonitorConsts.WaterDetectedState)); + + act.Should().NotThrow(); + VerifyLogged(LogLevel.Error, Times.Once()); + + // The failed event must not tear down the subscription. + _stateChanges.Publish(LeakMonitorTestData.CreateStateChange( + _haContextMock.Object, + LeakMonitorTestData.AquariumSensorId, + LeakMonitorConsts.WaterDetectedState, + LeakMonitorConsts.WaterClearedState)); + + _notificationServiceMock.Verify( + n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId), + Times.Once()); + } + + [Fact] + public void InitializeAsync_WhenSubscriptionFails_ShouldSwallowAndLogError() + { + _haContextMock + .Setup(h => h.StateAllChanges()) + .Throws(new InvalidOperationException("home assistant offline")); + + var act = () => CreateSut(); + + act.Should().NotThrow(); + _stateChanges.SubscriptionCount.Should().Be(0); + VerifyNotifications(Times.Never()); + VerifyLogged(LogLevel.Error, Times.Once()); + } + + #endregion } diff --git a/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs b/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs new file mode 100644 index 0000000..8678619 --- /dev/null +++ b/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs @@ -0,0 +1,248 @@ +using System.Text.Json; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using LeakMonitor.Models; +using LeakMonitorManager.Models; + +namespace LeakMonitor.Manager.Tests; + +/// +/// Shared, deterministic builders and datasets used by the LeakMonitor tests. +/// Keeping entity/state construction, notification payload capture and generated +/// input rows here means the test classes only describe the scenario under test. +/// +internal static class LeakMonitorTestData +{ + public const string AquariumSensorId = "binary_sensor.aquarium_leak_sensor"; + + public const string BoilerSensorId = "binary_sensor.boiler_moisture"; + + public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId]; + + public static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); + + /// + /// Builds leak monitor options with production-compatible defaults. + /// Pass [] for no sensors; omit the argument for the shared sensor set. + /// + public static LeakMonitorOptions CreateOptions( + IEnumerable? sensorEntityIds = null, + int notificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes, + bool enabled = true) => new() + { + Enabled = enabled, + SensorEntityIds = sensorEntityIds?.ToArray() ?? [.. DefaultSensorIds], + NotificationCooldownMinutes = notificationCooldownMinutes + }; + + /// + /// Every casing of the "water detected" state, across both configured sensors. + /// + public static TheoryData WaterDetectedCases { get; } = new() + { + { AquariumSensorId, LeakMonitorConsts.WaterDetectedState }, + { AquariumSensorId, "ON" }, + { AquariumSensorId, "On" }, + { AquariumSensorId, "oN" }, + { BoilerSensorId, LeakMonitorConsts.WaterDetectedState } + }; + + /// + /// Every casing of the "water cleared" state, across both configured sensors. + /// + public static TheoryData WaterClearedCases { get; } = new() + { + { AquariumSensorId, LeakMonitorConsts.WaterClearedState }, + { AquariumSensorId, "OFF" }, + { AquariumSensorId, "Off" }, + { BoilerSensorId, "oFf" } + }; + + /// + /// 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). + /// + public static TheoryData NonActionableStateCases { get; } = new() + { + "unavailable", + "UNAVAILABLE", + "unknown", + "UNKNOWN", + string.Empty, + " ", + "\t", + "open", + "idle", + "detected", + "ON ", + " off", + "1", + "true", + null + }; + + /// + /// Blank but non-null sensor ids. Production does not validate ids, so these are + /// subscribed and forwarded verbatim. + /// + public static TheoryData BlankSensorIds { get; } = new() + { + string.Empty, + " ", + "\t" + }; + + /// + /// (sensor id, expected notification id) rows for the id sanitising rules: + /// dots become underscores, other characters and blanks are preserved. + /// + public static TheoryData NotificationIdCases { get; } = new() + { + { AquariumSensorId, "leak_monitor_binary_sensor_aquarium_leak_sensor" }, + { BoilerSensorId, "leak_monitor_binary_sensor_boiler_moisture" }, + { "sensor.a.b.c", "leak_monitor_sensor_a_b_c" }, + { "no_dots", "leak_monitor_no_dots" }, + { "binary_sensor.already_snake_case", "leak_monitor_binary_sensor_already_snake_case" }, + { "binary_sensor.dash-and-dot.", "leak_monitor_binary_sensor_dash-and-dot_" }, + { string.Empty, "leak_monitor_" }, + { " ", "leak_monitor_ " } + }; + + /// + /// (cooldown minutes, elapsed seconds before the second alert, expected notification count) + /// rows straddling the strict elapsed < cooldown boundary, plus zero, negative + /// and int-max cooldowns. + /// + public static TheoryData CooldownBoundaryCases { get; } = new() + { + { 5, 0, 1 }, + { 5, 299, 1 }, + { 5, 300, 2 }, + { 5, 301, 2 }, + { 10, 599, 1 }, + { 10, 600, 2 }, + { 1, 59, 1 }, + { 1, 60, 2 }, + { 0, 0, 2 }, + { -5, 0, 2 }, + { int.MaxValue, 600, 1 } + }; + + /// + /// Repetition counts used to exercise duplicate suppression and zero-cooldown behaviour. + /// + public static TheoryData RepeatedNotificationCounts { get; } = new() + { + 2, + 3, + 5, + 10 + }; + + /// + /// A deterministic detection/recovery sequence. The repeated "on" transition is filtered + /// out downstream, so the expected totals are two alerts and two dismissals. + /// + public static (string? OldState, string? NewState)[] DetectionSequence { get; } = + [ + ("off", "on"), + ("on", "on"), + ("on", "off"), + ("off", "unavailable"), + ("unavailable", "on"), + ("on", "off") + ]; + + /// + /// Builds an , or null when the entity has no state at all. + /// + public static EntityState? CreateOptionalState(string? state) => + state is null ? null : new EntityState { State = state }; + + public static StateChange CreateStateChange( + IHaContext haContext, + string entityId, + string? oldState, + string? newState) => + new(new Entity(haContext, entityId), CreateOptionalState(oldState), CreateOptionalState(newState)); + + public static IReadOnlyList CreateStateChangeSequence( + IHaContext haContext, + string entityId, + params (string? OldState, string? NewState)[] transitions) => + transitions + .Select(transition => CreateStateChange(haContext, entityId, transition.OldState, transition.NewState)) + .ToList(); + + /// One captured IHaContext.CallService invocation. + public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data); + + /// + /// Wires on the mock and returns the captured calls + /// in invocation order. + /// + public static List CaptureServiceCalls(Mock haContextMock) + { + var calls = new List(); + + haContextMock + .Setup(h => h.CallService( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Callback((domain, service, target, data) => + calls.Add(new ServiceCall(domain, service, target, data))); + + return calls; + } + + /// Serialises a captured service-call payload so tests can assert on it. + public static JsonElement SerializePayload(object? data) => JsonSerializer.SerializeToElement(data); + + /// + /// Deterministic clock so cooldown boundaries can be crossed without real waiting. + /// + public sealed class ManualTimeProvider(DateTimeOffset? start = null) : TimeProvider + { + private DateTimeOffset _utcNow = start ?? DefaultStart; + + public override DateTimeOffset GetUtcNow() => _utcNow; + + public void Advance(TimeSpan duration) => _utcNow += duration; + + public void AdvanceSeconds(int seconds) => Advance(TimeSpan.FromSeconds(seconds)); + } + + /// + /// Observable that records subscriptions and lets tests push state changes through the + /// same pipeline the NetDaemon runtime uses. + /// + public sealed class TrackingObservable : IObservable + { + private readonly List> _observers = []; + + public int SubscriptionCount => _observers.Count; + + public IDisposable Subscribe(IObserver observer) + { + _observers.Add(observer); + + return new Subscription(_observers, observer); + } + + public void Publish(T value) + { + foreach (var observer in _observers.ToArray()) + { + observer.OnNext(value); + } + } + + private sealed class Subscription(List> observers, IObserver observer) : IDisposable + { + public void Dispose() => observers.Remove(observer); + } + } +} diff --git a/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs b/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs index 1b2009b..b3144ad 100644 --- a/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs +++ b/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs @@ -12,74 +12,204 @@ namespace LeakMonitor.Manager.Tests; public class LeakNotificationServiceTests { - private readonly Mock _haContextMock; - private readonly Mock> _loggerMock; - private readonly LeakMonitorOptions _options; + private readonly Mock _haContextMock = new(); + private readonly Mock> _loggerMock = new(); + private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new(); - public LeakNotificationServiceTests() - { - _haContextMock = new Mock(); - _loggerMock = new Mock>(); - _options = new LeakMonitorOptions - { - Enabled = true, - NotificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes - }; - } - - private LeakNotificationService CreateSut() + private LeakNotificationService CreateSut(LeakMonitorOptions? options = null) { return new LeakNotificationService( _haContextMock.Object, _loggerMock.Object, - Options.Create(_options), - TimeProvider.System); + Options.Create(options ?? LeakMonitorTestData.CreateOptions()), + _timeProvider); + } + + private void VerifyMobilePush(Times times) + { + _haContextMock.Verify( + h => h.CallService( + LeakMonitorConsts.NotifyDomain, + LeakMonitorConsts.MobileAppService, + It.IsAny(), + It.IsAny()), + times); + } + + private void VerifyPersistentCreate(Times times) + { + _haContextMock.Verify( + h => h.CallService( + LeakMonitorConsts.PersistentNotificationDomain, + LeakMonitorConsts.PersistentNotificationCreateService, + It.IsAny(), + It.IsAny()), + times); + } + + private void VerifyPersistentDismiss(Times times) + { + _haContextMock.Verify( + h => h.CallService( + LeakMonitorConsts.PersistentNotificationDomain, + LeakMonitorConsts.PersistentNotificationDismissService, + It.IsAny(), + It.IsAny()), + times); } #region SendLeakAlert - [Fact] - public void SendLeakAlert_ShouldCallMobileNotifyService() + public static TheoryData SendAlertServiceCalls { get; } = new() + { + { LeakMonitorConsts.NotifyDomain, LeakMonitorConsts.MobileAppService }, + { LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationCreateService } + }; + + [Theory] + [MemberData(nameof(SendAlertServiceCalls))] + public void SendLeakAlert_ShouldCallExpectedService(string domain, string service) { var sut = CreateSut(); - sut.SendLeakAlert("binary_sensor.aquarium_leak_sensor"); + sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId); - _haContextMock.Verify(h => h.CallService( - LeakMonitorConsts.NotifyDomain, - LeakMonitorConsts.MobileAppService, - It.IsAny(), - It.IsAny()), Times.Once); + _haContextMock.Verify( + h => h.CallService(domain, service, It.IsAny(), It.IsAny()), + Times.Once()); } [Fact] - public void SendLeakAlert_ShouldCallPersistentNotificationCreate() + public void SendLeakAlert_ShouldIncludeSensorDetailsInPayloads() { + var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock); var sut = CreateSut(); + const string sensorId = LeakMonitorTestData.AquariumSensorId; + var expectedMessage = $"Water detected by {sensorId}! Check immediately."; - sut.SendLeakAlert("binary_sensor.aquarium_leak_sensor"); + sut.SendLeakAlert(sensorId); - _haContextMock.Verify(h => h.CallService( - LeakMonitorConsts.PersistentNotificationDomain, - LeakMonitorConsts.PersistentNotificationCreateService, - It.IsAny(), - It.IsAny()), Times.Once); + calls.Should().HaveCount(2); + + var mobileCall = calls.Single(c => c.Service == LeakMonitorConsts.MobileAppService); + mobileCall.Domain.Should().Be(LeakMonitorConsts.NotifyDomain); + mobileCall.Target.Should().BeNull(); + + var mobilePayload = LeakMonitorTestData.SerializePayload(mobileCall.Data); + mobilePayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle); + mobilePayload.GetProperty("message").GetString().Should().Be(expectedMessage); + + var sound = mobilePayload.GetProperty("data").GetProperty("push").GetProperty("sound"); + sound.GetProperty("critical").GetInt32().Should().Be(1); + sound.GetProperty("volume").GetDouble().Should().Be(1.0); + + var persistentCall = calls.Single(c => c.Service == LeakMonitorConsts.PersistentNotificationCreateService); + persistentCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain); + persistentCall.Target.Should().BeNull(); + + var persistentPayload = LeakMonitorTestData.SerializePayload(persistentCall.Data); + persistentPayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle); + persistentPayload.GetProperty("message").GetString().Should().Be(expectedMessage); + persistentPayload.GetProperty("notification_id").GetString().Should() + .Be(LeakNotificationService.BuildNotificationId(sensorId)); } [Fact] - public void SendLeakAlert_CalledTwiceWithinCooldown_ShouldOnlyNotifyOnce() + public void SendLeakAlert_ShouldNotDismissNotification() { var sut = CreateSut(); - const string sensorId = "binary_sensor.aquarium_leak_sensor"; + + sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId); + + VerifyMobilePush(Times.Once()); + VerifyPersistentCreate(Times.Once()); + VerifyPersistentDismiss(Times.Never()); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.NotificationIdCases), MemberType = typeof(LeakMonitorTestData))] + public void SendLeakAlert_ShouldUseExpectedNotificationId(string sensorId, string expectedNotificationId) + { + var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock); + var sut = CreateSut(); sut.SendLeakAlert(sensorId); + + var persistentCall = calls.Single(c => + c.Domain == LeakMonitorConsts.PersistentNotificationDomain && + c.Service == LeakMonitorConsts.PersistentNotificationCreateService); + + LeakMonitorTestData.SerializePayload(persistentCall.Data) + .GetProperty("notification_id") + .GetString() + .Should() + .Be(expectedNotificationId); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.RepeatedNotificationCounts), MemberType = typeof(LeakMonitorTestData))] + public void SendLeakAlert_RepeatedWithinCooldown_ShouldOnlyNotifyOnce(int repeats) + { + var sut = CreateSut(); + const string sensorId = LeakMonitorTestData.AquariumSensorId; + + for (var i = 0; i < repeats; i++) + { + sut.SendLeakAlert(sensorId); + } + + VerifyMobilePush(Times.Once()); + VerifyPersistentCreate(Times.Once()); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.RepeatedNotificationCounts), MemberType = typeof(LeakMonitorTestData))] + public void SendLeakAlert_RepeatedWithZeroCooldown_ShouldAlwaysNotify(int repeats) + { + var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: 0)); + const string sensorId = LeakMonitorTestData.AquariumSensorId; + + for (var i = 0; i < repeats; i++) + { + sut.SendLeakAlert(sensorId); + } + + VerifyMobilePush(Times.Exactly(repeats)); + VerifyPersistentCreate(Times.Exactly(repeats)); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.CooldownBoundaryCases), MemberType = typeof(LeakMonitorTestData))] + public void SendLeakAlert_ShouldRespectCooldownBoundaries( + int cooldownMinutes, + int elapsedSeconds, + int expectedNotificationCount) + { + var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: cooldownMinutes)); + const string sensorId = LeakMonitorTestData.AquariumSensorId; + + sut.SendLeakAlert(sensorId); + _timeProvider.AdvanceSeconds(elapsedSeconds); sut.SendLeakAlert(sensorId); - _haContextMock.Verify(h => h.CallService( - LeakMonitorConsts.NotifyDomain, - LeakMonitorConsts.MobileAppService, - It.IsAny(), - It.IsAny()), Times.Once); + VerifyMobilePush(Times.Exactly(expectedNotificationCount)); + VerifyPersistentCreate(Times.Exactly(expectedNotificationCount)); + } + + [Fact] + public void SendLeakAlert_AfterEachCooldownExpires_ShouldNotifyEveryTime() + { + var sut = CreateSut(); + const string sensorId = LeakMonitorTestData.AquariumSensorId; + + sut.SendLeakAlert(sensorId); + _timeProvider.Advance(TimeSpan.FromMinutes(LeakMonitorConsts.DefaultNotificationCooldownMinutes)); + sut.SendLeakAlert(sensorId); + _timeProvider.Advance(TimeSpan.FromMinutes(LeakMonitorConsts.DefaultNotificationCooldownMinutes)); + sut.SendLeakAlert(sensorId); + + VerifyMobilePush(Times.Exactly(3)); + VerifyPersistentCreate(Times.Exactly(3)); } [Fact] @@ -87,31 +217,50 @@ public class LeakNotificationServiceTests { var sut = CreateSut(); - sut.SendLeakAlert("binary_sensor.aquarium_leak_sensor"); - sut.SendLeakAlert("binary_sensor.boiler_moisture"); + foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds) + { + sut.SendLeakAlert(sensorId); + } - _haContextMock.Verify(h => h.CallService( - LeakMonitorConsts.NotifyDomain, - LeakMonitorConsts.MobileAppService, - It.IsAny(), - It.IsAny()), Times.Exactly(2)); + VerifyMobilePush(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); + VerifyPersistentCreate(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length)); } [Fact] - public void SendLeakAlert_WithZeroCooldown_ShouldAlwaysNotify() + public void SendLeakAlert_CooldownShouldBeTrackedPerSensor() { - _options.NotificationCooldownMinutes = 0; + var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock); var sut = CreateSut(); - const string sensorId = "binary_sensor.aquarium_leak_sensor"; - sut.SendLeakAlert(sensorId); - sut.SendLeakAlert(sensorId); + sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId); + _timeProvider.AdvanceSeconds(60); - _haContextMock.Verify(h => h.CallService( - LeakMonitorConsts.NotifyDomain, - LeakMonitorConsts.MobileAppService, - It.IsAny(), - It.IsAny()), Times.Exactly(2)); + // A first-ever alert for a different sensor is not suppressed by the first sensor's cooldown. + sut.SendLeakAlert(LeakMonitorTestData.BoilerSensorId); + sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId); + + VerifyMobilePush(Times.Exactly(2)); + + var boilerNotifications = calls + .Where(c => c.Domain == LeakMonitorConsts.NotifyDomain) + .Where(c => LeakMonitorTestData.SerializePayload(c.Data) + .GetProperty("message") + .GetString()! + .Contains(LeakMonitorTestData.BoilerSensorId, StringComparison.Ordinal)); + + boilerNotifications.Should().ContainSingle(); + } + + [Fact] + public void SendLeakAlert_WithNullSensorId_ShouldThrowAndNotNotify() + { + var sut = CreateSut(); + + var act = () => sut.SendLeakAlert(null!); + + act.Should().Throw(); + VerifyMobilePush(Times.Never()); + VerifyPersistentCreate(Times.Never()); } #endregion @@ -123,33 +272,82 @@ public class LeakNotificationServiceTests { var sut = CreateSut(); - sut.DismissLeakAlert("binary_sensor.aquarium_leak_sensor"); + sut.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId); - _haContextMock.Verify(h => h.CallService( - LeakMonitorConsts.PersistentNotificationDomain, - LeakMonitorConsts.PersistentNotificationDismissService, - It.IsAny(), - It.IsAny()), Times.Once); + VerifyPersistentDismiss(Times.Once()); + VerifyMobilePush(Times.Never()); + VerifyPersistentCreate(Times.Never()); + } + + [Theory] + [MemberData(nameof(LeakMonitorTestData.NotificationIdCases), MemberType = typeof(LeakMonitorTestData))] + public void DismissLeakAlert_ShouldUseExpectedNotificationId(string sensorId, string expectedNotificationId) + { + var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock); + var sut = CreateSut(); + + sut.DismissLeakAlert(sensorId); + + var dismissCall = calls.Should().ContainSingle().Which; + dismissCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain); + dismissCall.Service.Should().Be(LeakMonitorConsts.PersistentNotificationDismissService); + dismissCall.Target.Should().BeNull(); + LeakMonitorTestData.SerializePayload(dismissCall.Data) + .GetProperty("notification_id") + .GetString() + .Should() + .Be(expectedNotificationId); + } + + [Fact] + public void DismissLeakAlert_CalledRepeatedly_ShouldDismissEachTime() + { + var sut = CreateSut(); + const string sensorId = LeakMonitorTestData.AquariumSensorId; + + sut.DismissLeakAlert(sensorId); + sut.DismissLeakAlert(sensorId); + + VerifyPersistentDismiss(Times.Exactly(2)); + } + + [Fact] + public void DismissLeakAlert_ShouldNotResetCooldown() + { + var sut = CreateSut(); + const string sensorId = LeakMonitorTestData.AquariumSensorId; + + sut.SendLeakAlert(sensorId); + sut.DismissLeakAlert(sensorId); + _timeProvider.AdvanceSeconds(60); + sut.SendLeakAlert(sensorId); + + VerifyMobilePush(Times.Once()); + VerifyPersistentCreate(Times.Once()); + VerifyPersistentDismiss(Times.Once()); } #endregion #region BuildNotificationId - [Fact] - public void BuildNotificationId_ShouldReplaceDotsWithUnderscores() + [Theory] + [MemberData(nameof(LeakMonitorTestData.NotificationIdCases), MemberType = typeof(LeakMonitorTestData))] + public void BuildNotificationId_ShouldSanitizeSensorId(string sensorEntityId, string expected) { - var result = LeakNotificationService.BuildNotificationId("binary_sensor.aquarium_leak_sensor"); + var result = LeakNotificationService.BuildNotificationId(sensorEntityId); - result.Should().Be("leak_monitor_binary_sensor_aquarium_leak_sensor"); + result.Should().Be(expected); + result.Should().StartWith(LeakMonitorConsts.NotificationIdPrefix); } [Fact] - public void BuildNotificationId_ShouldStartWithPrefix() + public void BuildNotificationId_WithNullSensorId_ShouldThrow() { - var result = LeakNotificationService.BuildNotificationId("binary_sensor.boiler_moisture"); + // Production has no null guard; the string.Replace call fails before any prefix is built. + Action act = () => LeakNotificationService.BuildNotificationId(null!); - result.Should().StartWith(LeakMonitorConsts.NotificationIdPrefix); + act.Should().Throw(); } #endregion diff --git a/LeakMonitor.Manager/LeakMonitor.Manager.csproj b/LeakMonitor.Manager/LeakMonitor.Manager.csproj index dd8b140..17e998d 100644 --- a/LeakMonitor.Manager/LeakMonitor.Manager.csproj +++ b/LeakMonitor.Manager/LeakMonitor.Manager.csproj @@ -19,9 +19,9 @@ - - - + + + diff --git a/LightMonitor.Manager.Tests/LightControlServiceTests.cs b/LightMonitor.Manager.Tests/LightControlServiceTests.cs index 1b06219..4f8c26d 100644 --- a/LightMonitor.Manager.Tests/LightControlServiceTests.cs +++ b/LightMonitor.Manager.Tests/LightControlServiceTests.cs @@ -11,14 +11,10 @@ namespace LightMonitor.Manager.Tests; public class LightControlServiceTests { - private const string LightEntityId = "light.sonoff_1002214d40"; - private const string SunEntityId = "sun.sun"; + private const string LightEntityId = LightMonitorTestData.LightEntityId; + private const string SunEntityId = LightMonitorTestData.SunEntityId; - private readonly LightMonitorOptions _defaultOptions = new() - { - LightEntityId = LightEntityId, - SunEntityId = SunEntityId - }; + private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions(); private readonly Mock _haContextMock = new(); @@ -30,87 +26,116 @@ public class LightControlServiceTests Options.Create(options ?? _defaultOptions)); } - [Fact] - public void TurnOnLight_WhenDarkAndLightIsOff_ShouldTurnOnLight() + private void SetupState(string entityId, string? state) { - _haContextMock.Setup(x => x.GetState(SunEntityId)) - .Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon }); - _haContextMock.Setup(x => x.GetState(LightEntityId)) - .Returns(new EntityState { State = "off" }); + _haContextMock.Setup(x => x.GetState(entityId)) + .Returns(LightMonitorTestData.CreateOptionalState(state)); + } - var service = CreateService(); - service.TurnOnLight(); + private void VerifyTurnOn(string entityId, bool shouldTurnOn) + { + if (!shouldTurnOn) + { + _haContextMock.Verify(x => x.CallService( + It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny()), + Times.Never); + + return; + } _haContextMock.Verify(x => x.CallService("light", "turn_on", - It.IsAny(), It.IsAny()), Times.Once); + It.Is(target => target.EntityIds != null && target.EntityIds.Contains(entityId)), + It.IsAny()), + Times.Once); + } + + [Theory] + [MemberData(nameof(LightMonitorTestData.SunStateTurnOnCases), MemberType = typeof(LightMonitorTestData))] + public void TurnOnLight_ShouldOnlyTurnOnWhenSunIsBelowHorizon(string? sunState, bool shouldTurnOn) + { + SetupState(SunEntityId, sunState); + SetupState(LightEntityId, "off"); + + CreateService().TurnOnLight(); + + VerifyTurnOn(LightEntityId, shouldTurnOn); + } + + [Theory] + [MemberData(nameof(LightMonitorTestData.LightStateTurnOnCases), MemberType = typeof(LightMonitorTestData))] + public void TurnOnLight_WhenSunIsBelowHorizon_ShouldOnlyTurnOnWhenLightIsNotAlreadyOn( + string? lightState, + bool shouldTurnOn) + { + SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon); + SetupState(LightEntityId, lightState); + + CreateService().TurnOnLight(); + + VerifyTurnOn(LightEntityId, shouldTurnOn); } [Fact] - public void TurnOnLight_WhenDarkAndLightIsAlreadyOn_ShouldNotCallService() + public void TurnOnLight_ShouldTargetTheConfiguredLightEntity() { - _haContextMock.Setup(x => x.GetState(SunEntityId)) - .Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon }); - _haContextMock.Setup(x => x.GetState(LightEntityId)) - .Returns(new EntityState { State = "on" }); + const string customLightEntityId = "light.kitchen_ceiling"; + var options = LightMonitorTestData.CreateOptions(lightEntityId: customLightEntityId); - var service = CreateService(); - service.TurnOnLight(); + SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon); + SetupState(customLightEntityId, "off"); - _haContextMock.Verify(x => x.CallService("light", "turn_on", - It.IsAny(), It.IsAny()), Times.Never); + CreateService(options).TurnOnLight(); + + VerifyTurnOn(customLightEntityId, true); } [Fact] - public void TurnOnLight_WhenSunIsAboveHorizon_ShouldNotTurnOnLight() + public void TurnOnLight_WithDefaultOptions_ShouldTargetTheDefaultLightEntity() { - _haContextMock.Setup(x => x.GetState(SunEntityId)) - .Returns(new EntityState { State = LightMonitorConsts.SunAboveHorizon }); + var options = new LightMonitorOptions(); - var service = CreateService(); - service.TurnOnLight(); + SetupState(LightMonitorConsts.DefaultSunEntityId, LightMonitorConsts.SunBelowHorizon); + SetupState(LightMonitorConsts.DefaultLightEntityId, null); - _haContextMock.Verify(x => x.CallService("light", "turn_on", - It.IsAny(), It.IsAny()), Times.Never); + CreateService(options).TurnOnLight(); + + VerifyTurnOn(LightMonitorConsts.DefaultLightEntityId, true); } [Fact] - public void TurnOnLight_WhenSunStateIsNull_ShouldNotTurnOnLight() + public void TurnOnLight_WhenSunIsAboveHorizon_ShouldNotReadTheLightState() { - _haContextMock.Setup(x => x.GetState(SunEntityId)) - .Returns((EntityState?)null); + SetupState(SunEntityId, LightMonitorConsts.SunAboveHorizon); - var service = CreateService(); - service.TurnOnLight(); + CreateService().TurnOnLight(); - _haContextMock.Verify(x => x.CallService("light", "turn_on", - It.IsAny(), It.IsAny()), Times.Never); + _haContextMock.Verify(x => x.GetState(LightEntityId), Times.Never); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void TurnOnLight_WhenSunEntityIdIsBlank_ShouldNotTurnOnLight(string sunEntityId) + { + var options = LightMonitorTestData.CreateOptions(sunEntityId: sunEntityId); + SetupState(LightEntityId, "off"); + + CreateService(options).TurnOnLight(); + + VerifyTurnOn(LightEntityId, false); } [Fact] - public void TurnOnLight_WhenSunStateIsUnavailable_ShouldNotTurnOnLight() + public void TurnOnLight_ShouldReadEachStateAtMostOnce() { - _haContextMock.Setup(x => x.GetState(SunEntityId)) - .Returns(new EntityState { State = "unavailable" }); + SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon); + SetupState(LightEntityId, LightMonitorConsts.LightOnState); - var service = CreateService(); - service.TurnOnLight(); + CreateService().TurnOnLight(); - _haContextMock.Verify(x => x.CallService("light", "turn_on", - It.IsAny(), It.IsAny()), Times.Never); - } - - [Fact] - public void TurnOnLight_WhenLightStateIsNull_ShouldTurnOnLight() - { - _haContextMock.Setup(x => x.GetState(SunEntityId)) - .Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon }); - _haContextMock.Setup(x => x.GetState(LightEntityId)) - .Returns((EntityState?)null); - - var service = CreateService(); - service.TurnOnLight(); - - _haContextMock.Verify(x => x.CallService("light", "turn_on", - It.IsAny(), It.IsAny()), Times.Once); + _haContextMock.Verify(x => x.GetState(SunEntityId), Times.Once); + _haContextMock.Verify(x => x.GetState(LightEntityId), Times.Once); + VerifyTurnOn(LightEntityId, false); } } diff --git a/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj b/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj index 81dc668..f6e5b87 100644 --- a/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj +++ b/LightMonitor.Manager.Tests/LightMonitor.Manager.Tests.csproj @@ -8,18 +8,18 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + diff --git a/LightMonitor.Manager.Tests/LightMonitorInitTests.cs b/LightMonitor.Manager.Tests/LightMonitorInitTests.cs index 5ec39af..21efaa2 100644 --- a/LightMonitor.Manager.Tests/LightMonitorInitTests.cs +++ b/LightMonitor.Manager.Tests/LightMonitorInitTests.cs @@ -1,4 +1,5 @@ using System.Reactive.Subjects; +using FluentAssertions; using LightMonitor.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -13,25 +14,28 @@ namespace LightMonitor.Manager.Tests; public class LightMonitorInitTests { - private const string SunEntityId = "sun.sun"; - private const string PersonEntityId = "person.marius"; + private const string SunEntityId = LightMonitorTestData.SunEntityId; + private const string PersonEntityId = LightMonitorTestData.PrimaryPersonEntityId; private readonly Mock _haContextMock = new(); private readonly Mock _presenceServiceMock = new(); private readonly Mock _lightControlServiceMock = new(); private readonly Subject _stateChangesSubject = new(); - private readonly LightMonitorOptions _defaultOptions = new() - { - Enabled = true, - SunEntityId = SunEntityId, - PersonEntityIds = [PersonEntityId] - }; + private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions(); - private LightMonitorInit CreateSut(LightMonitorOptions? options = null) + private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null) { - _haContextMock.Setup(x => x.StateAllChanges()) - .Returns(_stateChangesSubject); + if (subscriptionException is null) + { + _haContextMock.Setup(x => x.StateAllChanges()) + .Returns(_stateChangesSubject); + } + else + { + _haContextMock.Setup(x => x.StateAllChanges()) + .Throws(subscriptionException); + } return new LightMonitorInit( _haContextMock.Object, @@ -44,124 +48,219 @@ public class LightMonitorInitTests private void EmitStateChange(string entityId, string? oldState, string? newState) { var entity = new Entity(_haContextMock.Object, entityId); - var old = oldState is not null ? new EntityState { State = oldState } : null; - var @new = newState is not null ? new EntityState { State = newState } : null; - _stateChangesSubject.OnNext(new StateChange(entity, old, @new)); + _stateChangesSubject.OnNext(new StateChange( + entity, + LightMonitorTestData.CreateOptionalState(oldState), + LightMonitorTestData.CreateOptionalState(newState))); + } + + private void VerifyTurnOn(bool shouldTurnOn) + { + if (shouldTurnOn) + { + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once); + } + else + { + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + } + } + + [Theory] + [MemberData(nameof(LightMonitorTestData.PersonNewStateCases), MemberType = typeof(LightMonitorTestData))] + public void PersonStateChange_ShouldTurnOnLightOnlyWhenNewStateIsHome(string? newState, bool shouldTurnOn) + { + CreateSut(); + + EmitStateChange(PersonEntityId, "not_home", newState); + + VerifyTurnOn(shouldTurnOn); + } + + [Theory] + [MemberData(nameof(LightMonitorTestData.PersonArrivalTransitions), MemberType = typeof(LightMonitorTestData))] + public void PersonStateChange_ToHome_ShouldIgnoreOnlyRecoveryTransitions(string? oldState, bool shouldTurnOn) + { + CreateSut(); + + EmitStateChange(PersonEntityId, oldState, LightMonitorConsts.PersonHomeState); + + VerifyTurnOn(shouldTurnOn); + } + + [Theory] + [InlineData(LightMonitorTestData.PrimaryPersonEntityId)] + [InlineData(LightMonitorTestData.SecondaryPersonEntityId)] + [InlineData(LightMonitorTestData.PhonePersonEntityId)] + public void PersonStateChange_ShouldTurnOnLightForEveryConfiguredPerson(string personEntityId) + { + CreateSut(); + + EmitStateChange(personEntityId, "not_home", LightMonitorConsts.PersonHomeState); + + VerifyTurnOn(true); } [Fact] - public void PersonStateChange_FromNotHomeToHome_ShouldCallTurnOnLight() + public void PersonStateChange_ForUnconfiguredPerson_ShouldNotTurnOnLight() + { + CreateSut(LightMonitorTestData.CreateOptions(personEntityIds: [PersonEntityId])); + + EmitStateChange( + LightMonitorTestData.SecondaryPersonEntityId, + "not_home", + LightMonitorConsts.PersonHomeState); + + VerifyTurnOn(false); + } + + [Fact] + public void PersonStateChange_ShouldNotConsultThePresenceService() { CreateSut(); EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState); - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once); + VerifyTurnOn(true); + _presenceServiceMock.Verify(x => x.IsAnyoneHome(), Times.Never); } - [Fact] - public void PersonStateChange_FromUnavailableToHome_ShouldNotCallTurnOnLight() - { - CreateSut(); - - EmitStateChange(PersonEntityId, LightMonitorConsts.UnavailableState, LightMonitorConsts.PersonHomeState); - - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); - } - - [Fact] - public void PersonStateChange_FromUnknownToHome_ShouldNotCallTurnOnLight() - { - CreateSut(); - - EmitStateChange(PersonEntityId, LightMonitorConsts.UnknownState, LightMonitorConsts.PersonHomeState); - - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); - } - - [Fact] - public void PersonStateChange_FromNullToHome_ShouldNotCallTurnOnLight() - { - CreateSut(); - - EmitStateChange(PersonEntityId, null, LightMonitorConsts.PersonHomeState); - - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); - } - - [Fact] - public void PersonStateChange_FromNotHomeToNotHome_ShouldNotCallTurnOnLight() - { - CreateSut(); - - EmitStateChange(PersonEntityId, "not_home", "not_home"); - - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); - } - - [Fact] - public void SunStateChange_FromAboveHorizonToBelowHorizon_WhenSomeoneIsHome_ShouldCallTurnOnLight() + [Theory] + [MemberData(nameof(LightMonitorTestData.SunStateTurnOnCases), MemberType = typeof(LightMonitorTestData))] + public void SunStateChange_ShouldTurnOnLightOnlyWhenNewStateIsBelowHorizon(string? newState, bool shouldTurnOn) { _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true); CreateSut(); + EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, newState); + + VerifyTurnOn(shouldTurnOn); + } + + [Theory] + [MemberData(nameof(LightMonitorTestData.SunBelowHorizonTransitions), MemberType = typeof(LightMonitorTestData))] + public void SunStateChange_ToBelowHorizon_ShouldIgnoreOnlyRecoveryTransitions( + string? oldState, + bool shouldTurnOn) + { + _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true); + CreateSut(); + + EmitStateChange(SunEntityId, oldState, LightMonitorConsts.SunBelowHorizon); + + VerifyTurnOn(shouldTurnOn); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void SunStateChange_ToBelowHorizon_ShouldTurnOnLightOnlyWhenSomeoneIsHome(bool anyoneHome) + { + _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(anyoneHome); + CreateSut(); + EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon); - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once); + VerifyTurnOn(anyoneHome); + _presenceServiceMock.Verify(x => x.IsAnyoneHome(), Times.Once); } [Fact] - public void SunStateChange_FromAboveHorizonToBelowHorizon_WhenNoOneIsHome_ShouldNotCallTurnOnLight() + public void SunStateChange_WithNoConfiguredPersons_ShouldStillReactToTheSun() { - _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(false); - CreateSut(); + _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true); + CreateSut(LightMonitorTestData.CreateOptions(personEntityIds: [])); EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon); - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + VerifyTurnOn(true); } [Fact] - public void SunStateChange_FromUnavailableToBelowHorizon_ShouldNotCallTurnOnLight() + public void SunStateChange_WhenPresenceCheckThrows_ShouldKeepListening() + { + _presenceServiceMock.SetupSequence(x => x.IsAnyoneHome()) + .Throws(new InvalidOperationException("presence failed")) + .Returns(true); + CreateSut(); + + var act = () => EmitStateChange( + SunEntityId, + LightMonitorConsts.SunAboveHorizon, + LightMonitorConsts.SunBelowHorizon); + + act.Should().NotThrow(); + VerifyTurnOn(false); + + EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon); + VerifyTurnOn(true); + } + + [Fact] + public void PersonStateChange_WhenTurnOnLightThrows_ShouldKeepListening() + { + _lightControlServiceMock.SetupSequence(x => x.TurnOnLight()) + .Throws(new InvalidOperationException("light failed")) + .Pass(); + CreateSut(); + + var act = () => EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState); + + act.Should().NotThrow(); + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once); + + EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState); + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Exactly(2)); + } + + [Fact] + public void Constructor_WhenStateSubscriptionThrows_ShouldNotThrow() + { + var act = () => CreateSut(subscriptionException: new InvalidOperationException("state stream failed")); + + act.Should().NotThrow(); + VerifyTurnOn(false); + } + + [Fact] + public async Task InitializeAsync_ShouldCompleteWithoutThrowing() + { + var sut = CreateSut(); + + var act = () => sut.InitializeAsync(); + + await act.Should().NotThrowAsync(); + } + + [Fact] + public void StateChange_ForUnrelatedEntity_ShouldNotTurnOnLight() + { + CreateSut(); + + EmitStateChange("sensor.sun_next_dawn", LightMonitorConsts.UnavailableState, LightMonitorConsts.SunBelowHorizon); + + VerifyTurnOn(false); + } + + [Fact] + public void SunStateChange_WhenStateDoesNotActuallyChange_ShouldNotTurnOnLight() { _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true); CreateSut(); - EmitStateChange(SunEntityId, LightMonitorConsts.UnavailableState, LightMonitorConsts.SunBelowHorizon); + EmitStateChange(SunEntityId, LightMonitorConsts.SunBelowHorizon, LightMonitorConsts.SunBelowHorizon); - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + VerifyTurnOn(false); } [Fact] - public void SunStateChange_FromUnknownToBelowHorizon_ShouldNotCallTurnOnLight() - { - _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true); - CreateSut(); - - EmitStateChange(SunEntityId, LightMonitorConsts.UnknownState, LightMonitorConsts.SunBelowHorizon); - - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); - } - - [Fact] - public void SunStateChange_FromNullToBelowHorizon_ShouldNotCallTurnOnLight() - { - _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true); - CreateSut(); - - EmitStateChange(SunEntityId, null, LightMonitorConsts.SunBelowHorizon); - - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); - } - - [Fact] - public void SunStateChange_FromBelowHorizonToAboveHorizon_ShouldNotCallTurnOnLight() + public void PersonStateChange_WhenStateDoesNotActuallyChange_ShouldNotTurnOnLight() { CreateSut(); - EmitStateChange(SunEntityId, LightMonitorConsts.SunBelowHorizon, LightMonitorConsts.SunAboveHorizon); + EmitStateChange(PersonEntityId, LightMonitorConsts.PersonHomeState, LightMonitorConsts.PersonHomeState); - _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + VerifyTurnOn(false); } } diff --git a/LightMonitor.Manager.Tests/LightMonitorTestData.cs b/LightMonitor.Manager.Tests/LightMonitorTestData.cs new file mode 100644 index 0000000..646294f --- /dev/null +++ b/LightMonitor.Manager.Tests/LightMonitorTestData.cs @@ -0,0 +1,179 @@ +using LightMonitor.Models; +using LightMonitorManager.Models; +using NetDaemon.HassModel.Entities; + +namespace LightMonitor.Manager.Tests; + +/// +/// Deterministic, reusable fixtures for the LightMonitor tests. +/// Keeping the option builder, state builders and generated state tables here +/// avoids copy-pasted setup across the test classes. +/// +internal static class LightMonitorTestData +{ + public const string LightEntityId = "light.sonoff_1002214d40"; + public const string SunEntityId = "sun.sun"; + + public const string PrimaryPersonEntityId = "person.marius"; + public const string SecondaryPersonEntityId = "person.erika"; + public const string PhonePersonEntityId = "person.home_phone"; + + public static readonly string[] PersonEntityIds = + [ + PrimaryPersonEntityId, + SecondaryPersonEntityId, + PhonePersonEntityId + ]; + + private static readonly string?[] PresenceStates = + [ + LightMonitorConsts.PersonHomeState, + "not_home", + LightMonitorConsts.UnavailableState, + null + ]; + + /// + /// Builds light monitor options with production-compatible defaults. + /// + public static LightMonitorOptions CreateOptions( + string lightEntityId = LightEntityId, + string sunEntityId = SunEntityId, + IEnumerable? personEntityIds = null, + bool enabled = true) => new() + { + Enabled = enabled, + LightEntityId = lightEntityId, + SunEntityId = sunEntityId, + PersonEntityIds = personEntityIds?.ToArray() ?? [.. PersonEntityIds] + }; + + /// + /// Builds an carrying . + /// + public static EntityState CreateState(string? state) => new() { State = state }; + + /// + /// Builds an , or null when the entity has no state at all + /// (as returned by IHaContext.GetState for a missing entity). + /// + public static EntityState? CreateOptionalState(string? state) => + state is null ? null : CreateState(state); + + /// + /// Sun states that should (true) or should not (false) cause a light turn on. + /// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and + /// missing states must never turn the light on. + /// + public static TheoryData SunStateTurnOnCases { get; } = new() + { + { LightMonitorConsts.SunBelowHorizon, true }, + { LightMonitorConsts.SunBelowHorizon.ToUpperInvariant(), true }, + { "Below_Horizon", true }, + { LightMonitorConsts.SunAboveHorizon, false }, + { LightMonitorConsts.SunAboveHorizon.ToUpperInvariant(), false }, + { LightMonitorConsts.UnavailableState, false }, + { LightMonitorConsts.UnknownState, false }, + { string.Empty, false }, + { " ", false }, + { null, false } + }; + + /// + /// Light states evaluated while the sun is below the horizon. Only "on" (any casing) + /// suppresses the turn on call; everything else, including missing state, turns it on. + /// + public static TheoryData LightStateTurnOnCases { get; } = new() + { + { LightMonitorConsts.LightOnState, false }, + { LightMonitorConsts.LightOnState.ToUpperInvariant(), false }, + { "On", false }, + { "off", true }, + { "OFF", true }, + { LightMonitorConsts.UnavailableState, true }, + { LightMonitorConsts.UnknownState, true }, + { string.Empty, true }, + { " ", true }, + { null, true } + }; + + /// + /// Person states checked against the "arrived home" transition. + /// Only "home" in any casing counts. + /// + public static TheoryData PersonNewStateCases { get; } = new() + { + { LightMonitorConsts.PersonHomeState, true }, + { "HOME", true }, + { "Home", true }, + { "hOmE", true }, + { "not_home", false }, + { "not_home ", false }, + { LightMonitorConsts.UnavailableState, false }, + { LightMonitorConsts.UnknownState, false }, + { string.Empty, false }, + { " ", false }, + { null, false } + }; + + /// + /// Old person states for a transition to "home". Recovery from unavailable, unknown or + /// missing state must be ignored; every other old state is a real arrival. + /// + public static TheoryData PersonArrivalTransitions { get; } = new() + { + { "not_home", true }, + { "work", true }, + { string.Empty, true }, + { LightMonitorConsts.UnavailableState, false }, + { LightMonitorConsts.UnknownState, false }, + { null, false } + }; + + /// + /// Old sun states for a transition to "below_horizon". Recovery from unavailable, unknown + /// or missing state must be ignored. + /// + public static TheoryData SunBelowHorizonTransitions { get; } = new() + { + { LightMonitorConsts.SunAboveHorizon, true }, + { string.Empty, true }, + { LightMonitorConsts.UnavailableState, false }, + { LightMonitorConsts.UnknownState, false }, + { null, false } + }; + + /// + /// Every 4^3 = 64 combination of home / not_home / unavailable / missing state across the + /// three configured person entities. + /// + public static TheoryData PresenceStateMatrix { get; } = CreatePresenceStateMatrix(); + + /// + /// Person id configurations that resolve to "nobody tracked". + /// + public static TheoryData NoPersonEntityIdSets { get; } = new() + { + { [] }, + { [string.Empty] }, + { [" "] } + }; + + private static TheoryData CreatePresenceStateMatrix() + { + var matrix = new TheoryData(); + + foreach (var first in PresenceStates) + { + foreach (var second in PresenceStates) + { + foreach (var third in PresenceStates) + { + matrix.Add([first, second, third]); + } + } + } + + return matrix; + } +} diff --git a/LightMonitor.Manager.Tests/PresenceServiceTests.cs b/LightMonitor.Manager.Tests/PresenceServiceTests.cs index 05463a0..8a19e62 100644 --- a/LightMonitor.Manager.Tests/PresenceServiceTests.cs +++ b/LightMonitor.Manager.Tests/PresenceServiceTests.cs @@ -1,4 +1,5 @@ using FluentAssertions; +using LightMonitor.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; @@ -13,10 +14,7 @@ public class PresenceServiceTests { private readonly Mock _haContextMock = new(); - private readonly LightMonitorOptions _defaultOptions = new() - { - PersonEntityIds = ["person.marius", "person.erika", "person.home_phone"] - }; + private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions(); private PresenceService CreateService(LightMonitorOptions? options = null) { @@ -26,120 +24,106 @@ public class PresenceServiceTests Options.Create(options ?? _defaultOptions)); } - [Fact] - public void IsAnyoneHome_WhenOnePersonIsHome_ShouldReturnTrue() + private void SetupStates(IReadOnlyList personStates) { - _haContextMock.Setup(x => x.GetState("person.marius")) - .Returns(new EntityState { State = "home" }); - _haContextMock.Setup(x => x.GetState("person.erika")) - .Returns(new EntityState { State = "not_home" }); - _haContextMock.Setup(x => x.GetState("person.home_phone")) - .Returns(new EntityState { State = "not_home" }); - - var service = CreateService(); - - service.IsAnyoneHome().Should().BeTrue(); - } - - [Fact] - public void IsAnyoneHome_WhenAllPersonsAreHome_ShouldReturnTrue() - { - _haContextMock.Setup(x => x.GetState("person.marius")) - .Returns(new EntityState { State = "home" }); - _haContextMock.Setup(x => x.GetState("person.erika")) - .Returns(new EntityState { State = "home" }); - _haContextMock.Setup(x => x.GetState("person.home_phone")) - .Returns(new EntityState { State = "home" }); - - var service = CreateService(); - - service.IsAnyoneHome().Should().BeTrue(); - } - - [Fact] - public void IsAnyoneHome_WhenNoPersonIsHome_ShouldReturnFalse() - { - _haContextMock.Setup(x => x.GetState("person.marius")) - .Returns(new EntityState { State = "not_home" }); - _haContextMock.Setup(x => x.GetState("person.erika")) - .Returns(new EntityState { State = "not_home" }); - _haContextMock.Setup(x => x.GetState("person.home_phone")) - .Returns(new EntityState { State = "not_home" }); - - var service = CreateService(); - - service.IsAnyoneHome().Should().BeFalse(); - } - - [Fact] - public void IsAnyoneHome_WhenStateIsUnavailable_ShouldSkipAndReturnFalse() - { - _haContextMock.Setup(x => x.GetState("person.marius")) - .Returns(new EntityState { State = "unavailable" }); - _haContextMock.Setup(x => x.GetState("person.erika")) - .Returns(new EntityState { State = "unknown" }); - _haContextMock.Setup(x => x.GetState("person.home_phone")) - .Returns((EntityState?)null); - - var service = CreateService(); - - service.IsAnyoneHome().Should().BeFalse(); - } - - [Fact] - public void IsAnyoneHome_WhenStateIsNull_ShouldSkipAndReturnFalse() - { - _haContextMock.Setup(x => x.GetState("person.marius")) - .Returns((EntityState?)null); - _haContextMock.Setup(x => x.GetState("person.erika")) - .Returns((EntityState?)null); - _haContextMock.Setup(x => x.GetState("person.home_phone")) - .Returns((EntityState?)null); - - var service = CreateService(); - - service.IsAnyoneHome().Should().BeFalse(); - } - - [Fact] - public void IsAnyoneHome_WhenMixedStatesWithOneHome_ShouldReturnTrue() - { - _haContextMock.Setup(x => x.GetState("person.marius")) - .Returns(new EntityState { State = "unavailable" }); - _haContextMock.Setup(x => x.GetState("person.erika")) - .Returns(new EntityState { State = "home" }); - _haContextMock.Setup(x => x.GetState("person.home_phone")) - .Returns((EntityState?)null); - - var service = CreateService(); - - service.IsAnyoneHome().Should().BeTrue(); + for (var index = 0; index < personStates.Count; index++) + { + _haContextMock.Setup(x => x.GetState(LightMonitorTestData.PersonEntityIds[index])) + .Returns(LightMonitorTestData.CreateOptionalState(personStates[index])); + } } [Theory] - [InlineData("HOME")] - [InlineData("Home")] - [InlineData("home")] - public void IsAnyoneHome_CaseInsensitiveHomeState_ShouldReturnTrue(string homeState) + [MemberData(nameof(LightMonitorTestData.PresenceStateMatrix), MemberType = typeof(LightMonitorTestData))] + public void IsAnyoneHome_ForEveryPresenceCombination_ShouldReturnTrueOnlyWhenSomeoneIsHome(string?[] personStates) { - _haContextMock.Setup(x => x.GetState("person.marius")) - .Returns(new EntityState { State = homeState }); - _haContextMock.Setup(x => x.GetState("person.erika")) - .Returns(new EntityState { State = "not_home" }); - _haContextMock.Setup(x => x.GetState("person.home_phone")) - .Returns(new EntityState { State = "not_home" }); + SetupStates(personStates); - var service = CreateService(); + var expected = personStates.Any(state => + string.Equals(state, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)); - service.IsAnyoneHome().Should().BeTrue(); + CreateService().IsAnyoneHome().Should().Be(expected); + } + + [Theory] + [MemberData(nameof(LightMonitorTestData.PersonNewStateCases), MemberType = typeof(LightMonitorTestData))] + public void IsAnyoneHome_ShouldOnlyTreatHomeStateAsPresent(string? state, bool expected) + { + _haContextMock.Setup(x => x.GetState(LightMonitorTestData.PrimaryPersonEntityId)) + .Returns(LightMonitorTestData.CreateOptionalState(state)); + + var options = LightMonitorTestData.CreateOptions( + personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]); + + CreateService(options).IsAnyoneHome().Should().Be(expected); + } + + [Theory] + [MemberData(nameof(LightMonitorTestData.NoPersonEntityIdSets), MemberType = typeof(LightMonitorTestData))] + public void IsAnyoneHome_WithNoUsablePersonEntityIds_ShouldReturnFalse(string[] personEntityIds) + { + var options = LightMonitorTestData.CreateOptions(personEntityIds: personEntityIds); + + CreateService(options).IsAnyoneHome().Should().BeFalse(); } [Fact] - public void IsAnyoneHome_WithEmptyPersonList_ShouldReturnFalse() + public void IsAnyoneHome_WithEmptyPersonList_ShouldNotQueryAnyEntity() { - var options = new LightMonitorOptions { PersonEntityIds = [] }; - var service = CreateService(options); + var options = LightMonitorTestData.CreateOptions(personEntityIds: []); + + CreateService(options).IsAnyoneHome().Should().BeFalse(); + + _haContextMock.Verify(x => x.GetState(It.IsAny()), Times.Never); + } + + [Fact] + public void IsAnyoneHome_ShouldStopCheckingAfterTheFirstHomePerson() + { + _haContextMock.Setup(x => x.GetState(LightMonitorTestData.PrimaryPersonEntityId)) + .Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState)); + + CreateService().IsAnyoneHome().Should().BeTrue(); + + _haContextMock.Verify(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId), Times.Never); + _haContextMock.Verify(x => x.GetState(LightMonitorTestData.PhonePersonEntityId), Times.Never); + } + + [Fact] + public void IsAnyoneHome_ShouldCheckEveryConfiguredPersonWhenNobodyIsHome() + { + CreateService().IsAnyoneHome().Should().BeFalse(); + + foreach (var personEntityId in LightMonitorTestData.PersonEntityIds) + { + _haContextMock.Verify(x => x.GetState(personEntityId), Times.Once); + } + } + + [Fact] + public void IsAnyoneHome_ShouldIgnorePersonsThatAreNotConfigured() + { + _haContextMock.Setup(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId)) + .Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState)); + + var options = LightMonitorTestData.CreateOptions( + personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]); + + CreateService(options).IsAnyoneHome().Should().BeFalse(); + + _haContextMock.Verify(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId), Times.Never); + } + + [Fact] + public void IsAnyoneHome_WithDefaultOptions_ShouldQueryAllDefaultPersonEntities() + { + var service = CreateService(new LightMonitorOptions()); service.IsAnyoneHome().Should().BeFalse(); + + foreach (var personEntityId in LightMonitorConsts.DefaultPersonEntityIds) + { + _haContextMock.Verify(x => x.GetState(personEntityId), Times.Once); + } } } diff --git a/LightMonitor.Manager/LightMonitor.Manager.csproj b/LightMonitor.Manager/LightMonitor.Manager.csproj index 660f934..f188841 100644 --- a/LightMonitor.Manager/LightMonitor.Manager.csproj +++ b/LightMonitor.Manager/LightMonitor.Manager.csproj @@ -19,8 +19,8 @@ - - + + diff --git a/LightMonitor.Models/LightMonitor.Models.csproj b/LightMonitor.Models/LightMonitor.Models.csproj index 6b50cba..097c2f6 100644 --- a/LightMonitor.Models/LightMonitor.Models.csproj +++ b/LightMonitor.Models/LightMonitor.Models.csproj @@ -12,7 +12,7 @@ - + diff --git a/Mappings/Mappings.csproj b/Mappings/Mappings.csproj index fd262b8..c0e665d 100644 --- a/Mappings/Mappings.csproj +++ b/Mappings/Mappings.csproj @@ -7,7 +7,7 @@ - + diff --git a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs index 3a3e36a..86c7646 100644 --- a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs +++ b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs @@ -8,65 +8,93 @@ namespace NordPool.Manager.Tests; public class CheapestIntervalsFinderTests { - private readonly Mock> _loggerMock; + private static readonly DateTime DayStart = NordPoolTestData.DayStart; + private static readonly DateTime DeadlineEndOfDay = DayStart.AddDays(1); - public CheapestIntervalsFinderTests() - { - _loggerMock = new Mock>(); - } + private readonly Mock> _loggerMock = new(); - private CheapestIntervalsFinder CreateSut() - { - return new CheapestIntervalsFinder(_loggerMock.Object); - } + private CheapestIntervalsFinder CreateSut() => new(_loggerMock.Object); - private static NordPoolPrice CreatePricesForDay(DateTime dayStart, int intervalCount = 96) + private static NordPoolPrice CreatePricesForDay(DateTime dayStart, int intervalCount = NordPoolConsts.MaxDailyIntervals) { - var prices = new List(); - for (var i = 0; i < intervalCount; i++) + return new NordPoolPrice { - var start = dayStart.AddMinutes(i * 15); - prices.Add(new NordPoolDayPrice - { - Start = start, - End = start.AddMinutes(15), - Price = 4.93 + i * 0.22 - }); - } - - return new NordPoolPrice { Prices = prices }; + Prices = NordPoolTestData.CreateIntervals(intervalCount, i => 4.93 + i * 0.22, dayStart) + }; } private static NordPoolPrice CreatePricesWithValues(DateTime dayStart, params double[] priceValues) { - var prices = new List(); - for (var i = 0; i < priceValues.Length; i++) + return new NordPoolPrice { - var start = dayStart.AddMinutes(i * 15); - prices.Add(new NordPoolDayPrice - { - Start = start, - End = start.AddMinutes(15), - Price = priceValues[i] - }); - } - - return new NordPoolPrice { Prices = prices }; + Prices = NordPoolTestData.CreateIntervals(priceValues.Length, i => priceValues[i], dayStart) + }; } + private static CheapestIntervalResult Interval(int startSeconds, int endSeconds, double price = 5.0, int rank = 1) + { + return new CheapestIntervalResult + { + Start = DayStart.AddSeconds(startSeconds), + End = DayStart.AddSeconds(endSeconds), + Price = price, + Rank = rank + }; + } + + private const int Hour = 3_600; + private const int Quarter = 15 * 60; + #region FindCheapestIntervals + public static IEnumerable 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] + ]; + + [Theory] + [MemberData(nameof(FilteringCases))] + public void FindCheapestIntervals_ShouldApplyFiltersAndReturnExpectedCount( + string scenario, + double[] priceValues, + int requestedIntervals, + double priceCap, + double deadlineSeconds, + int expectedCount) + { + // Arrange + var sut = CreateSut(); + var prices = CreatePricesWithValues(DayStart, priceValues); + var deadline = DayStart.AddSeconds(deadlineSeconds); + + // Act + var result = sut.FindCheapestIntervals(prices, requestedIntervals, priceCap, deadline); + + // Assert + result.Should().HaveCount(expectedCount, $"scenario: {scenario}"); + result.Should().OnlyContain(r => r.End <= deadline && r.Price <= priceCap); + result.Select(r => r.Rank).Should().OnlyHaveUniqueItems(); + } + [Fact] public void FindCheapestIntervals_WithValidPrices_ShouldReturnRequestedCount() { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesForDay(dayStart); - var deadline = dayStart.AddDays(1); + var prices = CreatePricesForDay(DayStart); // Act - var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline); + var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay); // Assert result.Should().HaveCount(4); @@ -77,12 +105,10 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92, 5.63, 13.26); - var deadline = dayStart.AddDays(1); + var prices = CreatePricesWithValues(DayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92, 5.63, 13.26); // Act - var result = sut.FindCheapestIntervals(prices, 3, double.MaxValue, deadline); + var result = sut.FindCheapestIntervals(prices, 3, double.MaxValue, DeadlineEndOfDay); // Assert result.Should().HaveCount(3); @@ -97,18 +123,14 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 17.91, 8.96, 4.93, 13.26); - var deadline = dayStart.AddDays(1); + var prices = CreatePricesWithValues(DayStart, 17.91, 8.96, 4.93, 13.26); // Act - var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline); + var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay); // Assert - var cheapest = result.Single(r => r.Price == 4.93); - cheapest.Rank.Should().Be(1); - var secondCheapest = result.Single(r => r.Price == 8.96); - secondCheapest.Rank.Should().Be(2); + result.Single(r => r.Price == 4.93).Rank.Should().Be(1); + result.Single(r => r.Price == 8.96).Rank.Should().Be(2); } [Fact] @@ -116,83 +138,28 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96); - var deadline = dayStart.AddDays(1); + var prices = CreatePricesWithValues(DayStart, 17.91, 6.20, 12.50, 4.93, 8.96); // Act - var result = sut.FindCheapestIntervals(prices, 3, double.MaxValue, deadline); + var result = sut.FindCheapestIntervals(prices, 3, double.MaxValue, DeadlineEndOfDay); // Assert result.Should().BeInAscendingOrder(r => r.Start); } - [Fact] - public void FindCheapestIntervals_WithDeadline_ShouldExcludeIntervalsEndingAfterDeadline() - { - // Arrange - var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 2.50, 1.80, 3.20); - var deadline = dayStart.AddMinutes(75); // 1h15m = covers intervals 0-4 (end of interval 4 = 75min) - - // Act - var result = sut.FindCheapestIntervals(prices, 8, double.MaxValue, deadline); - - // Assert - result.Should().HaveCount(5); - result.Should().OnlyContain(r => r.End <= deadline); - } - - [Fact] - public void FindCheapestIntervals_WithPriceCap_ShouldExcludeExpensiveIntervals() - { - // Arrange - var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92); - var deadline = dayStart.AddDays(1); - - // Act - var result = sut.FindCheapestIntervals(prices, 10, 10.0, deadline); - - // Assert - result.Should().HaveCount(3); - result.Should().OnlyContain(r => r.Price <= 10.0); - } - [Fact] public void FindCheapestIntervals_WithMaxPriceCap_ShouldIncludeAllIntervalsBeforeDeadline() - { - // Arrange: realistic ct/kWh samples — with double.MaxValue all six intervals qualify - var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92); - var deadline = dayStart.AddDays(1); - - // Act - var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline); - - // Assert: all 6 intervals are eligible, we take 4 cheapest by price - result.Should().HaveCount(4); - result.Select(r => r.Price).OrderBy(p => p).Should().ContainInOrder(4.93, 6.20, 8.96, 12.50); - } - - [Fact] - public void FindCheapestIntervals_WithDeadlineAndPriceCap_ShouldApplyBothFilters() { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 2.50); - var deadline = dayStart.AddMinutes(75); + var prices = CreatePricesWithValues(DayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92); // Act - var result = sut.FindCheapestIntervals(prices, 2, 10.0, deadline); + var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay); - // Assert - result.Should().HaveCount(2); - result.Should().OnlyContain(r => r.End <= deadline && r.Price <= 10.0); + // Assert — all six intervals are eligible, the four cheapest are taken + result.Should().HaveCount(4); + result.Select(r => r.Price).OrderBy(p => p).Should().ContainInOrder(4.93, 6.20, 8.96, 12.50); } [Fact] @@ -201,10 +168,9 @@ public class CheapestIntervalsFinderTests // Arrange var sut = CreateSut(); var prices = new NordPoolPrice { Prices = null }; - var deadline = DateTime.Today.AddDays(1); // Act - var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline); + var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay); // Assert result.Should().BeEmpty(); @@ -216,110 +182,67 @@ public class CheapestIntervalsFinderTests // Arrange var sut = CreateSut(); var prices = new NordPoolPrice { Prices = new List() }; - var deadline = DateTime.Today.AddDays(1); // Act - var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline); + var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay); // Assert result.Should().BeEmpty(); } [Fact] - public void FindCheapestIntervals_WithZeroIntervals_ShouldReturnEmpty() + public void FindCheapestIntervals_WithEqualPrices_ShouldPreferEarliestStart() { - // Arrange + // Arrange — four equally priced intervals, only two are requested var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesForDay(dayStart); - var deadline = dayStart.AddDays(1); + var prices = CreatePricesWithValues(DayStart, 5.0, 5.0, 5.0, 5.0); // Act - var result = sut.FindCheapestIntervals(prices, 0, double.MaxValue, deadline); + var result = sut.FindCheapestIntervals(prices, 2, double.MaxValue, DeadlineEndOfDay); - // Assert - result.Should().BeEmpty(); + // Assert — tie-break is by Start ascending + result.Should().HaveCount(2); + result.Select(r => r.Start).Should().ContainInOrder(DayStart, DayStart.AddMinutes(15)); + result.Select(r => r.Rank).Should().ContainInOrder(1, 2); } [Fact] - public void FindCheapestIntervals_WithNegativeIntervals_ShouldReturnEmpty() + public void FindCheapestIntervals_WithNegativePrices_ShouldRankCheapestFirst() { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesForDay(dayStart); - var deadline = dayStart.AddDays(1); + var prices = CreatePricesWithValues(DayStart, -2.10, 0.50, -7.40, 3.30); // Act - var result = sut.FindCheapestIntervals(prices, -1, double.MaxValue, deadline); + var result = sut.FindCheapestIntervals(prices, 2, double.MaxValue, DeadlineEndOfDay); - // Assert - result.Should().BeEmpty(); + // Assert — results are chronological, ranks still follow price order + result.Should().HaveCount(2); + result.Select(r => r.Price).Should().ContainInOrder(-2.10, -7.40); + result.Single(r => r.Price == -7.40).Rank.Should().Be(1); + result.Single(r => r.Price == -2.10).Rank.Should().Be(2); } [Fact] - public void FindCheapestIntervals_WhenFewerAvailableThanRequested_ShouldReturnAllAvailable() + public void FindCheapestIntervals_WithDuplicateIntervals_ShouldKeepBoth() { - // Arrange + // Arrange — duplicate payload entries are not deduplicated var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 6.20, 8.96); - var deadline = dayStart.AddDays(1); + var prices = new NordPoolPrice + { + Prices = new List + { + new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }, + new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 } + } + }; // Act - var result = sut.FindCheapestIntervals(prices, 10, double.MaxValue, deadline); + var result = sut.FindCheapestIntervals(prices, 2, double.MaxValue, DeadlineEndOfDay); // Assert result.Should().HaveCount(2); - } - - [Fact] - public void FindCheapestIntervals_AllPricesAboveCap_ShouldReturnEmpty() - { - // Arrange - var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 17.91, 24.92, 22.44); - var deadline = dayStart.AddDays(1); - - // Act - var result = sut.FindCheapestIntervals(prices, 4, 10.0, deadline); - - // Assert - result.Should().BeEmpty(); - } - - [Fact] - public void FindCheapestIntervals_AllIntervalsAfterDeadline_ShouldReturnEmpty() - { - // Arrange - var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 12, 0, 0); - var prices = CreatePricesWithValues(dayStart, 4.93, 5.63, 6.20); - var deadline = new DateTime(2026, 3, 31, 10, 0, 0); - - // Act - var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline); - - // Assert - result.Should().BeEmpty(); - } - - [Fact] - public void FindCheapestIntervals_AllSamePrice_ShouldReturnRequestedCount() - { - // Arrange - var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); - var prices = CreatePricesWithValues(dayStart, 12.50, 12.50, 12.50, 12.50, 12.50); - var deadline = dayStart.AddDays(1); - - // Act - var result = sut.FindCheapestIntervals(prices, 3, double.MaxValue, deadline); - - // Assert - result.Should().HaveCount(3); - result.Should().OnlyContain(r => r.Price == 12.50); + result.Select(r => r.Rank).Should().BeEquivalentTo([1, 2]); } [Fact] @@ -327,117 +250,110 @@ public class CheapestIntervalsFinderTests { // Arrange var sut = CreateSut(); - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0); var prices = new NordPoolPrice { Prices = new List { - new() { Start = dayStart, End = dayStart.AddMinutes(15), Price = 8.96 }, - new() { Start = dayStart.AddMinutes(15), End = dayStart.AddMinutes(30), Price = null }, - new() { Start = dayStart.AddMinutes(30), End = dayStart.AddMinutes(45), Price = 6.20 }, - new() { Start = null, End = dayStart.AddMinutes(60), Price = 4.93 }, - new() { Start = dayStart.AddMinutes(60), End = null, Price = 5.63 } + new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 }, + new() { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null }, + new() { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 }, + new() { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 }, + new() { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 } } }; - var deadline = dayStart.AddDays(1); // Act - var result = sut.FindCheapestIntervals(prices, 10, double.MaxValue, deadline); + var result = sut.FindCheapestIntervals(prices, 10, double.MaxValue, DeadlineEndOfDay); // Assert result.Should().HaveCount(2); } + [Fact] + public void FindCheapestIntervals_WithGeneratedFullDay_ShouldSelectExactlyTheCheapestIntervals() + { + // Arrange — deterministic 96-interval dataset with negative, cheap and expensive prices + var sut = CreateSut(); + var prices = new NordPoolPrice { Prices = NordPoolTestData.CreateGeneratedDay() }; + const int requestedIntervals = 8; + const double priceCap = 12.0; + + var expected = prices.Prices! + .Where(p => p.Price <= priceCap) + .OrderBy(p => p.Price) + .ThenBy(p => p.Start) + .Take(requestedIntervals) + .OrderBy(p => p.Start) + .ToList(); + + // Act + var result = sut.FindCheapestIntervals(prices, requestedIntervals, priceCap, DeadlineEndOfDay); + + // Assert + expected.Should().HaveCount(requestedIntervals); + result.Should().HaveCount(requestedIntervals); + result.Select(r => r.Start).Should().ContainInOrder(expected.Select(p => p.Start!.Value)); + result.Should().BeInAscendingOrder(r => r.Start); + result.Select(r => r.Rank).Should().BeEquivalentTo(Enumerable.Range(1, requestedIntervals)); + result.Should().OnlyContain(r => r.Price <= priceCap); + } + #endregion #region IsCurrentIntervalCheap - [Fact] - public void IsCurrentIntervalCheap_WhenWithinInterval_ShouldReturnTrue() + public static IEnumerable 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(), false] + ]; + + [Theory] + [MemberData(nameof(CurrentIntervalCases))] + public void IsCurrentIntervalCheap_ShouldMatchIntervalBounds( + string scenario, + int nowSeconds, + CheapestIntervalResult[] intervals, + bool expected) { // Arrange var sut = CreateSut(); - var now = new DateTime(2026, 3, 31, 10, 7, 0); - var intervals = new List - { - new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 } - }; + var now = DayStart.AddSeconds(nowSeconds); // Act var result = sut.IsCurrentIntervalCheap(intervals, now); // Assert - result.Should().BeTrue(); + result.Should().Be(expected, $"scenario: {scenario}"); } [Fact] - public void IsCurrentIntervalCheap_WhenExactlyAtStart_ShouldReturnTrue() + public void IsCurrentIntervalCheap_WithGeneratedDay_ShouldBeTrueOnlyForSelectedQuarters() { - // Arrange + // Arrange — pick the four cheapest intervals of a generated day and probe every quarter var sut = CreateSut(); - var now = new DateTime(2026, 3, 31, 10, 0, 0); - var intervals = new List + var prices = new NordPoolPrice { Prices = NordPoolTestData.CreateGeneratedDay() }; + var cheapest = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay); + + for (var quarter = 0; quarter < NordPoolConsts.MaxDailyIntervals; quarter++) { - new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 } - }; + var now = DayStart.AddMinutes(quarter * NordPoolConsts.MinutesPerInterval); + var expected = cheapest.Any(i => now >= i.Start && now < i.End); - // Act - var result = sut.IsCurrentIntervalCheap(intervals, now); + // Act + var result = sut.IsCurrentIntervalCheap(cheapest, now); - // Assert - result.Should().BeTrue(); - } - - [Fact] - public void IsCurrentIntervalCheap_WhenExactlyAtEnd_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - var now = new DateTime(2026, 3, 31, 10, 15, 0); - var intervals = new List - { - new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 } - }; - - // Act - var result = sut.IsCurrentIntervalCheap(intervals, now); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void IsCurrentIntervalCheap_WhenOutsideAllIntervals_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - var now = new DateTime(2026, 3, 31, 12, 0, 0); - var intervals = new List - { - new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 }, - new() { Start = new DateTime(2026, 3, 31, 14, 0, 0), End = new DateTime(2026, 3, 31, 14, 15, 0), Price = 6.20, Rank = 2 } - }; - - // Act - var result = sut.IsCurrentIntervalCheap(intervals, now); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void IsCurrentIntervalCheap_WithEmptyList_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - var now = DateTime.UtcNow; - var intervals = new List(); - - // Act - var result = sut.IsCurrentIntervalCheap(intervals, now); - - // Assert - result.Should().BeFalse(); + // Assert + result.Should().Be(expected, $"quarter {quarter} at {now:O}"); + } } #endregion diff --git a/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs b/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs index 1a2f7ee..dd32772 100644 --- a/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs +++ b/NordPool.Manager.Tests/CompactNordPoolDayPriceTests.cs @@ -115,14 +115,20 @@ public class CompactNordPoolDayPriceTests json.Should().Be($"[{TestStartEpoch},{TestEndEpoch},null]"); } - [Fact] - public void JsonDeserialization_ShouldRoundTrip() + [Theory] + [InlineData(17.91)] + [InlineData(-12.34)] + [InlineData(0.0)] + [InlineData(0.001)] + [InlineData(17.9159)] + [InlineData(null)] + public void JsonDeserialization_ShouldRoundTripPrice(double? price) { var original = new CompactNordPoolDayPrice { Start = TestStartEpoch, End = TestEndEpoch, - Price = 17.91 + Price = price }; var json = JsonSerializer.Serialize(original); @@ -155,28 +161,33 @@ public class CompactNordPoolDayPriceTests act.Should().Throw(); } - [Fact] - public void JsonDeserialization_EmptyArray_ShouldThrowJsonException() - { - var act = () => JsonSerializer.Deserialize("[]"); + public static IEnumerable 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}"] + ]; - act.Should().Throw(); + [Theory] + [MemberData(nameof(InvalidJsonPayloads))] + public void JsonDeserialization_WithInvalidPayload_ShouldThrowJsonException(string scenario, string json) + { + var act = () => JsonSerializer.Deserialize(json); + + act.Should().Throw($"scenario: {scenario}"); } [Fact] - public void JsonDeserialization_TooFewElements_ShouldThrowJsonException() + public void JsonSerialization_EmptyList_ShouldProduceEmptyArray() { - var act = () => JsonSerializer.Deserialize("[1,2]"); + var json = JsonSerializer.Serialize(new List()); - act.Should().Throw(); - } - - [Fact] - public void JsonDeserialization_InvalidTokenType_ShouldThrowJsonException() - { - var act = () => JsonSerializer.Deserialize("[\"abc\",2,3]"); - - act.Should().Throw(); + json.Should().Be("[]"); } [Fact] @@ -216,23 +227,53 @@ public class CompactNordPoolDayPriceTests result.Should().BeEmpty(); } + [Fact] + public void ToCompact_WithGeneratedDay_ShouldPreserveOrderAndCount() + { + var prices = NordPoolTestData.CreateIntervals(96, i => 4.93 + i * 0.22); + + var result = prices.ToCompact(); + + result.Should().HaveCount(96); + result.Should().BeInAscendingOrder(p => p.Start); + result[0].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart).ToUnixTimeSeconds()); + result[95].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval)).ToUnixTimeSeconds()); + } + + [Fact] + public void JsonSerialization_WithGeneratedDay_ShouldRoundTripAllEntries() + { + var compact = NordPoolTestData.CreateGeneratedDay().ToCompact(); + + var json = JsonSerializer.Serialize(compact); + var roundTripped = JsonSerializer.Deserialize>(json); + + roundTripped.Should().NotBeNull(); + roundTripped!.Should().HaveCount(compact.Count); + roundTripped.Should().BeEquivalentTo(compact); + } + + [Fact] + public void ToCompact_ShouldPreserveNullPriceAndNullTimestamps() + { + var prices = new List + { + new() { Start = null, End = null, Price = null } + }; + + var result = prices.ToCompact(); + + result.Should().ContainSingle(); + result[0].Start.Should().Be(0L); + result[0].End.Should().Be(0L); + result[0].Price.Should().BeNull(); + } + [Fact] public void SerializedSize_WithMaxEntries_ShouldBeUnderHaAttributeLimit() { const int haAttributeByteLimitBytes = 16_384; - var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); - var prices = new List(); - - for (var i = 0; i < MaxExpectedPriceEntries; i++) - { - var start = dayStart.AddMinutes(i * MinutesPerInterval); - prices.Add(new NordPoolDayPrice - { - Start = start, - End = start.AddMinutes(MinutesPerInterval), - Price = 4.93 + i * 0.22 - }); - } + var prices = NordPoolTestData.CreateIntervals(MaxExpectedPriceEntries, i => 4.93 + i * 0.22); var compactPrices = prices.ToCompact(); var attributePayload = new diff --git a/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj b/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj index 68cf51c..4c0f2b8 100644 --- a/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj +++ b/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj @@ -8,19 +8,19 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + diff --git a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs index 004d284..c838598 100644 --- a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs @@ -130,6 +130,20 @@ public class NordPoolEntityServiceTests _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(7)); } + [Fact] + public async Task CreateEntitiesAsync_WithNullUnitOfMeasurement_ShouldStillCreateAllEntities() + { + // Arrange + _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) + .Returns(Task.CompletedTask); + + // Act + await _sut.CreateEntitiesAsync(null); + + // Assert + _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(7)); + } + #endregion #region CleanupEntitiesAsync @@ -421,106 +435,85 @@ public class NordPoolEntityServiceTests Times.Once); } - [Fact] - public async Task UpdateEntitiesAsync_WithTodayAndTomorrowPrices_ShouldUpdateCombinedSensor() + public static IEnumerable MergedPriceScenarios() { - // Arrange var todayStart = new DateTime(2026, 3, 31, 6, 0, 0, DateTimeKind.Utc); var tomorrowStart = new DateTime(2026, 4, 1, 6, 0, 0, DateTimeKind.Utc); - var todayPrice = new NordPoolPrice - { - Prices = - [ - new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 }, - new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 12.50 } - ] - }; - var tomorrowPrice = new NordPoolPrice - { - Prices = - [ - new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 } - ] - }; - var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice); - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + yield return + [ + "today and tomorrow with null-start entry filtered", + new NordPoolPrice + { + Prices = + [ + new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 }, + new NordPoolDayPrice { Start = null, End = todayStart.AddHours(3).AddMinutes(15), Price = 1.0 } + ] + }, + new NordPoolPrice + { + Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] + }, + 2 + ]; - // Act - await _sut.UpdateEntitiesAsync(context); + yield return + [ + "only today", + new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 }] }, + new NordPoolPrice { Prices = [] }, + 1 + ]; - // Assert - state is update time in yyyy-MM-dd HH:mm:ss format - _entityManagerMock.Verify( - em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => - s.Length > 0 && s.Contains('-') && s.Contains(':') && s != "0" && s != "3")), - Times.Once); + yield return + [ + "only tomorrow", + new NordPoolPrice { Prices = [] }, + new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] }, + 1 + ]; - // Assert - attributes contain merged, sorted prices (today 06:00, today 08:00, tomorrow 06:00) - _entityManagerMock.Verify( - em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(o => - o.GetType().GetProperty("prices_count")!.GetValue(o)!.Equals(3))), - Times.Once); + 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]; } - [Fact] - public async Task UpdateEntitiesAsync_WithOnlyTodayPrices_ShouldUpdateCombinedSensor() + [Theory] + [MemberData(nameof(MergedPriceScenarios))] + public async Task UpdateEntitiesAsync_WithMergedPriceScenarios_ShouldPublishSortedFilteredPrices( + string scenario, + NordPoolPrice? todayPrice, + NordPoolPrice? tomorrowPrice, + int expectedMergedCount) { // Arrange - var todayPrice = new NordPoolPrice - { - Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddMinutes(15), Price = 17.91 }] - }; - var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] }); - + object? capturedAttributes = null; _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) + .Callback((_, attrs) => capturedAttributes = attrs) .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny())) + .Returns(Task.CompletedTask); + + var context = CreateDefaultContext() with + { + TodayNordPoolPrice = todayPrice, + TomorrowNordPoolPrice = tomorrowPrice + }; // Act await _sut.UpdateEntitiesAsync(context); // Assert - _entityManagerMock.Verify( - em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => - s.Length > 0 && s.Contains('-') && s != "0")), - Times.Once); - _entityManagerMock.Verify( - em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(o => - o.GetType().GetProperty("prices_count")!.GetValue(o)!.Equals(1))), - Times.Once); - } - - [Fact] - public async Task UpdateEntitiesAsync_WithOnlyTomorrowPrices_ShouldUpdateCombinedSensor() - { - // Arrange - var tomorrowPrice = new NordPoolPrice - { - Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow.AddDays(1), End = DateTime.UtcNow.AddDays(1).AddMinutes(15), Price = 18.71 }] - }; - var context = CreateDefaultContext(todayPrice: new NordPoolPrice { Prices = [] }, tomorrowPrice: tomorrowPrice); - - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - - // Act - await _sut.UpdateEntitiesAsync(context); - - // Assert - _entityManagerMock.Verify( - em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => - s.Length > 0 && s.Contains('-') && s != "0")), - Times.Once); - _entityManagerMock.Verify( - em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(o => - o.GetType().GetProperty("prices_count")!.GetValue(o)!.Equals(1))), - Times.Once); + capturedAttributes.Should().NotBeNull(); + var attributes = capturedAttributes!; + var type = attributes.GetType(); + var prices = (List)type.GetProperty("prices")!.GetValue(attributes)!; + prices.Should().HaveCount(expectedMergedCount, $"scenario: {scenario}"); + prices.Select(p => p.Start).Should().BeInAscendingOrder(); + type.GetProperty("prices_count")!.GetValue(attributes).Should().Be(expectedMergedCount); } [Fact] @@ -600,5 +593,272 @@ public class NordPoolEntityServiceTests $"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit"); } + [Theory] + [InlineData(17.91, "17.91")] + [InlineData(0.0, "0.00")] + [InlineData(-5.25, "-5.25")] + [InlineData(1234.5, "1234.50")] + [InlineData(17.916, "17.92")] + public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price, string expected) + { + // Arrange + var context = CreateDefaultContext(currentPrice: price); + + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", expected), Times.Once); + } + + [Fact] + public async Task UpdateEntitiesAsync_CurrentPriceAttributes_ShouldReflectContext() + { + // Arrange + object? capturedAttributes = null; + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny())) + .Callback((_, attrs) => capturedAttributes = attrs) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_current_price"), It.IsAny())) + .Returns(Task.CompletedTask); + + var context = CreateDefaultContext() with + { + UnitOfMeasurement = "EUR/MWh", + DayQuartersIndex = 42, + LastApiUpdateDate = null, + UsingCachedData = true + }; + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + capturedAttributes.Should().NotBeNull(); + var attributes = capturedAttributes!; + var type = attributes.GetType(); + type.GetProperty("unit_of_measurement")!.GetValue(attributes).Should().Be("EUR/MWh"); + type.GetProperty("device_class")!.GetValue(attributes).Should().Be("monetary"); + type.GetProperty("state_class")!.GetValue(attributes).Should().Be("measurement"); + type.GetProperty("last_api_fetch")!.GetValue(attributes).Should().BeNull(); + type.GetProperty("using_cached_data")!.GetValue(attributes).Should().Be(true); + type.GetProperty("current_quarter_index")!.GetValue(attributes).Should().Be(42); + type.GetProperty("last_updated")!.GetValue(attributes).Should().NotBeNull(); + } + + [Fact] + public async Task UpdateEntitiesAsync_CheapestIntervalsAttributes_ShouldSummarizeSchedule() + { + // Arrange + object? capturedAttributes = null; + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny())) + .Callback((_, attrs) => capturedAttributes = attrs) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny())) + .Returns(Task.CompletedTask); + + var first = new CheapestIntervalResult + { + Start = new DateTime(2026, 3, 31, 22, 0, 0, DateTimeKind.Utc), + End = new DateTime(2026, 3, 31, 22, 15, 0, DateTimeKind.Utc), + Price = 4.93, + Rank = 1 + }; + var second = new CheapestIntervalResult + { + Start = new DateTime(2026, 3, 31, 23, 0, 0, DateTimeKind.Utc), + End = new DateTime(2026, 3, 31, 23, 15, 0, DateTimeKind.Utc), + Price = 5.63, + Rank = 2 + }; + + var context = CreateDefaultContext() with + { + CheapestIntervals = [first, second], + ConfiguredHours = 0.5, + ConfiguredIntervalCount = 2, + ConfiguredPriceCap = 25.0, + SkipPriceCap = true, + ConfiguredReadyBy = "06:30", + IsNowCheap = true, + NextCheapIntervalStart = first.Start + }; + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "2"), Times.Once); + + capturedAttributes.Should().NotBeNull(); + var attributes = capturedAttributes!; + var type = attributes.GetType(); + ((IEnumerable)type.GetProperty("intervals")!.GetValue(attributes)!).Should().HaveCount(2); + type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(30); + type.GetProperty("is_now_cheap")!.GetValue(attributes).Should().Be(true); + type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().Be(first.Start.ToString("O")); + type.GetProperty("skip_price_cap")!.GetValue(attributes).Should().Be(true); + type.GetProperty("configured_hours")!.GetValue(attributes).Should().Be(0.5); + type.GetProperty("configured_interval_count")!.GetValue(attributes).Should().Be(2); + type.GetProperty("configured_price_cap")!.GetValue(attributes).Should().Be(25.0); + type.GetProperty("configured_ready_by")!.GetValue(attributes).Should().Be("06:30"); + } + + [Fact] + public async Task UpdateEntitiesAsync_WhenCheapestIntervalsAreNull_ShouldPublishEmptyIntervals() + { + // Arrange + object? capturedAttributes = null; + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny())) + .Callback((_, attrs) => capturedAttributes = attrs) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny())) + .Returns(Task.CompletedTask); + + var context = CreateDefaultContext() with { CheapestIntervals = null }; + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once); + + capturedAttributes.Should().NotBeNull(); + var attributes = capturedAttributes!; + var type = attributes.GetType(); + ((IEnumerable)type.GetProperty("intervals")!.GetValue(attributes)!).Should().BeEmpty(); + type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(0); + type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().BeNull(); + } + + [Fact] + public async Task UpdateEntitiesAsync_MergedPrices_ShouldDropEntriesWithoutStartAndSortByStart() + { + // Arrange + object? capturedAttributes = null; + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) + .Callback((_, attrs) => capturedAttributes = attrs) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny())) + .Returns(Task.CompletedTask); + + var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); + var todayPrice = new NordPoolPrice + { + Prices = + [ + new NordPoolDayPrice { Start = dayStart.AddHours(2), End = dayStart.AddHours(2).AddMinutes(15), Price = 17.91 }, + new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 } + ] + }; + var tomorrowPrice = new NordPoolPrice + { + Prices = + [ + new NordPoolDayPrice { Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 } + ] + }; + var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice); + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + capturedAttributes.Should().NotBeNull(); + var attributes = capturedAttributes!; + var type = attributes.GetType(); + var prices = (List)type.GetProperty("prices")!.GetValue(attributes)!; + prices.Should().HaveCount(2); + prices.Select(p => p.Start).Should().BeInAscendingOrder(); + type.GetProperty("prices_count")!.GetValue(attributes).Should().Be(2); + } + + [Fact] + public async Task UpdateEntitiesAsync_WhenMergedPricesExceedExpectedMaximum_ShouldLogWarning() + { + // Arrange + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + + var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); + var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc); + var todayPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice + { + Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), + End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), + Price = 10.0 + }).ToList(); + var tomorrowPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice + { + Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval), + End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval), + Price = 10.0 + }).ToList(); + + var context = CreateDefaultContext( + todayPrice: new NordPoolPrice { Prices = todayPrices }, + tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices }); + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + _loggerMock.Verify( + l => l.Log( + LogLevel.Warning, + It.IsAny(), + It.Is((state, _) => state != null && state.ToString()!.Contains("exceeds expected maximum")), + It.IsAny(), + It.IsAny>()), + Times.Once); + } + + #endregion + + #region Cancellation + + public static IEnumerable CancelledOperations() + { + var cancelled = new CancellationToken(canceled: true); + var context = CreateDefaultContext(); + + yield return ["create entities", (Func)(sut => sut.CreateEntitiesAsync("EUR/kWh", cancelled))]; + yield return ["reset entities", (Func)(sut => sut.ResetEntitiesAsync(cancelled))]; + yield return ["update entities", (Func)(sut => sut.UpdateEntitiesAsync(context, cancelled))]; + yield return ["cleanup entities", (Func)(sut => sut.CleanupEntitiesAsync(cancelled))]; + } + + [Theory] + [MemberData(nameof(CancelledOperations))] + public async Task Operation_WithCancelledToken_ShouldThrowAndNotWriteAnything( + string scenario, + Func operation) + { + // Act + var act = () => operation(_sut); + + // Assert + await act.Should().ThrowAsync($"scenario: {scenario}"); + _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Never); + } + #endregion } diff --git a/NordPool.Manager.Tests/NordPoolInitTests.cs b/NordPool.Manager.Tests/NordPoolInitTests.cs index 1f0d988..a6a61b6 100644 --- a/NordPool.Manager.Tests/NordPoolInitTests.cs +++ b/NordPool.Manager.Tests/NordPoolInitTests.cs @@ -41,7 +41,7 @@ public class NordPoolInitTests _entityServiceMock.Setup(e => e.CreateEntitiesAsync(It.IsAny())).Returns(Task.CompletedTask); _entityServiceMock.Setup(e => e.ResetEntitiesAsync()).Returns(Task.CompletedTask); _entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny())).Returns(Task.CompletedTask); - _priceServiceMock.Setup(p => p.UpdateCurrentPrice()).Returns(0.0); + _priceServiceMock.Setup(p => p.GetCurrentPrice()).Returns(0.0); _priceServiceMock.Setup(p => p.ShouldFetchNewPrices(It.IsAny())).Returns(false); _priceServiceMock.SetupGet(p => p.DayQuartersIndex).Returns(0); _priceServiceMock.SetupGet(p => p.TodayNordPoolPrice).Returns((NordPoolPrice?)null); @@ -88,38 +88,36 @@ public class NordPoolInitTests sut.Should().NotBeNull(); } - [Fact] - public async Task CleanupEntitiesAsync_ShouldDelegateToEntityService() + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task InitializeAsync_ShouldRespectCleanupOnStartupSetting(bool cleanupEntitiesOnStartup) { - // Arrange - var sut = CreateSut(); - _entityServiceMock.Setup(es => es.CleanupEntitiesAsync(It.IsAny())) - .Returns(Task.CompletedTask); - - // Act - await sut.CleanupEntitiesAsync(); - - // Assert - _entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny()), Times.Once); - } - - [Fact] - public async Task InitializeAsync_WhenCleanupEntitiesOnStartupIsTrue_ShouldCallEntityCleanup() - { - var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = true }); + var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = cleanupEntitiesOnStartup }); await sut.InitializeAsync(); - _entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny()), Times.AtLeastOnce); + // The constructor also starts the same init flow in the background, so calls may happen more than once. + _entityServiceMock.Verify( + es => es.CleanupEntitiesAsync(It.IsAny()), + cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never()); + _entityServiceMock.Verify(es => es.CreateEntitiesAsync(It.IsAny(), It.IsAny()), Times.AtLeastOnce); + _entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny()), Times.AtLeastOnce); + _entityServiceMock.Verify(es => es.UpdateEntitiesAsync(It.IsAny(), It.IsAny()), Times.AtLeastOnce); } [Fact] - public async Task InitializeAsync_WhenCleanupEntitiesOnStartupIsFalse_ShouldNotCallEntityCleanup() + public async Task InitializeAsync_WhenCreatingEntitiesFails_ShouldRethrow() { var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = false }); + _entityServiceMock + .Setup(es => es.CreateEntitiesAsync(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("create failed")); - await sut.InitializeAsync(); + var act = () => sut.InitializeAsync(); - _entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny()), Times.Never); + await act.Should().ThrowAsync().WithMessage("create failed"); + _entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny()), Times.Never); + _entityServiceMock.Verify(es => es.UpdateEntitiesAsync(It.IsAny(), It.IsAny()), Times.Never); } } diff --git a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs index 77f65a0..0ba1658 100644 --- a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs @@ -154,6 +154,14 @@ public class NordPoolPriceServiceTests [InlineData(200.0, 24.2)] [InlineData(0.0, 0.0)] [InlineData(123.456, 14.94)] + [InlineData(1.0, 0.12)] + [InlineData(10.0, 1.21)] + [InlineData(250.0, 30.25)] + [InlineData(500.0, 60.5)] + [InlineData(1000.0, 121.0)] + [InlineData(-1000.0, -121.0)] + [InlineData(1234.5, 149.37)] + [InlineData(0.01, 0.0)] public void PriceCorrection_ShouldCalculateCorrectPrice(double mwPrice, double expectedCentsPrice) { // Act @@ -459,7 +467,8 @@ public class NordPoolPriceServiceTests _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; // Act - var result = _sut.UpdateCurrentPrice(); + _sut.UpdateCurrentPrice(); + var result = _sut.GetCurrentPrice(); // Assert result.Should().BeGreaterThan(0); @@ -469,7 +478,8 @@ public class NordPoolPriceServiceTests public void UpdateCurrentPrice_WhenNordPoolPriceIsNull_ShouldReturnZero() { // Act - var result = _sut.UpdateCurrentPrice(); + _sut.UpdateCurrentPrice(); + var result = _sut.GetCurrentPrice(); // Assert result.Should().Be(0); @@ -482,7 +492,8 @@ public class NordPoolPriceServiceTests _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = new List() }; // Act - var result = _sut.UpdateCurrentPrice(); + _sut.UpdateCurrentPrice(); + var result = _sut.GetCurrentPrice(); // Assert result.Should().Be(0); @@ -495,7 +506,8 @@ public class NordPoolPriceServiceTests _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = null }; // Act - var result = _sut.UpdateCurrentPrice(); + _sut.UpdateCurrentPrice(); + var result = _sut.GetCurrentPrice(); // Assert result.Should().Be(0); @@ -516,7 +528,8 @@ public class NordPoolPriceServiceTests _sut.CurrentPrice = 17.91; // Act - var result = _sut.UpdateCurrentPrice(); + _sut.UpdateCurrentPrice(); + var result = _sut.GetCurrentPrice(); // Assert result.Should().Be(17.91); @@ -535,7 +548,8 @@ public class NordPoolPriceServiceTests _sut.DayQuartersIndex = -1; // Act - var result = _sut.UpdateCurrentPrice(); + _sut.UpdateCurrentPrice(); + var result = _sut.GetCurrentPrice(); // Assert result.Should().Be(17.91); @@ -559,78 +573,164 @@ public class NordPoolPriceServiceTests _sut.DayQuartersIndex.Should().BeGreaterThanOrEqualTo(0); } + [Theory] + [InlineData(-3.25)] + [InlineData(0.0)] + [InlineData(0.01)] + [InlineData(123.45)] + [InlineData(999.99)] + public void UpdateCurrentPrice_WhenCurrentQuarterHasPrice_ShouldStoreThatPrice(double expectedPrice) + { + // Arrange — negative and zero spot prices are valid NordPool scenarios + var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); + var prices = NordPoolTestData.CreateIntervals( + NordPoolConsts.MaxDailyIntervals, + i => i == index ? expectedPrice : 10.0); + + _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; + _sut.CurrentPrice = 17.91; + _sut.DayQuartersIndex = -1; + + // Act + _sut.UpdateCurrentPrice(); + + // Assert + _sut.CurrentPrice.Should().Be(expectedPrice); + _sut.DayQuartersIndex.Should().Be(index); + } + + [Fact] + public void UpdateCurrentPrice_WhenCurrentIndexIsOutsidePricesRange_ShouldKeepPreviousPriceButAdvanceIndex() + { + // Arrange — fewer prices than the current quarter index (e.g. partial day payload) + var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); + var prices = Enumerable.Range(0, index) + .Select(i => new NordPoolDayPrice { Price = 10.0 + i }) + .ToList(); + + _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; + _sut.CurrentPrice = 17.91; + _sut.DayQuartersIndex = -1; + + // Act + _sut.UpdateCurrentPrice(); + + // Assert + _sut.CurrentPrice.Should().Be(17.91); + _sut.DayQuartersIndex.Should().Be(index); + } + + [Fact] + public void UpdateCurrentPrice_WhenQuarterIndexUnchangedButPricesChanged_ShouldKeepCachedPrice() + { + // Arrange + var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); + var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals) + .Select(i => new NordPoolDayPrice { Price = 99.0 }) + .ToList(); + + _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; + _sut.DayQuartersIndex = index; + _sut.CurrentPrice = 17.91; + + // Act + _sut.UpdateCurrentPrice(); + + // Assert — same quarter means no recompute, cached value survives + _sut.CurrentPrice.Should().Be(17.91); + _sut.DayQuartersIndex.Should().Be(index); + } + + [Fact] + public void UpdateCurrentPrice_WhenOnlyCurrentQuarterPriceIsNull_ShouldKeepPreviousPriceAndAdvanceIndex() + { + // Arrange + var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); + var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals) + .Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 }) + .ToList(); + + _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices }; + _sut.CurrentPrice = 17.91; + _sut.DayQuartersIndex = (index + 1) % NordPoolConsts.MaxDailyIntervals; + + // Act + _sut.UpdateCurrentPrice(); + + // Assert + _sut.CurrentPrice.Should().Be(17.91); + _sut.DayQuartersIndex.Should().Be(index); + } + #endregion #region ShouldFetchNewPrices - [Fact] - public void ShouldFetchNewPrices_WhenNoLastFetchedDate_ShouldReturnTrue() + /// + /// 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). + /// + public static IEnumerable ShouldFetchScenarios() { + var today = DateOnly.FromDateTime(DateTime.Now); + + static NordPoolPrice Prices(params double?[] values) => new() + { + Prices = values.Select(price => new NordPoolDayPrice { Price = price }).ToList() + }; + + 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]; + } + + [Theory] + [MemberData(nameof(ShouldFetchScenarios))] + public void ShouldFetchNewPrices_ShouldMatchScenario( + string scenario, + DateOnly? lastFetchedDate, + NordPoolPrice? todayPrice, + NordPoolPrice? tomorrowPrice, + bool expected) + { + // Arrange + _sut.LastFetchedDate = lastFetchedDate; + _sut.TodayNordPoolPrice = todayPrice; + _sut.TomorrowNordPoolPrice = tomorrowPrice; + // Act var result = _sut.ShouldFetchNewPrices(DateOnly.FromDateTime(DateTime.Now)); // Assert - result.Should().BeTrue(); + result.Should().Be(expected, $"scenario: {scenario}"); } [Fact] - public void ShouldFetchNewPrices_WhenLastFetchedDateIsYesterday_ShouldReturnTrue() + public void ShouldFetchNewPrices_WhenTomorrowPricesAreNull_ShouldDependOnHourOfDay() { - // Arrange + // Arrange — tomorrow's prices are not published before 13:00, so cached data is acceptable until then var today = DateOnly.FromDateTime(DateTime.Now); - _sut.LastFetchedDate = today.AddDays(-1); + _sut.LastFetchedDate = today; _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = new List { new() { Price = 12.50 } } }; + _sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = null }; // Act var result = _sut.ShouldFetchNewPrices(today); // Assert - result.Should().BeTrue(); + result.Should().Be(DateTime.Now.Hour >= 13); } [Fact] - public void ShouldFetchNewPrices_WhenTodayPricesAreNull_ShouldReturnTrue() - { - // Arrange - var today = DateOnly.FromDateTime(DateTime.Now); - _sut.LastFetchedDate = today; - _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = null }; - _sut.TomorrowNordPoolPrice = new NordPoolPrice - { - Prices = new List { new() { Price = 12.50 } } - }; - - // Act - var result = _sut.ShouldFetchNewPrices(today); - - // Assert - result.Should().BeTrue(); - } - - [Fact] - public void ShouldFetchNewPrices_WhenTodayPricesAreEmpty_ShouldReturnTrue() - { - // Arrange - var today = DateOnly.FromDateTime(DateTime.Now); - _sut.LastFetchedDate = today; - _sut.TodayNordPoolPrice = new NordPoolPrice { Prices = new List() }; - _sut.TomorrowNordPoolPrice = new NordPoolPrice - { - Prices = new List { new() { Price = 12.50 } } - }; - - // Act - var result = _sut.ShouldFetchNewPrices(today); - - // Assert - result.Should().BeTrue(); - } - - [Fact] - public void ShouldFetchNewPrices_WhenAllPricesAvailable_ShouldReturnFalse() + public void ShouldFetchNewPrices_WhenTomorrowPricesAreEmpty_ShouldDependOnHourOfDay() { // Arrange var today = DateOnly.FromDateTime(DateTime.Now); @@ -639,30 +739,117 @@ public class NordPoolPriceServiceTests { Prices = new List { new() { Price = 12.50 } } }; - _sut.TomorrowNordPoolPrice = new NordPoolPrice + _sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = new List() }; + + // Act + var result = _sut.ShouldFetchNewPrices(today); + + // Assert + result.Should().Be(DateTime.Now.Hour >= 13); + } + + #endregion + + #region RollOverPrices + + [Fact] + public void RollOverPrices_WithTomorrowPrices_ShouldPromoteTomorrowToToday() + { + // Arrange + var tomorrow = new NordPoolPrice { Prices = new List { new() { Price = 18.71 } } }; + _sut.TodayNordPoolPrice = new NordPoolPrice + { + Prices = new List { new() { Price = 12.50 } } + }; + _sut.TomorrowNordPoolPrice = tomorrow; + _sut.DayQuartersIndex = 48; + var today = new DateOnly(2026, 4, 1); + // Act - var result = _sut.ShouldFetchNewPrices(today); + _sut.RollOverPrices(today); // Assert - result.Should().BeFalse(); + _sut.TodayNordPoolPrice.Should().BeSameAs(tomorrow); + _sut.TomorrowNordPoolPrice.Should().BeNull(); + _sut.DayQuartersIndex.Should().Be(-1); + _sut.LastFetchedDate.Should().Be(today); + } + + public static IEnumerable UnusableTomorrowPrices => + [ + [null], + [new NordPoolPrice { Prices = null }], + [new NordPoolPrice { Prices = [] }] + ]; + + [Theory] + [MemberData(nameof(UnusableTomorrowPrices))] + public void RollOverPrices_WithoutUsableTomorrowPrices_ShouldResetTodayToEmptyPrice(NordPoolPrice? tomorrow) + { + // Arrange + _sut.TodayNordPoolPrice = new NordPoolPrice + { + Prices = new List { new() { Price = 12.50 } } + }; + _sut.TomorrowNordPoolPrice = tomorrow; + _sut.DayQuartersIndex = 42; + var today = new DateOnly(2026, 4, 1); + + // Act + _sut.RollOverPrices(today); + + // Assert — nothing usable to promote, so today becomes an empty payload + _sut.TodayNordPoolPrice.Should().NotBeNull(); + _sut.TodayNordPoolPrice!.Prices.Should().BeNull(); + _sut.TomorrowNordPoolPrice.Should().BeNull(); + _sut.DayQuartersIndex.Should().Be(-1); + _sut.LastFetchedDate.Should().Be(today); } [Fact] - public void ShouldFetchNewPrices_WhenNordPoolPriceIsNull_ShouldReturnTrue() + public void RollOverPrices_WhenBothPricesAreNull_ShouldNotThrow() { // Arrange - var today = DateOnly.FromDateTime(DateTime.Now); - _sut.LastFetchedDate = today; + _sut.TodayNordPoolPrice = null; + _sut.TomorrowNordPoolPrice = null; + var today = new DateOnly(2026, 4, 1); // Act - var result = _sut.ShouldFetchNewPrices(today); + var act = () => _sut.RollOverPrices(today); // Assert - result.Should().BeTrue(); + act.Should().NotThrow(); + _sut.TodayNordPoolPrice.Should().NotBeNull(); + _sut.TodayNordPoolPrice!.Prices.Should().BeNull(); + } + + [Fact] + public void RollOverPrices_ShouldDiscardPreviousTodayPrices() + { + // Arrange + var previousToday = new NordPoolPrice + { + Prices = new List { new() { Price = 12.50 } } + }; + var tomorrow = new NordPoolPrice + { + Prices = new List { new() { Price = 18.71 } } + }; + + _sut.TodayNordPoolPrice = previousToday; + _sut.TomorrowNordPoolPrice = tomorrow; + + // Act + _sut.RollOverPrices(new DateOnly(2026, 4, 1)); + + // Assert — the old today payload is replaced, not mutated + _sut.TodayNordPoolPrice.Should().BeSameAs(tomorrow); + previousToday.Prices.Should().HaveCount(1); + previousToday.Prices![0].Price.Should().Be(12.50); } #endregion diff --git a/NordPool.Manager.Tests/NordPoolTestData.cs b/NordPool.Manager.Tests/NordPoolTestData.cs new file mode 100644 index 0000000..58637af --- /dev/null +++ b/NordPool.Manager.Tests/NordPoolTestData.cs @@ -0,0 +1,48 @@ +using NordPool.Models; + +namespace NordPool.Manager.Tests; + +/// +/// Shared, deterministic datasets used by the NordPool tests. +/// Keeping the generators here avoids copy-pasted price loops across test classes. +/// +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); + + /// + /// Builds a contiguous set of 15-minute intervals starting at . + /// + public static List CreateIntervals( + int count, + Func priceFactory, + DateTime? dayStart = null) + { + 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(); + } + + /// + /// A full 96-interval day with a deterministic sawtooth price curve covering + /// negative, zero, cheap and expensive prices. + /// + public static List CreateGeneratedDay(DateTime? dayStart = null) + { + var start = dayStart ?? DayStart; + + return CreateIntervals( + NordPoolConsts.MaxDailyIntervals, + i => Math.Round(15.0 * Math.Sin(i / 6.0) + (i % 8) - 2.0, 2), + start); + } +} diff --git a/NordPool.Manager/Interface/INordPoolInit.cs b/NordPool.Manager/Interface/INordPoolInit.cs deleted file mode 100644 index 8f8076a..0000000 --- a/NordPool.Manager/Interface/INordPoolInit.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace NordPoolManager.Interface; - -public interface INordPoolInit -{ - Task InitializeAsync(); - Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); -} \ No newline at end of file diff --git a/NordPool.Manager/Interface/INordPoolPriceService.cs b/NordPool.Manager/Interface/INordPoolPriceService.cs index 0ca95b0..dc7474a 100644 --- a/NordPool.Manager/Interface/INordPoolPriceService.cs +++ b/NordPool.Manager/Interface/INordPoolPriceService.cs @@ -12,7 +12,8 @@ public interface INordPoolPriceService DateOnly? LastFetchedDate { get; } Task FetchPricesAsync(); - double UpdateCurrentPrice(); + void UpdateCurrentPrice(); + double GetCurrentPrice(); bool ShouldFetchNewPrices(DateOnly today); void RollOverPrices(DateOnly today); } diff --git a/NordPool.Manager/Models/CheapestIntervalsUpdateResult.cs b/NordPool.Manager/Models/CheapestIntervalsUpdateResult.cs deleted file mode 100644 index 28deae3..0000000 --- a/NordPool.Manager/Models/CheapestIntervalsUpdateResult.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace NordPoolManager.Models; - -/// -/// Result of updating cheapest intervals, containing the effective configuration used for the update. -/// -public class CheapestIntervalsUpdateResult -{ - public int IntervalCount { get; init; } - public double PriceCap { get; init; } - public bool SkipPriceCap { get; init; } -} diff --git a/NordPool.Manager/NordPool.Manager.csproj b/NordPool.Manager/NordPool.Manager.csproj index a0eaf61..a49b2f1 100644 --- a/NordPool.Manager/NordPool.Manager.csproj +++ b/NordPool.Manager/NordPool.Manager.csproj @@ -20,10 +20,10 @@ - - - - + + + + diff --git a/NordPool.Manager/NordPoolEntityService.cs b/NordPool.Manager/NordPoolEntityService.cs index 9c9e8b7..6b19ed1 100644 --- a/NordPool.Manager/NordPoolEntityService.cs +++ b/NordPool.Manager/NordPoolEntityService.cs @@ -155,7 +155,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< var utcNow = DateTime.UtcNow; var timestamp = utcNow.ToString("O"); - var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"); + var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); var priceValue = ctx.CurrentPrice.ToString("F2", CultureInfo.InvariantCulture); var todayPricesCount = ctx.TodayNordPoolPrice?.Prices?.Count ?? 0; var tomorrowPricesCount = ctx.TomorrowNordPoolPrice?.Prices?.Count ?? 0; @@ -198,7 +198,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< state_class = "measurement", friendly_name = "NordPool current price", last_updated = timestamp, - last_api_fetch = ctx.LastApiUpdateDate?.ToString("O"), + last_api_fetch = ctx.LastApiUpdateDate?.ToString("O", CultureInfo.InvariantCulture), using_cached_data = ctx.UsingCachedData, current_quarter_index = ctx.DayQuartersIndex }).ConfigureAwait(false); @@ -251,7 +251,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< configured_ready_by = ctx.ConfiguredReadyBy, total_heating_minutes = cheapestCount * NordPoolConsts.MinutesPerInterval, is_now_cheap = ctx.IsNowCheap, - next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O"), + next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O", CultureInfo.InvariantCulture), friendly_name = "NordPool cheapest boiler intervals", last_updated = timestamp }).ConfigureAwait(false); diff --git a/NordPool.Manager/NordPoolInit.cs b/NordPool.Manager/NordPoolInit.cs index bcf38d3..c4fa507 100644 --- a/NordPool.Manager/NordPoolInit.cs +++ b/NordPool.Manager/NordPoolInit.cs @@ -15,7 +15,7 @@ using NordPoolManager.Models; namespace NordPoolManager; [NetDaemonApp] -public class NordPoolInit : INordPoolInit +public class NordPoolInit { private readonly ILogger _logger; private readonly IHaContext _haContext; @@ -57,7 +57,31 @@ public class NordPoolInit : INordPoolInit _ = InitializeAndScheduleAsync(); } + + public async Task InitializeAsync() + { + try + { + await Task.Delay(TimeSpan.FromSeconds(3)); + if (_options.CleanupEntitiesOnStartup) + { + await _entityService.CleanupEntitiesAsync(); + } + + await _entityService.CreateEntitiesAsync(UnitOfMeasurement); + await _entityService.ResetEntitiesAsync(); + await Task.Delay(TimeSpan.FromSeconds(10)); + + await UpdatePricesAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error initializing NordPool prices"); + throw; + } + } + private async Task InitializeAndScheduleAsync() { try @@ -72,41 +96,6 @@ public class NordPoolInit : INordPoolInit } } - public async Task InitializeAsync() - { - try - { - await Task.Delay(TimeSpan.FromSeconds(3)); - - await _priceService.FetchPricesAsync(); - - if (_options.CleanupEntitiesOnStartup) - { - await _entityService.CleanupEntitiesAsync(); - } - - await _entityService.CreateEntitiesAsync(UnitOfMeasurement); - await _entityService.ResetEntitiesAsync(); - await Task.Delay(TimeSpan.FromSeconds(10)); - - var currentPrice = _priceService.UpdateCurrentPrice(); - - if (currentPrice == 0) - { - _logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval"); - } - - var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration(); - UpdateCheapestIntervals(boilerConfig); - await UpdateEntitiesAsync(boilerConfig); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error initializing NordPool prices"); - throw; - } - } - private void SchedulePeriodicUpdates() { var now = _timeProvider.GetLocalNow(); @@ -143,7 +132,6 @@ public class NordPoolInit : INordPoolInit var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration(); UpdateCheapestIntervals(boilerConfig); await UpdateEntitiesAsync(boilerConfig); - } catch (Exception ex) { @@ -158,36 +146,10 @@ public class NordPoolInit : INordPoolInit .Subscribe(_ => { _logger.LogInformation("Fetch prices button pressed, triggering manual NordPool price update"); - Task.Run(HandleFetchPricesAsync); + Task.Run(UpdatePricesAsync); }); } - private async Task HandleFetchPricesAsync() - { - try - { - _logger.LogInformation("Manual fetch: forcing fresh NordPool price retrieval"); - - await _priceService.FetchPricesAsync(); - _priceService.UpdateCurrentPrice(); - - var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration(); - UpdateCheapestIntervals(boilerConfig); - await UpdateEntitiesAsync(boilerConfig); - - _logger.LogInformation("Manual fetch and update completed"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error during manual NordPool price fetch"); - } - } - - public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) - { - await _entityService.CleanupEntitiesAsync(cancellationToken); - } - private void UpdateCheapestIntervals(BoilerConfig config) { var effectivePriceCap = config.SkipPriceCap ? double.MaxValue : config.PriceCap; @@ -215,14 +177,14 @@ public class NordPoolInit : INordPoolInit private async Task UpdateEntitiesAsync(BoilerConfig boilerConfig) { var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); - var nowCet = TimeZoneInfo.ConvertTime(_timeProvider.GetUtcNow(), cetTimeZone).DateTime; - var todayCet = DateOnly.FromDateTime(nowCet); - var currentDateTime = nowCet; + var currentDateTime = TimeZoneInfo.ConvertTime(_timeProvider.GetUtcNow(), cetTimeZone).DateTime; + var todayCet = DateOnly.FromDateTime(currentDateTime); var configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour; var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture); var isNowCheap = CheapestIntervals != null && _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime); + var nextCheapInterval = CheapestIntervals? .Where(i => i.Start > currentDateTime) .OrderBy(i => i.Start) diff --git a/NordPool.Manager/NordPoolPriceService.cs b/NordPool.Manager/NordPoolPriceService.cs index 2228f49..b1402c9 100644 --- a/NordPool.Manager/NordPoolPriceService.cs +++ b/NordPool.Manager/NordPoolPriceService.cs @@ -26,13 +26,13 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger 0 }) - { - TodayNordPoolPrice = TomorrowNordPoolPrice; - } - else - { - TodayNordPoolPrice = new NordPoolPrice(); - } + TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 } ? TomorrowNordPoolPrice : new NordPoolPrice(); TomorrowNordPoolPrice = null; @@ -215,7 +211,7 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger - + diff --git a/PLAN.md b/PLAN.md deleted file mode 100644 index 4c7fc07..0000000 --- a/PLAN.md +++ /dev/null @@ -1,190 +0,0 @@ -# Power Limit Enforcement — Implementation Plan - -Extend existing (unused) PowerMonitor with power-limit enforcement. Switch from -1s polling to main-meter state-change trigger. On breach, turn off boiler -switch + `switch.boilermonitor_auto_management`. Recover after 10 min if power -dropped. Enable monitor. Default on. Reuse `persistent_notification`. - -## Decisions locked - -1. Extend PowerMonitor (enable + fix), not a new monitor. -2. Enforce = turn off boiler physical switch AND `switch.boilermonitor_auto_management`. -3. Recovery after 10 min (config `RecoverySeconds`). If power still over limit at - recovery check, stay enforced + wait another 10 min. -4. Default enabled (`EnforceLimitEnabled=true`, monitor `Enabled=true`). -5. Reuse `persistent_notification` for notifications. -6. Event-driven (meter state change), NOT periodic poll. Trust meter (no - fallback timer). - -## Files - -### New (3) - -- `PowerMonitor.Manager/Interface/IPowerLimitEnforcementService.cs` -- `PowerMonitor.Manager/PowerLimitEnforcementService.cs` -- `PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs` - -### Edit (5) - -- `PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs` — 3 new default consts -- `PowerMonitor.Manager/Models/PowerMonitorOptions.cs` — 6 new props -- `PowerMonitor.Manager/PowerMonitorInit.cs` — replace polling w/ state-change sub; - inject enforcement svc; call after high-power notify; fix cost-calc elapsed time -- `PowerMonitor.Manager/PowerMonitorServiceRegistration.cs` — register transient -- `PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs` — new props -- `HomeAssistant.Server/appsettings.json` — PowerMonitor `Enabled:true` + new keys - -No `program.cs` change (options already `Configure`). - -## Trigger refactor - -Replace `SchedulePeriodicPolling()` (lines 104-118) with `SubscribeToMainMeterChanges()`: - -```csharp -private void SubscribeToMainMeterChanges() -{ - var meter = new Entity(_haContext, _options.MainMeterEntityId); - meter.StateChanges() - .Subscribe(e => - { - if (e.Old?.State == e.New?.State) return; - _ = PollAndUpdateAsync(); - }); -} -``` - -Called from `InitializeAndScheduleAsync()` instead of `SchedulePeriodicPolling()`. -Keep initial `PollAndUpdateAsync()` in `InitializeAsync` (line 90). Pattern matches -`BoilerMonitorInit.SubscribeToSkipPriceCapChanges:227`. - -## Cost-calc fix (event-driven elapsed time) - -Add `_lastPollTimestamp` field. In `PollAndUpdateAsync`: - -```csharp -var now = _timeProvider.GetLocalNow(); -var elapsed = _lastPollTimestamp.HasValue - ? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10) - : _options.PollIntervalSeconds; -_lastPollTimestamp = now; -_costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsed), now.LocalDateTime); -``` - -Cap = `PollInterval x 10` prevents huge cost jumps on meter silence. Min 1 prevents -div-by-zero. - -## Options (`PowerMonitorOptions` + `PowerMonitorConsts`) - -| Prop | Type | Const default | -|---|---|---| -| `EnforceLimitEnabled` | bool | `true` | -| `PowerLimitWatts` | double | `DefaultPowerLimitWatts=5500` | -| `RecoverySeconds` | int | `DefaultRecoverySeconds=600` | -| `LimitCooldownSeconds` | int | `DefaultLimitCooldownSeconds=30` | -| `EnforceSwitchOffEntityIds` | string[] | `["switch.sonoff_1002230e32"]` | -| `PauseAndRestoreEntityIds` | string[] | `["switch.boilermonitor_auto_management"]` | - -New consts in `PowerMonitorConsts.cs`: -- `DefaultPowerLimitWatts = 5500.0` -- `DefaultRecoverySeconds = 600` -- `DefaultLimitCooldownSeconds = 30` -- `PowerLimitNotificationId = "power_monitor_power_limit"` -- `PowerLimitNotificationTitle = "Power Limit Enforced"` - -## Service `IPowerLimitEnforcementService` (transient: `IHaContext` + `IOptions` + `TimeProvider`) - -```csharp -void EnforceLimit(double currentPowerWatts); -bool IsLimitActive { get; } -``` - -State: `_isLimitActive`, `_enforcedAt`, `_lastActionTime`. - -### Logic per call - -- `!_isLimitActive && power > PowerLimitWatts && now-_lastAction >= Cooldown`: - 1. `switch.turn_off` each `EnforceSwitchOffEntityIds` (boiler first — race-safe) - 2. `switch.turn_off` each `PauseAndRestoreEntityIds` (auto_management) - 3. `persistent_notification.create` "Power Limit Enforced" - 4. `_isLimitActive=true; _enforcedAt=now; _lastAction=now;` -- `_isLimitActive`: - - `now-_enforcedAt < RecoverySeconds` -> no-op (waiting) - - `power < PowerLimitWatts` -> `switch.turn_on` each `PauseAndRestoreEntityIds`; - dismiss notif; `_isLimitActive=false` - - `power >= PowerLimitWatts` -> `_enforcedAt=now` (wait another 10 min, keep notif) -- else no-op - -Never turn boiler switch back on — BoilerMonitor decides on next cheap interval. - -## Wire into poll loop - -`PowerMonitorInit.PollAndUpdateAsync` after `EvaluateHighPowerNotification(...)` (line 232): - -```csharp -if (_options.EnforceLimitEnabled) - _enforcementService.EnforceLimit(calculation.TotalPowerWatts); -``` - -Add `IPowerLimitEnforcementService` to ctor. - -## Register - -`PowerMonitorServiceRegistration.cs`: - -```csharp -.AddTransient() -``` - -Transient (injects `IHaContext` — AGENTS.md DI rule, never singleton). - -## appsettings.json `PowerMonitor` - -```json -"PowerMonitor": { - "Enabled": true, - "MainMeterEntityId": "sensor.sonoff_100267d63f_power", - "PollIntervalSeconds": 1, - "SmoothingWindowSize": 10, - "AnomalyThresholdWatts": 500, - "HighPowerThresholdWatts": 6000, - "EnforceLimitEnabled": true, - "PowerLimitWatts": 5500, - "RecoverySeconds": 600, - "LimitCooldownSeconds": 30, - "EnforceSwitchOffEntityIds": [ "switch.sonoff_1002230e32" ], - "PauseAndRestoreEntityIds": [ "switch.boilermonitor_auto_management" ], - "ExcludedSensorPatterns": [ - "sensor.nordpool_*", - "sensor.powermonitor_*" - ] -} -``` - -`PollIntervalSeconds` kept = 1 (now used as fallback/default elapsed + cap base). - -## Tests - -### `PowerLimitEnforcementServiceTests` (new) - -- Breach -> turn-off order: boiler switch before auto_management (Moq `CallService` - sequence assert) -- Recovery at 10min + power auto_mgmt on, boiler switch NOT turned on -- Recovery at 10min + power still high -> `_enforcedAt` resets, stays enforced -- Before 10min -> no-op -- Cooldown blocks rapid re-enforce -- `EnforceLimitEnabled=false` -> no-op -- Use `FakeTimeProvider` for time advance -- Add `Microsoft.Extensions.TimeProvider.Testing` package to test csproj - -### `PowerMonitorOptionsTests` (extend) - -- 6 new props defaults + `SectionName=="PowerMonitor"` - -## Verify after implementation - -1. `dotnet build PowerMonitor.Manager` -2. `dotnet test PowerMonitor.Manager.Tests` -3. `dotnet build HomeAssistantSDK.sln` -4. `RunSmokeTest` MCP (homeassistant server) -5. `ValidateEntities`: `sensor.sonoff_100267d63f_power`, `switch.sonoff_1002230e32`, - `switch.boilermonitor_auto_management` \ No newline at end of file diff --git a/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs b/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs index f61b0d6..07b4281 100644 --- a/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs +++ b/PowerMonitor.Manager.Tests/CostAccumulatorTests.cs @@ -5,164 +5,303 @@ namespace PowerMonitor.Manager.Tests; public class CostAccumulatorTests { + public enum CostWindow + { + FifteenMinutes, + Hour, + Day, + Month + } + #region AddCost and GetSnapshot [Fact] public void GetSnapshot_WhenNew_ShouldReturnZeroCosts() { - var sut = new CostAccumulator(new DateTime(2026, 3, 17, 10, 0, 0)); + // Arrange + var sut = new CostAccumulator(PowerMonitorTestData.FixedNow); + // Act var snapshot = sut.GetSnapshot(); + // Assert snapshot.Cost15Min.Should().Be(0); snapshot.Cost1Hour.Should().Be(0); snapshot.CostDaily.Should().Be(0); snapshot.CostMonthly.Should().Be(0); + snapshot.Previous15Min.Should().Be(0); + snapshot.Previous1Hour.Should().Be(0); + snapshot.PreviousDaily.Should().Be(0); + snapshot.PreviousMonthly.Should().Be(0); snapshot.PartialWindow.Should().BeTrue(); } [Fact] public void AddCost_ShouldAccumulateInAllWindows() { - var now = new DateTime(2026, 3, 17, 10, 0, 0); + // Arrange + var now = PowerMonitorTestData.FixedNow; var sut = new CostAccumulator(now); + // Act sut.AddCost(0.05, now.AddSeconds(15)); sut.AddCost(0.03, now.AddSeconds(30)); + // Assert var snapshot = sut.GetSnapshot(); - snapshot.Cost15Min.Should().BeApproximately(0.08, 0.0001); - snapshot.Cost1Hour.Should().BeApproximately(0.08, 0.0001); - snapshot.CostDaily.Should().BeApproximately(0.08, 0.0001); - snapshot.CostMonthly.Should().BeApproximately(0.08, 0.0001); + snapshot.Cost15Min.Should().BeApproximately(0.08, 1e-9); + snapshot.Cost1Hour.Should().BeApproximately(0.08, 1e-9); + snapshot.CostDaily.Should().BeApproximately(0.08, 1e-9); + snapshot.CostMonthly.Should().BeApproximately(0.08, 1e-9); + snapshot.PartialWindow.Should().BeTrue(); } - #endregion - - #region 15-minute window resets - [Fact] - public void AddCost_When15MinWindowCrosses_ShouldResetAndStorePrevious() + public void AddCost_WithGeneratedSeriesInSameWindow_ShouldSumEveryIncrement() { - var now = new DateTime(2026, 3, 17, 10, 14, 0); + // Arrange + var now = PowerMonitorTestData.FixedNow; var sut = new CostAccumulator(now); - sut.AddCost(0.10, now); + var increments = PowerMonitorTestData.CreatePowerSampleSeries(50) + .Select(watts => watts / 100_000.0) + .ToArray(); - sut.AddCost(0.02, new DateTime(2026, 3, 17, 10, 15, 0)); + // Act + foreach (var increment in increments) + { + sut.AddCost(increment, now.AddSeconds(1)); + } + // Assert + var expected = increments.Sum(); var snapshot = sut.GetSnapshot(); - snapshot.Cost15Min.Should().BeApproximately(0.02, 0.0001); - snapshot.Previous15Min.Should().BeApproximately(0.10, 0.0001); - snapshot.PartialWindow.Should().BeFalse(); + snapshot.Cost15Min.Should().BeApproximately(expected, 1e-9); + snapshot.Cost1Hour.Should().BeApproximately(expected, 1e-9); + snapshot.CostDaily.Should().BeApproximately(expected, 1e-9); + snapshot.CostMonthly.Should().BeApproximately(expected, 1e-9); + snapshot.PartialWindow.Should().BeTrue(); } - #endregion - - #region Hourly window resets - [Fact] - public void AddCost_WhenHourWindowCrosses_ShouldResetAndStorePrevious() + public void AddCost_WithNegativeIncrement_ShouldReduceEveryWindow() { - var now = new DateTime(2026, 3, 17, 10, 59, 0); + // Arrange - a meter that corrects itself downwards must not be clamped by the accumulator. + var now = PowerMonitorTestData.FixedNow; var sut = new CostAccumulator(now); sut.AddCost(0.50, now); - sut.AddCost(0.01, new DateTime(2026, 3, 17, 11, 0, 0)); + // Act + sut.AddCost(-0.20, now.AddSeconds(15)); + // Assert var snapshot = sut.GetSnapshot(); - snapshot.Cost1Hour.Should().BeApproximately(0.01, 0.0001); - snapshot.Previous1Hour.Should().BeApproximately(0.50, 0.0001); + snapshot.Cost15Min.Should().BeApproximately(0.30, 1e-9); + snapshot.Cost1Hour.Should().BeApproximately(0.30, 1e-9); + snapshot.CostDaily.Should().BeApproximately(0.30, 1e-9); + snapshot.CostMonthly.Should().BeApproximately(0.30, 1e-9); + } + + [Fact] + public void AddCost_WithVeryLargeIncrement_ShouldPreserveTheValue() + { + // Arrange + var now = PowerMonitorTestData.FixedNow; + var sut = new CostAccumulator(now); + + // Act + sut.AddCost(1_000_000.0, now); + + // Assert + sut.GetSnapshot().CostMonthly.Should().Be(1_000_000.0); + } + + [Fact] + public void AddCost_WithinSameWindows_ShouldNotPopulatePreviousValues() + { + // Arrange + var now = PowerMonitorTestData.FixedNow; + var sut = new CostAccumulator(now); + + // Act + sut.AddCost(0.01, now); + sut.AddCost(0.01, now.AddSeconds(15)); + sut.AddCost(0.01, now.AddMinutes(14)); + + // Assert + var snapshot = sut.GetSnapshot(); + snapshot.Previous15Min.Should().Be(0); + snapshot.Previous1Hour.Should().Be(0); + snapshot.PreviousDaily.Should().Be(0); + snapshot.PreviousMonthly.Should().Be(0); + snapshot.PartialWindow.Should().BeTrue(); } #endregion - #region Daily window resets + #region Window rollovers - [Fact] - public void AddCost_WhenDayChanges_ShouldResetDailyAndStorePrevious() + public static IEnumerable 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] + ]; + + [Theory] + [MemberData(nameof(WindowRolloverCases))] + public void AddCost_WhenWindowRollsOver_ShouldResetCurrentAndKeepPrevious( + string scenario, + CostWindow window, + DateTime firstTimestamp, + DateTime rolloverTimestamp, + double beforeRolloverCost, + double afterRolloverCost) { - var now = new DateTime(2026, 3, 17, 23, 59, 0); - var sut = new CostAccumulator(now); - sut.AddCost(5.00, now); + // Arrange + var sut = new CostAccumulator(firstTimestamp); + sut.AddCost(beforeRolloverCost, firstTimestamp); - sut.AddCost(0.01, new DateTime(2026, 3, 18, 0, 0, 0)); + // Act + sut.AddCost(afterRolloverCost, rolloverTimestamp); + // Assert var snapshot = sut.GetSnapshot(); - snapshot.CostDaily.Should().BeApproximately(0.01, 0.0001); - snapshot.PreviousDaily.Should().BeApproximately(5.00, 0.0001); + GetCurrent(snapshot, window).Should().BeApproximately(afterRolloverCost, 1e-9, $"scenario: {scenario}"); + GetPrevious(snapshot, window).Should().BeApproximately(beforeRolloverCost, 1e-9, $"scenario: {scenario}"); + snapshot.PartialWindow.Should().BeFalse($"scenario: {scenario}"); } - #endregion + [Fact] + public void AddCost_WhenAllWindowBoundariesCoincide_ShouldResetEveryWindow() + { + // Arrange + var lastSampleTime = new DateTime(2026, 3, 31, 23, 59, 0); + var rolloverTime = new DateTime(2026, 4, 1, 0, 0, 0); + var sut = new CostAccumulator(lastSampleTime); + sut.AddCost(12.34, lastSampleTime); - #region Monthly window resets + // Act + sut.AddCost(0.56, rolloverTime); + + // Assert + var snapshot = sut.GetSnapshot(); + snapshot.Cost15Min.Should().BeApproximately(0.56, 1e-9); + snapshot.Cost1Hour.Should().BeApproximately(0.56, 1e-9); + snapshot.CostDaily.Should().BeApproximately(0.56, 1e-9); + snapshot.CostMonthly.Should().BeApproximately(0.56, 1e-9); + snapshot.Previous15Min.Should().BeApproximately(12.34, 1e-9); + snapshot.Previous1Hour.Should().BeApproximately(12.34, 1e-9); + snapshot.PreviousDaily.Should().BeApproximately(12.34, 1e-9); + snapshot.PreviousMonthly.Should().BeApproximately(12.34, 1e-9); + } [Fact] - public void AddCost_WhenMonthChanges_ShouldResetMonthlyAndStorePrevious() + public void AddCost_AfterFirstRollover_ShouldKeepPartialWindowFalse() { - var now = new DateTime(2026, 3, 31, 23, 59, 0); + // Arrange + var now = PowerMonitorTestData.FixedNow; var sut = new CostAccumulator(now); - sut.AddCost(100.00, now); + sut.AddCost(0.10, now); - sut.AddCost(0.01, new DateTime(2026, 4, 1, 0, 0, 0)); + // Act + sut.AddCost(0.10, now.AddMinutes(15)); + sut.AddCost(0.10, now.AddMinutes(30)); - var snapshot = sut.GetSnapshot(); - snapshot.CostMonthly.Should().BeApproximately(0.01, 0.0001); - snapshot.PreviousMonthly.Should().BeApproximately(100.00, 0.0001); + // Assert + sut.GetSnapshot().PartialWindow.Should().BeFalse(); } #endregion #region Window boundary detection (static methods) - [Theory] - [InlineData(10, 0, 10, 14, false)] - [InlineData(10, 0, 10, 15, true)] - [InlineData(10, 14, 10, 15, true)] - [InlineData(10, 29, 10, 30, true)] - [InlineData(10, 44, 10, 45, true)] - [InlineData(10, 45, 10, 59, false)] - [InlineData(10, 45, 11, 0, true)] - public void IsNew15MinWindow_ShouldDetectBoundary(int lastHour, int lastMin, int nowHour, int nowMin, bool expected) - { - var lastReset = new DateTime(2026, 3, 17, lastHour, lastMin, 0); - var now = new DateTime(2026, 3, 17, nowHour, nowMin, 0); + public static IEnumerable 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] + ]; - CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected); + [Theory] + [MemberData(nameof(FifteenMinuteBoundaryCases))] + public void IsNew15MinWindow_ShouldDetectBoundary(string scenario, DateTime lastReset, DateTime now, bool expected) + { + CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); } - [Theory] - [InlineData(10, 10, false)] - [InlineData(10, 11, true)] - [InlineData(23, 0, true)] - public void IsNewHourWindow_ShouldDetectBoundary(int lastHour, int nowHour, bool expected) - { - var lastReset = new DateTime(2026, 3, 17, lastHour, 0, 0); - var now = new DateTime(2026, 3, 17, nowHour, 0, 0); + public static IEnumerable 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] + ]; - CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected); + [Theory] + [MemberData(nameof(HourBoundaryCases))] + public void IsNewHourWindow_ShouldDetectBoundary(string scenario, DateTime lastReset, DateTime now, bool expected) + { + CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); } - [Theory] - [InlineData(17, 17, false)] - [InlineData(17, 18, true)] - public void IsNewDayWindow_ShouldDetectBoundary(int lastDay, int nowDay, bool expected) - { - var lastReset = new DateTime(2026, 3, lastDay, 0, 0, 0); - var now = new DateTime(2026, 3, nowDay, 0, 0, 0); + public static IEnumerable 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] + ]; - CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected); + [Theory] + [MemberData(nameof(DayBoundaryCases))] + public void IsNewDayWindow_ShouldDetectBoundary(string scenario, DateTime lastReset, DateTime now, bool expected) + { + CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); } - [Theory] - [InlineData(3, 3, false)] - [InlineData(3, 4, true)] - [InlineData(12, 1, true)] - public void IsNewMonthWindow_ShouldDetectBoundary(int lastMonth, int nowMonth, bool expected) - { - var lastReset = new DateTime(2026, lastMonth, 1, 0, 0, 0); - var now = new DateTime(2026, nowMonth, 1, 0, 0, 0); + public static IEnumerable 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] + ]; - CostAccumulator.IsNewMonthWindow(now, lastReset).Should().Be(expected); + [Theory] + [MemberData(nameof(MonthBoundaryCases))] + public void IsNewMonthWindow_ShouldDetectBoundary(string scenario, DateTime lastReset, DateTime now, bool expected) + { + CostAccumulator.IsNewMonthWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}"); } #endregion @@ -172,12 +311,14 @@ public class CostAccumulatorTests [Fact] public async Task AddCost_ConcurrentAccess_ShouldNotLoseData() { - var now = new DateTime(2026, 3, 17, 10, 0, 0); + // Arrange + var now = PowerMonitorTestData.FixedNow; var sut = new CostAccumulator(now); const double incrementPerCall = 0.001; const int callsPerThread = 1000; const int threadCount = 10; + // Act var tasks = Enumerable.Range(0, threadCount) .Select(_ => Task.Run(() => { @@ -190,10 +331,29 @@ public class CostAccumulatorTests await Task.WhenAll(tasks); + // Assert var snapshot = sut.GetSnapshot(); var expected = incrementPerCall * callsPerThread * threadCount; snapshot.CostMonthly.Should().BeApproximately(expected, 0.0001); } #endregion + + private static double GetCurrent(CostSnapshot snapshot, CostWindow window) => window switch + { + CostWindow.FifteenMinutes => snapshot.Cost15Min, + CostWindow.Hour => snapshot.Cost1Hour, + CostWindow.Day => snapshot.CostDaily, + CostWindow.Month => snapshot.CostMonthly, + _ => throw new ArgumentOutOfRangeException(nameof(window)) + }; + + private static double GetPrevious(CostSnapshot snapshot, CostWindow window) => window switch + { + CostWindow.FifteenMinutes => snapshot.Previous15Min, + CostWindow.Hour => snapshot.Previous1Hour, + CostWindow.Day => snapshot.PreviousDaily, + CostWindow.Month => snapshot.PreviousMonthly, + _ => throw new ArgumentOutOfRangeException(nameof(window)) + }; } diff --git a/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs b/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs index dba782a..70ed076 100644 --- a/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs +++ b/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs @@ -18,103 +18,181 @@ public class OtherPowerCalculationServiceTests #region Basic calculation - [Fact] - public void Calculate_ShouldReturnOtherAsTotalMinusDevices() + public static IEnumerable CalculationCases => + [ + ["two devices", 341.97, new[] { 8.55, 36.93 }, 296.49, "ok"], + ["no devices", 341.97, System.Array.Empty(), 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(), 0.0, "ok"], + ["negative total, no devices", -120.0, System.Array.Empty(), 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"] + ]; + + [Theory] + [MemberData(nameof(CalculationCases))] + public void Calculate_ShouldDeriveOtherPowerFromTotalAndDevices( + string scenario, + double totalPowerWatts, + double[] deviceWatts, + double expectedOtherWatts, + string expectedDataQuality) { + // Arrange var sut = CreateSut(smoothingWindowSize: 1); - var devices = new Dictionary - { - ["sensor.sonoff_100215c534_power"] = 8.55, - ["sensor.sonoff_10018909cb_power"] = 36.93 - }; + var devices = deviceWatts + .Select((watts, index) => ($"sensor.device{index}_power", watts)) + .ToDictionary(entry => entry.Item1, entry => entry.Item2); - var result = sut.Calculate(341.97, devices); + // Act + var result = sut.Calculate(totalPowerWatts, devices); - result.TotalPowerWatts.Should().Be(341.97); - result.KnownDevicesSumWatts.Should().BeApproximately(45.48, 0.01); - result.RawOtherPowerWatts.Should().BeApproximately(296.49, 0.01); - result.DataQuality.Should().Be("ok"); - } - - [Fact] - public void Calculate_WhenDevicesSumExceedsTotal_ShouldClampToZero() - { - var sut = CreateSut(smoothingWindowSize: 1); - var devices = new Dictionary - { - ["sensor.sonoff_100215c534_power"] = 200.0, - ["sensor.sonoff_10018909cb_power"] = 180.0 - }; - - var result = sut.Calculate(341.97, devices); - - result.RawOtherPowerWatts.Should().Be(0); - result.SmoothedOtherPowerWatts.Should().Be(0); - result.DataQuality.Should().Be("device_sum_exceeds_total"); - } - - [Fact] - public void Calculate_WithNoDevices_ShouldReturnTotalAsOther() - { - var sut = CreateSut(smoothingWindowSize: 1); - var devices = new Dictionary(); - - var result = sut.Calculate(341.97, devices); - - result.RawOtherPowerWatts.Should().Be(341.97); - result.KnownDevicesSumWatts.Should().Be(0); + // Assert + result.TotalPowerWatts.Should().Be(totalPowerWatts, $"scenario: {scenario}"); + result.KnownDevicesSumWatts.Should().BeApproximately(deviceWatts.Sum(), 1e-6, $"scenario: {scenario}"); + result.RawOtherPowerWatts.Should().BeApproximately(expectedOtherWatts, 1e-6, $"scenario: {scenario}"); + result.SmoothedOtherPowerWatts.Should().BeApproximately(expectedOtherWatts, 1e-6, $"scenario: {scenario}"); + result.DataQuality.Should().Be(expectedDataQuality, $"scenario: {scenario}"); + result.DevicePowerReadings.Should().HaveCount(deviceWatts.Length, $"scenario: {scenario}"); } [Fact] public void Calculate_ShouldIncludeAllDeviceReadingsInResult() { + // Arrange var sut = CreateSut(smoothingWindowSize: 1); - var devices = new Dictionary - { - ["sensor.sonoff_100215c534_power"] = 8.55, - ["sensor.sonoff_10018909cb_power"] = 36.93 - }; + var devices = PowerMonitorTestData.CreateCostDeviceReadings(); - var result = sut.Calculate(341.97, devices); + // Act + var result = sut.Calculate(PowerMonitorTestData.DefaultTotalWatts, devices); + // Assert result.DevicePowerReadings.Should().HaveCount(2); - result.DevicePowerReadings["sensor.sonoff_100215c534_power"].Should().Be(8.55); - result.DevicePowerReadings["sensor.sonoff_10018909cb_power"].Should().Be(36.93); + result.DevicePowerReadings["sensor.sonoff_100215c534_power"].Should().Be(101.0); + result.DevicePowerReadings["sensor.sonoff_10018909cb_power"].Should().Be(109.93); + } + + [Fact] + public void Calculate_ShouldCopyDeviceReadingsInsteadOfAliasingThem() + { + // Arrange + var sut = CreateSut(smoothingWindowSize: 1); + var devices = new Dictionary { ["sensor.tv_power"] = 100.0 }; + + // Act + var result = sut.Calculate(150.0, devices); + devices["sensor.tv_power"] = 900.0; + + // Assert + result.DevicePowerReadings["sensor.tv_power"].Should().Be(100.0); + result.KnownDevicesSumWatts.Should().Be(100.0); } #endregion #region EMA smoothing + [Fact] + public void Calculate_FirstSample_ShouldReturnRawValueWithoutSmoothing() + { + // Arrange + var sut = CreateSut(smoothingWindowSize: 10); + + // Act + var result = sut.Calculate(341.97, new Dictionary()); + + // Assert + result.SmoothedOtherPowerWatts.Should().Be(341.97); + } + [Fact] public void Calculate_WithSmoothing_ShouldApplyExponentialMovingAverage() { + // Arrange var sut = CreateSut(smoothingWindowSize: 4); var devices = new Dictionary(); + // Act var result1 = sut.Calculate(341.97, devices); - result1.SmoothedOtherPowerWatts.Should().BeApproximately(341.97, 0.1); - var result2 = sut.Calculate(115.0, devices); + + // Assert + result1.SmoothedOtherPowerWatts.Should().BeApproximately(341.97, 0.1); result2.SmoothedOtherPowerWatts.Should().BeLessThan(341.97); result2.SmoothedOtherPowerWatts.Should().BeGreaterThan(115.0); } [Fact] - public void Calculate_MultipleCallsWithSameValue_ShouldConverge() + public void Calculate_WithSmoothingWindowOfOne_ShouldFollowRawValueExactly() { - var sut = CreateSut(smoothingWindowSize: 5); + // Arrange - alpha becomes 1, so the previous value has no influence. + var sut = CreateSut(smoothingWindowSize: 1); + + // Act + sut.Calculate(500.0, new Dictionary()); + var result = sut.Calculate(25.0, new Dictionary()); + + // Assert + result.SmoothedOtherPowerWatts.Should().Be(25.0); + } + + [Fact] + public void Calculate_ShouldDampenSingleSpike() + { + // Arrange + var sut = CreateSut(smoothingWindowSize: 10); + sut.Calculate(100.0, new Dictionary()); + + // Act + var result = sut.Calculate(10_000.0, new Dictionary()); + + // Assert + result.RawOtherPowerWatts.Should().Be(10_000.0); + result.SmoothedOtherPowerWatts.Should().BeLessThan(result.RawOtherPowerWatts * 0.25); + result.SmoothedOtherPowerWatts.Should().BeGreaterThan(100.0); + } + + [Theory] + [InlineData(2)] + [InlineData(4)] + [InlineData(5)] + [InlineData(10)] + [InlineData(20)] + public void Calculate_MultipleCallsWithSameValue_ShouldConverge(int smoothingWindowSize) + { + // Arrange + var sut = CreateSut(smoothingWindowSize); var devices = new Dictionary(); + // Act PowerCalculationResult? result = null; - for (var i = 0; i < 50; i++) + for (var i = 0; i < 200; i++) { result = sut.Calculate(200.0, devices); } + // Assert result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1); } + [Fact] + public void Calculate_WithGeneratedSeries_ShouldNeverOvershootTheInputRange() + { + // Arrange + var sut = CreateSut(smoothingWindowSize: 5); + var samples = PowerMonitorTestData.CreatePowerSampleSeries(50); + var devices = new Dictionary(); + + // Act + var results = samples.Select(sample => sut.Calculate(sample, devices)).ToList(); + + // Assert + results.Should().OnlyContain(r => r.SmoothedOtherPowerWatts >= samples.Min()); + results.Should().OnlyContain(r => r.SmoothedOtherPowerWatts <= samples.Max()); + } + #endregion #region Reset @@ -122,16 +200,33 @@ public class OtherPowerCalculationServiceTests [Fact] public void Reset_ShouldClearSmoothedState() { + // Arrange var sut = CreateSut(smoothingWindowSize: 10); var devices = new Dictionary(); sut.Calculate(341.97, devices); sut.Calculate(341.97, devices); + // Act sut.Reset(); var result = sut.Calculate(115.0, devices); + // Assert result.SmoothedOtherPowerWatts.Should().BeApproximately(115.0, 0.1); } + [Fact] + public void Reset_WhenCalledBeforeAnyCalculation_ShouldKeepFirstSampleRaw() + { + // Arrange + var sut = CreateSut(smoothingWindowSize: 10); + + // Act + sut.Reset(); + var result = sut.Calculate(42.5, new Dictionary()); + + // Assert + result.SmoothedOtherPowerWatts.Should().Be(42.5); + } + #endregion } diff --git a/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs b/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs index 4c78d9e..fe001fb 100644 --- a/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs @@ -7,62 +7,66 @@ namespace PowerMonitor.Manager.Tests; public class PowerCostCalculationServiceTests { - private readonly PowerCostCalculationService _sut = new(); - - private const double DefaultTotalWatts = 341.97; - private const double DefaultSmoothedOtherWatts = 131.04; - private const double DefaultPricePerKwh = 0.1791; - - private static PowerCalculationResult CreateResult( - double totalWatts = DefaultTotalWatts, - double smoothedOtherWatts = DefaultSmoothedOtherWatts, - Dictionary? deviceReadings = null) + public enum CostBucket { - var readings = deviceReadings ?? new Dictionary - { - ["sensor.sonoff_100215c534_power"] = 101.0, - ["sensor.sonoff_10018909cb_power"] = 109.93 - }; - - return new PowerCalculationResult - { - TotalPowerWatts = totalWatts, - KnownDevicesSumWatts = readings.Values.Sum(), - RawOtherPowerWatts = smoothedOtherWatts, - SmoothedOtherPowerWatts = smoothedOtherWatts, - DataQuality = "ok", - DevicePowerReadings = readings - }; + Total, + Other } + private readonly PowerCostCalculationService _sut = new(); + #region CalculateCostIncrement - [Fact] - public void CalculateCostIncrement_ShouldComputeCorrectCost() - { - var cost = PowerCostCalculationService.CalculateCostIncrement( - powerWatts: 341.97, - pricePerKwh: 0.1791, - pollIntervalSeconds: PowerMonitorConsts.DefaultPollIntervalSeconds); + public static IEnumerable 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] + ]; - var expected = (341.97 / PowerMonitorConsts.WattsPerKilowatt) - * 0.1791 - * ((double)PowerMonitorConsts.DefaultPollIntervalSeconds / PowerMonitorConsts.SecondsPerHour); - cost.Should().BeApproximately(expected, 0.000001); + [Theory] + [MemberData(nameof(CostIncrementCases))] + public void CalculateCostIncrement_ShouldComputeExpectedCost( + string scenario, + double powerWatts, + double pricePerKwh, + int pollIntervalSeconds, + double expectedCost) + { + // Act + var cost = PowerCostCalculationService.CalculateCostIncrement(powerWatts, pricePerKwh, pollIntervalSeconds); + + // Assert + var precision = expectedCost == 0 ? 1e-12 : Math.Abs(expectedCost) * 1e-9; + cost.Should().BeApproximately(expectedCost, precision, $"scenario: {scenario}"); } [Fact] - public void CalculateCostIncrement_WithZeroPower_ShouldReturnZero() + public void CalculateCostIncrement_ForGeneratedPowerSeries_ShouldBeProportionalToPower() { - var cost = PowerCostCalculationService.CalculateCostIncrement(0, DefaultPricePerKwh, 15); - cost.Should().Be(0); - } + // Arrange + const double pricePerKwh = 0.25; + const int pollIntervalSeconds = 15; + var samples = PowerMonitorTestData.CreatePowerSampleSeries(25); + var unitCost = PowerCostCalculationService.CalculateCostIncrement(1_000.0, pricePerKwh, pollIntervalSeconds); - [Fact] - public void CalculateCostIncrement_WithZeroPrice_ShouldReturnZero() - { - var cost = PowerCostCalculationService.CalculateCostIncrement(341.97, 0, 15); - cost.Should().Be(0); + // Act + var costs = samples + .Select(watts => PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds)) + .ToArray(); + + // Assert + costs.Should().BeInAscendingOrder("every generated sample is larger than the previous one"); + for (var i = 0; i < samples.Count; i++) + { + costs[i].Should().BeApproximately(samples[i] / 1_000.0 * unitCost, 1e-15); + } } #endregion @@ -72,41 +76,53 @@ public class PowerCostCalculationServiceTests [Fact] public void RecordCosts_ShouldCreateTotalAndOtherSnapshots() { - var now = new DateTime(2026, 3, 17, 10, 0, 0); - var result = CreateResult(); + // Arrange + var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation(); - _sut.RecordCosts(result, DefaultPricePerKwh, 15, now); + // Act + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now); - var totalSnapshot = _sut.GetTotalCostSnapshot(); - totalSnapshot.CostDaily.Should().BeGreaterThan(0); + // Assert + var expectedTotal = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); + var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts, PowerMonitorTestData.DefaultPricePerKwh); - var otherSnapshot = _sut.GetOtherCostSnapshot(); - otherSnapshot.CostDaily.Should().BeGreaterThan(0); + _sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expectedTotal, 1e-12); + _sut.GetOtherCostSnapshot().CostDaily.Should().BeApproximately(expectedOther, 1e-12); + _sut.GetTotalCostSnapshot().PartialWindow.Should().BeTrue(); } - [Fact] - public void RecordCosts_ShouldCreateDeviceSnapshots() + [Theory] + [InlineData("sensor.sonoff_100215c534_power")] + [InlineData("sensor.sonoff_10018909cb_power")] + public void RecordCosts_ShouldCreatePositiveDeviceSnapshotForEveryReading(string entityId) { - var now = new DateTime(2026, 3, 17, 10, 0, 0); - var result = CreateResult(); + // Arrange + var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation(); - _sut.RecordCosts(result, DefaultPricePerKwh, 15, now); + // Act + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now); - var ac = _sut.GetDeviceCostSnapshot("sensor.sonoff_100215c534_power"); - ac.CostDaily.Should().BeGreaterThan(0); - - var induction = _sut.GetDeviceCostSnapshot("sensor.sonoff_10018909cb_power"); - induction.CostDaily.Should().BeGreaterThan(0); + // Assert + var snapshot = _sut.GetDeviceCostSnapshot(entityId); + var expected = ExpectedCost(result.DevicePowerReadings[entityId], PowerMonitorTestData.DefaultPricePerKwh); + snapshot.CostDaily.Should().BeApproximately(expected, 1e-12); + snapshot.CostDaily.Should().BeGreaterThan(0); + snapshot.PartialWindow.Should().BeTrue(); } [Fact] public void RecordCosts_TotalCostShouldBeHigherThanOtherCost() { - var now = new DateTime(2026, 3, 17, 10, 0, 0); - var result = CreateResult(totalWatts: DefaultTotalWatts, smoothedOtherWatts: DefaultSmoothedOtherWatts); + // Arrange + var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation(); - _sut.RecordCosts(result, DefaultPricePerKwh, 15, now); + // Act + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now); + // Assert var total = _sut.GetTotalCostSnapshot(); var other = _sut.GetOtherCostSnapshot(); total.CostDaily.Should().BeGreaterThan(other.CostDaily); @@ -115,78 +131,334 @@ public class PowerCostCalculationServiceTests [Fact] public void RecordCosts_MultipleCalls_ShouldAccumulate() { - var now = new DateTime(2026, 3, 17, 10, 0, 0); - var result = CreateResult(); + // Arrange + var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation(); - _sut.RecordCosts(result, DefaultPricePerKwh, 15, now); + // Act + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now); var firstCost = _sut.GetTotalCostSnapshot().CostDaily; - _sut.RecordCosts(result, DefaultPricePerKwh, 15, now.AddSeconds(15)); + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15)); var secondCost = _sut.GetTotalCostSnapshot().CostDaily; + // Assert secondCost.Should().BeApproximately(firstCost * 2, 0.000001); } [Fact] public void RecordCosts_NewDeviceAppearing_ShouldCreateAccumulator() { - var now = new DateTime(2026, 3, 17, 10, 0, 0); - var result1 = CreateResult(deviceReadings: new Dictionary - { - ["sensor.sonoff_100215c534_power"] = 101.0 - }); + // Arrange + var now = PowerMonitorTestData.FixedNow; + var firstResult = PowerMonitorTestData.CreateCalculation( + deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0))); - _sut.RecordCosts(result1, DefaultPricePerKwh, 15, now); + // Act + _sut.RecordCosts(firstResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now); _sut.GetAllDeviceCostSnapshots().Should().HaveCount(1); - var result2 = CreateResult(deviceReadings: new Dictionary - { - ["sensor.sonoff_100215c534_power"] = 101.0, - ["sensor.sonoff_10018909cb_power"] = 109.93 - }); + _sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15)); - _sut.RecordCosts(result2, DefaultPricePerKwh, 15, now.AddSeconds(15)); + // Assert _sut.GetAllDeviceCostSnapshots().Should().HaveCount(2); } + [Fact] + public void RecordCosts_WhenDeviceDisappears_ShouldKeepItsPreviousAccumulator() + { + // Arrange + var now = PowerMonitorTestData.FixedNow; + _sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15, now); + var beforeDisappearance = _sut.GetDeviceCostSnapshot("sensor.sonoff_10018909cb_power").CostDaily; + + // Act + var singleDeviceResult = PowerMonitorTestData.CreateCalculation( + deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0))); + _sut.RecordCosts(singleDeviceResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15)); + + // Assert + _sut.GetAllDeviceCostSnapshots().Should().HaveCount(2); + _sut.GetDeviceCostSnapshot("sensor.sonoff_10018909cb_power").CostDaily.Should().Be(beforeDisappearance); + } + + [Fact] + public void RecordCosts_WithNoDeviceReadings_ShouldStillTrackTotals() + { + // Arrange + var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation(deviceReadings: new Dictionary()); + + // Act + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now); + + // Assert + _sut.GetAllDeviceCostSnapshots().Should().BeEmpty(); + _sut.GetTotalCostSnapshot().CostDaily.Should().BeGreaterThan(0); + } + + [Fact] + public void RecordCosts_WithZeroPower_ShouldCreateZeroCostSnapshots() + { + // Arrange + var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation( + totalWatts: 0, + smoothedOtherWatts: 0, + deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0))); + + // Act + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now); + + // Assert + _sut.GetTotalCostSnapshot().CostDaily.Should().Be(0); + _sut.GetOtherCostSnapshot().CostDaily.Should().Be(0); + _sut.GetDeviceCostSnapshot("sensor.sonoff_100215c534_power").CostDaily.Should().Be(0); + _sut.GetAllDeviceCostSnapshots().Should().HaveCount(1); + } + + [Fact] + public void RecordCosts_WithNegativeDevicePower_ShouldProduceNegativeDeviceCost() + { + // Arrange - a sensor glitch must flow through the pure cost math unchanged. + var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation( + deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.glitch_power", -500.0))); + + // Act + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now); + + // Assert + var expected = ExpectedCost(-500.0, PowerMonitorTestData.DefaultPricePerKwh); + _sut.GetDeviceCostSnapshot("sensor.glitch_power").CostDaily.Should().BeApproximately(expected, 1e-12); + _sut.GetDeviceCostSnapshot("sensor.glitch_power").CostDaily.Should().BeNegative(); + } + + [Fact] + public void RecordCosts_WithZeroPollInterval_ShouldTrackDevicesWithoutCost() + { + // Arrange + var now = PowerMonitorTestData.FixedNow; + + // Act + _sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 0, now); + + // Assert + _sut.GetTotalCostSnapshot().CostDaily.Should().Be(0); + _sut.GetAllDeviceCostSnapshots().Should().HaveCount(2); + _sut.GetAllDeviceCostSnapshots().Values.Should().OnlyContain(snapshot => snapshot.CostMonthly == 0); + } + + [Fact] + public void RecordCosts_When15MinWindowCrosses_ShouldResetAndStorePrevious() + { + // Arrange + var firstTimestamp = new DateTime(2026, 3, 17, 10, 14, 0); + var rolloverTimestamp = new DateTime(2026, 3, 17, 10, 15, 0); + var result = PowerMonitorTestData.CreateCalculation(); + var expected = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); + + // Act + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, firstTimestamp); + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, rolloverTimestamp); + + // Assert + var snapshot = _sut.GetTotalCostSnapshot(); + snapshot.Cost15Min.Should().BeApproximately(expected, 1e-12); + snapshot.Previous15Min.Should().BeApproximately(expected, 1e-12); + snapshot.PartialWindow.Should().BeFalse(); + } + + [Fact] + public void RecordCosts_WhenDayChanges_ShouldResetDailyWindow() + { + // Arrange + var beforeMidnight = new DateTime(2026, 3, 17, 23, 50, 0); + var afterMidnight = new DateTime(2026, 3, 18, 0, 5, 0); + var result = PowerMonitorTestData.CreateCalculation(); + var expected = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); + + // Act + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, beforeMidnight); + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, afterMidnight); + + // Assert + var snapshot = _sut.GetTotalCostSnapshot(); + snapshot.CostDaily.Should().BeApproximately(expected, 1e-12); + snapshot.PreviousDaily.Should().BeApproximately(expected, 1e-12); + } + + [Fact] + public void RecordCosts_WhenMonthChanges_ShouldResetMonthlyWindow() + { + // Arrange + var beforeMonthEnd = new DateTime(2026, 3, 31, 23, 59, 0); + var afterMonthStart = new DateTime(2026, 4, 1, 0, 0, 0); + var result = PowerMonitorTestData.CreateCalculation(); + var expected = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); + + // Act + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, beforeMonthEnd); + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, afterMonthStart); + + // Assert + var snapshot = _sut.GetTotalCostSnapshot(); + snapshot.CostMonthly.Should().BeApproximately(expected, 1e-12); + snapshot.PreviousMonthly.Should().BeApproximately(expected, 1e-12); + } + + [Fact] + public void RecordCosts_ForGeneratedQuarterHourDay_ShouldResetEverySlot() + { + // Arrange + const double pricePerKwh = 0.2; + var timestamps = PowerMonitorTestData.CreateSampleTimestamps(PowerMonitorTestData.FixedDayStart, 96); + var wattSamples = PowerMonitorTestData.CreatePowerSampleSeries(96); + var expectedPerSlot = timestamps + .Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds)) + .ToArray(); + + // Act + for (var slot = 0; slot < timestamps.Count; slot++) + { + var result = PowerMonitorTestData.CreateCalculation( + totalWatts: wattSamples[slot], + smoothedOtherWatts: wattSamples[slot] / 2, + deviceReadings: new Dictionary()); + _sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]); + } + + // Assert + var snapshot = _sut.GetTotalCostSnapshot(); + snapshot.Cost15Min.Should().BeApproximately(expectedPerSlot[^1], 1e-12); + snapshot.Previous15Min.Should().BeApproximately(expectedPerSlot[^2], 1e-12); + snapshot.CostDaily.Should().BeApproximately(expectedPerSlot.Sum(), 1e-9); + snapshot.PreviousDaily.Should().Be(0); + } + + [Fact] + public void RecordCosts_ForGeneratedHourlyDay_ShouldAccumulateDailyAndMonthlyTotals() + { + // Arrange + const int pollIntervalSeconds = PowerMonitorConsts.SecondsPerHour; + var windows = PowerMonitorTestData.CreateHourlyTariffWindows(PowerMonitorTestData.FixedDayStart); + var expectedPerHour = new List(); + + // Act + foreach (var (start, pricePerKwh) in windows) + { + var watts = 500.0 + (start.Hour * 125.0); + var result = PowerMonitorTestData.CreateCalculation( + totalWatts: watts, + smoothedOtherWatts: watts / 4, + deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2))); + _sut.RecordCosts(result, pricePerKwh, pollIntervalSeconds, start); + expectedPerHour.Add(ExpectedCost(watts, pricePerKwh, pollIntervalSeconds)); + } + + // Assert + var snapshot = _sut.GetTotalCostSnapshot(); + snapshot.CostDaily.Should().BeApproximately(expectedPerHour.Sum(), 1e-9); + snapshot.CostMonthly.Should().BeApproximately(expectedPerHour.Sum(), 1e-9); + snapshot.Cost1Hour.Should().BeApproximately(expectedPerHour[^1], 1e-12); + snapshot.Previous1Hour.Should().BeApproximately(expectedPerHour[^2], 1e-12); + } + #endregion #region Price management [Fact] - public void RecordCosts_WithValidPrice_ShouldUpdateLastKnownPrice() + public void InitialPrice_ShouldBeZeroAndLive() { - var now = new DateTime(2026, 3, 17, 10, 0, 0); - var result = CreateResult(); - - _sut.RecordCosts(result, 0.2492, 15, now); - - _sut.LastKnownPrice.Should().Be(0.2492); + _sut.LastKnownPrice.Should().Be(0); _sut.PriceSource.Should().Be("live"); } - [Fact] - public void RecordCosts_WithZeroPrice_ShouldUseFallback() + [Theory] + [InlineData(0.0001)] + [InlineData(0.1791)] + [InlineData(0.2492)] + [InlineData(1.5)] + [InlineData(100.0)] + public void RecordCosts_WithPositivePrice_ShouldStoreLivePrice(double price) { - var now = new DateTime(2026, 3, 17, 10, 0, 0); - var result = CreateResult(); + // Act + _sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), price, 15, PowerMonitorTestData.FixedNow); - _sut.RecordCosts(result, DefaultPricePerKwh, 15, now); - _sut.RecordCosts(result, 0, 15, now.AddSeconds(15)); - - _sut.LastKnownPrice.Should().Be(DefaultPricePerKwh); + // Assert + _sut.LastKnownPrice.Should().Be(price); _sut.PriceSource.Should().Be("live"); } - [Fact] - public void SetPrice_ShouldUpdatePriceAndMarkAsStale() + [Theory] + [InlineData(0.0)] + [InlineData(-0.0001)] + [InlineData(-5.0)] + public void RecordCosts_WithNonPositivePrice_ShouldFallBackToLastKnownPrice(double invalidPrice) { - _sut.SetPrice(0.1891); + // Arrange + var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation(); + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now); - _sut.LastKnownPrice.Should().Be(0.1891); + // Act + _sut.RecordCosts(result, invalidPrice, 15, now.AddSeconds(15)); + + // Assert + _sut.LastKnownPrice.Should().Be(PowerMonitorTestData.DefaultPricePerKwh); + _sut.PriceSource.Should().Be("live"); + var expected = 2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh); + _sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12); + } + + [Fact] + public void RecordCosts_WithZeroPriceAndNoPriorPrice_ShouldRecordZeroCost() + { + // Arrange + var result = PowerMonitorTestData.CreateCalculation(); + + // Act + _sut.RecordCosts(result, 0, 15, PowerMonitorTestData.FixedNow); + + // Assert + _sut.LastKnownPrice.Should().Be(0); + _sut.GetTotalCostSnapshot().CostDaily.Should().Be(0); + _sut.GetAllDeviceCostSnapshots().Should().HaveCount(2); + } + + [Theory] + [InlineData(0.1891)] + [InlineData(0.0)] + [InlineData(-1.25)] + [InlineData(12.5)] + public void SetPrice_ShouldUpdatePriceAndMarkAsStale(double price) + { + // Act + _sut.SetPrice(price); + + // Assert + _sut.LastKnownPrice.Should().Be(price); _sut.PriceSource.Should().Be("stale"); } + [Fact] + public void RecordCosts_AfterSetPrice_WithZeroPrice_ShouldKeepStalePriceAndSource() + { + // Arrange + var now = PowerMonitorTestData.FixedNow; + _sut.SetPrice(0.5); + + // Act + _sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), 0, 15, now); + + // Assert + _sut.LastKnownPrice.Should().Be(0.5); + _sut.PriceSource.Should().Be("stale"); + var expected = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, 0.5); + _sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12); + } + #endregion #region GetAllDeviceCostSnapshots @@ -197,11 +469,20 @@ public class PowerCostCalculationServiceTests _sut.GetAllDeviceCostSnapshots().Should().BeEmpty(); } - [Fact] - public void GetDeviceCostSnapshot_UnknownDevice_ShouldReturnEmptySnapshot() + [Theory] + [InlineData("sensor.unknown")] + [InlineData("")] + [InlineData(" ")] + [InlineData("SENSOR.SONOFF_100215C534_POWER")] + public void GetDeviceCostSnapshot_ForUnknownDevice_ShouldReturnEmptySnapshot(string entityId) { - var snapshot = _sut.GetDeviceCostSnapshot("sensor.unknown"); + // Act + var snapshot = _sut.GetDeviceCostSnapshot(entityId); + + // Assert + snapshot.Cost15Min.Should().Be(0); snapshot.CostDaily.Should().Be(0); + snapshot.CostMonthly.Should().Be(0); snapshot.PartialWindow.Should().BeTrue(); } @@ -209,19 +490,21 @@ public class PowerCostCalculationServiceTests #region Snapshot defaults - [Fact] - public void GetTotalCostSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot() + [Theory] + [InlineData(CostBucket.Total)] + [InlineData(CostBucket.Other)] + public void GetSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot(CostBucket bucket) { - var snapshot = _sut.GetTotalCostSnapshot(); - snapshot.CostDaily.Should().Be(0); - snapshot.PartialWindow.Should().BeTrue(); - } + // Act + var snapshot = bucket == CostBucket.Total + ? _sut.GetTotalCostSnapshot() + : _sut.GetOtherCostSnapshot(); - [Fact] - public void GetOtherCostSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot() - { - var snapshot = _sut.GetOtherCostSnapshot(); + // Assert + snapshot.Cost15Min.Should().Be(0); + snapshot.Cost1Hour.Should().Be(0); snapshot.CostDaily.Should().Be(0); + snapshot.CostMonthly.Should().Be(0); snapshot.PartialWindow.Should().BeTrue(); } @@ -232,23 +515,26 @@ public class PowerCostCalculationServiceTests [Fact] public async Task RecordCosts_ConcurrentAccess_ShouldNotLoseData() { - var now = new DateTime(2026, 3, 17, 10, 0, 0); - var result = CreateResult(totalWatts: DefaultTotalWatts, smoothedOtherWatts: DefaultSmoothedOtherWatts); + // Arrange + var now = PowerMonitorTestData.FixedNow; + var result = PowerMonitorTestData.CreateCalculation(); const int callsPerThread = 100; const int threadCount = 10; + // Act var tasks = Enumerable.Range(0, threadCount) .Select(_ => Task.Run(() => { for (var i = 0; i < callsPerThread; i++) { - _sut.RecordCosts(result, DefaultPricePerKwh, 15, now.AddSeconds(1)); + _sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1)); } })) .ToArray(); await Task.WhenAll(tasks); + // Assert var total = _sut.GetTotalCostSnapshot(); total.CostDaily.Should().BeGreaterThan(0); @@ -257,4 +543,12 @@ public class PowerCostCalculationServiceTests } #endregion + + private static double ExpectedCost( + double powerWatts, + double pricePerKwh, + int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds) => + powerWatts / PowerMonitorConsts.WattsPerKilowatt + * pricePerKwh + * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour); } diff --git a/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs b/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs index 2556909..8cf033b 100644 --- a/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs @@ -1,3 +1,4 @@ +using System.Globalization; using FluentAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -12,8 +13,8 @@ namespace PowerMonitor.Manager.Tests; public class PowerLimitEnforcementServiceTests { - private const string BoilerSwitch = "switch.sonoff_1002230e32"; - private const string AutoManagement = "switch.boilermonitor_auto_management"; + private const string BoilerSwitch = PowerMonitorTestData.BoilerSwitchEntityId; + private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId; private readonly Mock _haContextMock; private readonly Mock> _loggerMock; @@ -24,16 +25,8 @@ public class PowerLimitEnforcementServiceTests { _haContextMock = new Mock(); _loggerMock = new Mock>(); - _timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); - _options = new PowerMonitorOptions - { - EnforceLimitEnabled = true, - PowerLimitWatts = 5500, - RecoverySeconds = 600, - LimitCooldownSeconds = 30, - EnforceSwitchOffEntityIds = [BoilerSwitch], - PauseAndRestoreEntityIds = [AutoManagement] - }; + _timeProvider = new FakeTimeProvider(PowerMonitorTestData.FixedUtcNow); + _options = PowerMonitorTestData.CreateLimitEnforcementOptions(); } private PowerLimitEnforcementService CreateSut() => @@ -43,63 +36,96 @@ public class PowerLimitEnforcementServiceTests Options.Create(_options), _timeProvider); - private static bool IsTurnOffCall(string domain, string service, string entityId) => - domain == "switch" && service == "turn_off"; + private void VerifyNoServiceCalls() => + _haContextMock.Verify( + x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), + Times.Never); - private static bool IsTurnOnCall(string domain, string service, string entityId) => - domain == "switch" && service == "turn_on"; + private void VerifyTurnOff(string entityId, int expectedCalls) => + _haContextMock.Verify( + x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(entityId)), null), + Times.Exactly(expectedCalls)); - [Fact] - public void EnforceLimit_WhenDisabled_ShouldNotCallAnyService() + private void VerifyTurnOn(string entityId, int expectedCalls) => + _haContextMock.Verify( + x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(entityId)), null), + Times.Exactly(expectedCalls)); + + private void VerifyNotificationCreated(int expectedCalls) => + _haContextMock.Verify( + x => x.CallService("persistent_notification", "create", It.IsAny(), It.IsAny()), + Times.Exactly(expectedCalls)); + + private void VerifyNotificationDismissed(int expectedCalls) => + _haContextMock.Verify( + x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), + Times.Exactly(expectedCalls)); + + #region EnforceLimit + + [Theory] + [InlineData(0.0)] + [InlineData(5500.0)] + [InlineData(6000.0)] + [InlineData(1_000_000.0)] + public void EnforceLimit_WhenDisabled_ShouldNotCallAnyService(double powerWatts) { + // Arrange _options.EnforceLimitEnabled = false; var sut = CreateSut(); - sut.EnforceLimit(6000); + // Act + sut.EnforceLimit(powerWatts); - _haContextMock.Verify( - x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); + // Assert + VerifyNoServiceCalls(); sut.IsLimitActive.Should().BeFalse(); } - [Fact] - public void EnforceLimit_WhenPowerBelowLimit_ShouldNotEnforce() + [Theory] + [InlineData(-1000.0)] + [InlineData(0.0)] + [InlineData(0.5)] + [InlineData(2749.99)] + [InlineData(5499.99)] + [InlineData(5500.0)] + public void EnforceLimit_WhenPowerAtOrBelowLimit_ShouldNotEnforce(double powerWatts) { + // Arrange var sut = CreateSut(); - sut.EnforceLimit(5000); + // Act + sut.EnforceLimit(powerWatts); - sut.IsLimitActive.Should().BeFalse(); - _haContextMock.Verify( - x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); + // Assert + sut.IsLimitActive.Should().BeFalse("power equal to the limit must not trigger (strict greater-than)"); + VerifyNoServiceCalls(); } - [Fact] - public void EnforceLimit_WhenPowerExceedsLimit_ShouldTurnOffSwitchesAndPauseMonitors() + [Theory] + [InlineData(5500.01)] + [InlineData(6000.0)] + [InlineData(15_000.0)] + [InlineData(1_000_000.0)] + public void EnforceLimit_WhenPowerExceedsLimit_ShouldTurnOffSwitchesAndPauseMonitors(double powerWatts) { + // Arrange var sut = CreateSut(); - sut.EnforceLimit(6000); + // Act + sut.EnforceLimit(powerWatts); + // Assert sut.IsLimitActive.Should().BeTrue(); - // turn_off called for boiler switch + auto_management - _haContextMock.Verify( - x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(BoilerSwitch)), null), - Times.Once); - _haContextMock.Verify( - x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(AutoManagement)), null), - Times.Once); - // notification created - _haContextMock.Verify( - x => x.CallService("persistent_notification", "create", It.IsAny(), It.IsAny()), - Times.Once); + VerifyTurnOff(BoilerSwitch, 1); + VerifyTurnOff(AutoManagement, 1); + VerifyNotificationCreated(1); } [Fact] public void EnforceLimit_WhenBreached_ShouldTurnOffBoilerBeforeAutoManagement() { + // Arrange var calls = new List<(string domain, string service, string? entityId)>(); _haContextMock .Setup(x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) @@ -107,8 +133,10 @@ public class PowerLimitEnforcementServiceTests calls.Add((d, s, t?.EntityIds?.FirstOrDefault()))); var sut = CreateSut(); + // Act sut.EnforceLimit(6000); + // Assert var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList(); turnOffCalls.Should().HaveCount(2); turnOffCalls[0].entityId.Should().Be(BoilerSwitch, "boiler switch must be turned off before auto_management (race-safe order)"); @@ -116,230 +144,304 @@ public class PowerLimitEnforcementServiceTests } [Fact] - public void EnforceLimit_WhenAlreadyActiveAndBeforeRecoveryTime_ShouldDoNothing() + public void EnforceLimit_WithMultipleConfiguredEntities_ShouldTurnOffEveryEntityInConfiguredOrder() { + // Arrange + _options.EnforceSwitchOffEntityIds = ["switch.high_load_a", "switch.high_load_b"]; + _options.PauseAndRestoreEntityIds = ["switch.monitor_c"]; + var calls = new List(); + _haContextMock + .Setup(x => x.CallService(It.IsAny(), "turn_off", It.IsAny(), It.IsAny())) + .Callback((_, _, target, _) => + calls.Add(target?.EntityIds?.FirstOrDefault())); var sut = CreateSut(); - sut.EnforceLimit(6000); - _haContextMock.Invocations.Clear(); - // advance less than recovery - _timeProvider.Advance(TimeSpan.FromMinutes(5)); - sut.EnforceLimit(5000); + // Act + sut.EnforceLimit(7000); + // Assert + calls.Should().Equal("switch.high_load_a", "switch.high_load_b", "switch.monitor_c"); sut.IsLimitActive.Should().BeTrue(); - _haContextMock.Verify( - x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); } [Fact] - public void EnforceLimit_WhenRecoveryTimeReachedAndPowerBelowLimit_ShouldRestoreMonitorsAndNotTurnBoilerOn() + public void EnforceLimit_WithNoConfiguredEntities_ShouldStillNotifyAndActivate() { + // Arrange + _options.EnforceSwitchOffEntityIds = []; + _options.PauseAndRestoreEntityIds = []; var sut = CreateSut(); + + // Act sut.EnforceLimit(6000); - _haContextMock.Invocations.Clear(); - _timeProvider.Advance(TimeSpan.FromSeconds(601)); - sut.EnforceLimit(4000); - - sut.IsLimitActive.Should().BeFalse(); - // auto_management turned back ON + // Assert + sut.IsLimitActive.Should().BeTrue(); + VerifyNotificationCreated(1); _haContextMock.Verify( - x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(AutoManagement)), null), - Times.Once); - // boiler switch should NOT be turned back on - _haContextMock.Verify( - x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(BoilerSwitch)), null), + x => x.CallService("switch", It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); - // notification dismissed - _haContextMock.Verify( - x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), - Times.Once); } - [Fact] - public void EnforceLimit_WhenRecoveryTimeReachedButPowerStillHigh_ShouldStayEnforcedAndResetTimer() + #endregion + + #region Recovery + + public static IEnumerable 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] + ]; + + [Theory] + [MemberData(nameof(RecoveryCases))] + public void EnforceLimit_AfterEnforcement_ShouldEvaluateRecovery( + string scenario, + int secondsAfterEnforcement, + double powerWatts, + bool expectedLimitActive, + int expectedRecoveryActions) { + // Arrange var sut = CreateSut(); sut.EnforceLimit(6000); _haContextMock.Invocations.Clear(); - _timeProvider.Advance(TimeSpan.FromSeconds(601)); - sut.EnforceLimit(5800); + // Act + _timeProvider.Advance(TimeSpan.FromSeconds(secondsAfterEnforcement)); + sut.EnforceLimit(powerWatts); - sut.IsLimitActive.Should().BeTrue(); - // no restore, no dismiss - _haContextMock.Verify( - x => x.CallService("switch", "turn_on", It.IsAny(), It.IsAny()), - Times.Never); - _haContextMock.Verify( - x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), - Times.Never); + // Assert + sut.IsLimitActive.Should().Be(expectedLimitActive, $"scenario: {scenario}"); + VerifyTurnOn(AutoManagement, expectedRecoveryActions); + VerifyTurnOn(BoilerSwitch, 0); + VerifyNotificationDismissed(expectedRecoveryActions); } [Fact] public void EnforceLimit_WhenRecoveryTimeReachedButPowerStillHigh_ShouldAllowAnotherRecoveryCheckAfterWait() { + // Arrange var sut = CreateSut(); sut.EnforceLimit(6000); - // first recovery check - still high, timer resets + // Act - first recovery check finds power still high and resets the timer _timeProvider.Advance(TimeSpan.FromSeconds(601)); sut.EnforceLimit(5800); sut.IsLimitActive.Should().BeTrue(); - // immediately after - not enough time, no-op - sut.EnforceLimit(3000); + var immediatelyAfter = sut; + immediatelyAfter.EnforceLimit(3000); + + // Assert - not enough time has passed for another check sut.IsLimitActive.Should().BeTrue(); - // after another full wait - power dropped, recovers + // Act - after another full wait the power has dropped _timeProvider.Advance(TimeSpan.FromSeconds(601)); sut.EnforceLimit(3000); + + // Assert sut.IsLimitActive.Should().BeFalse(); + VerifyTurnOn(AutoManagement, 1); } - [Fact] - public void EnforceLimit_WhenCooldownActive_ShouldNotReEnforce() + #endregion + + #region Cooldown + + [Theory] + [InlineData(0, false)] + [InlineData(29, false)] + [InlineData(30, true)] + [InlineData(31, true)] + [InlineData(600, true)] + public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery, bool expectedLimitActive) { + // Arrange var sut = CreateSut(); sut.EnforceLimit(6000); - sut.IsLimitActive.Should().BeTrue(); - - // recover so we can re-trigger _timeProvider.Advance(TimeSpan.FromSeconds(601)); sut.EnforceLimit(3000); sut.IsLimitActive.Should().BeFalse(); _haContextMock.Invocations.Clear(); - // immediately breach again - within cooldown, should NOT enforce + // Act + _timeProvider.Advance(TimeSpan.FromSeconds(secondsAfterRecovery)); sut.EnforceLimit(6000); - sut.IsLimitActive.Should().BeFalse("cooldown should block immediate re-enforcement"); - _haContextMock.Verify( - x => x.CallService("switch", "turn_off", It.IsAny(), It.IsAny()), - Times.Never); + + // Assert + sut.IsLimitActive.Should().Be(expectedLimitActive); + + if (expectedLimitActive) + { + VerifyTurnOff(BoilerSwitch, 1); + VerifyTurnOff(AutoManagement, 1); + VerifyNotificationCreated(1); + } + else + { + VerifyNoServiceCalls(); + } } [Fact] - public void EnforceLimit_WhenCooldownPassed_ShouldReEnforce() + public void EnforceLimit_ImmediatelyAfterManualReset_ShouldNotReEnforceWithinCooldown() { + // Arrange var sut = CreateSut(); - sut.EnforceLimit(6000); - _timeProvider.Advance(TimeSpan.FromSeconds(601)); - sut.EnforceLimit(3000); - sut.IsLimitActive.Should().BeFalse(); - - // wait past cooldown - _timeProvider.Advance(TimeSpan.FromSeconds(31)); + sut.TriggerLimitBreach(); + sut.ResetLimitBreach(); _haContextMock.Invocations.Clear(); + // Act sut.EnforceLimit(6000); - sut.IsLimitActive.Should().BeTrue(); - _haContextMock.Verify( - x => x.CallService("switch", "turn_off", It.IsAny(), It.IsAny()), - Times.AtLeastOnce); + + // Assert + sut.IsLimitActive.Should().BeFalse("the manual reset starts the cooldown window"); + VerifyNoServiceCalls(); + } + + #endregion + + #region BuildLimitMessage + + [Theory] + [InlineData("typical breach", 6.0, 5.5, "6.00 kW", "5.5 kW")] + [InlineData("rounds current to two decimals", 5.999, 5.549, "6.00 kW", "5.5 kW")] + [InlineData("zero current", 0.0, 5.5, "0.00 kW", "5.5 kW")] + [InlineData("negative current", -1.0, 5.5, "-1.00 kW", "5.5 kW")] + [InlineData("large values", 123.456, 100.0, "123.46 kW", "100.0 kW")] + public void BuildLimitMessage_ShouldContainCurrentAndLimitInKw( + string scenario, + double currentKw, + double limitKw, + string expectedCurrentText, + string expectedLimitText) + { + // Act + var message = PowerLimitEnforcementService.BuildLimitMessage(currentKw, limitKw); + + // Assert + message.Should().Contain(expectedCurrentText, $"scenario: {scenario}"); + message.Should().Contain(expectedLimitText, $"scenario: {scenario}"); + message.Should().Contain("exceeded the limit"); } [Fact] - public void EnforceLimit_WhenExactlyAtLimit_ShouldNotEnforce() + public void BuildLimitMessage_WithCommaDecimalCulture_ShouldStillUseInvariantFormatting() { - var sut = CreateSut(); + // Arrange + var originalCulture = CultureInfo.CurrentCulture; - sut.EnforceLimit(5500); + try + { + CultureInfo.CurrentCulture = new CultureInfo("de-DE"); - sut.IsLimitActive.Should().BeFalse("power equal to limit should not trigger (strict greater-than)"); - _haContextMock.Verify( - x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); + // Act + var message = PowerLimitEnforcementService.BuildLimitMessage(6.0, 5.5); + + // Assert + message.Should().Contain("6.00 kW"); + message.Should().Contain("5.5 kW"); + } + finally + { + CultureInfo.CurrentCulture = originalCulture; + } } - [Fact] - public void BuildLimitMessage_ShouldContainCurrentAndLimitInKw() - { - var message = PowerLimitEnforcementService.BuildLimitMessage(6.0, 5.5); + #endregion - message.Should().Contain("6.00 kW"); - message.Should().Contain("5.5 kW"); - } + #region Debug triggers [Fact] public void TriggerLimitBreach_WhenNotActive_ShouldEnforceRegardlessOfPower() { + // Arrange var sut = CreateSut(); + // Act sut.TriggerLimitBreach(); + // Assert sut.IsLimitActive.Should().BeTrue(); _haContextMock.Verify( - x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(BoilerSwitch)), null), - Times.Once); - _haContextMock.Verify( - x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(AutoManagement)), null), - Times.Once); - _haContextMock.Verify( - x => x.CallService("persistent_notification", "create", It.IsAny(), It.IsAny()), - Times.Once); + x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), + Times.Exactly(3)); + VerifyTurnOff(BoilerSwitch, 1); + VerifyTurnOff(AutoManagement, 1); + VerifyNotificationCreated(1); } [Fact] public void TriggerLimitBreach_WhenAlreadyActive_ShouldDoNothing() { + // Arrange var sut = CreateSut(); sut.TriggerLimitBreach(); _haContextMock.Invocations.Clear(); + // Act sut.TriggerLimitBreach(); - _haContextMock.Verify( - x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); + // Assert + VerifyNoServiceCalls(); } [Fact] public void ResetLimitBreach_WhenActive_ShouldRecoverWithoutWaiting() { + // Arrange var sut = CreateSut(); sut.TriggerLimitBreach(); _haContextMock.Invocations.Clear(); + // Act sut.ResetLimitBreach(); + // Assert sut.IsLimitActive.Should().BeFalse(); - _haContextMock.Verify( - x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(AutoManagement)), null), - Times.Once); - _haContextMock.Verify( - x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), - Times.Once); - // boiler switch should NOT be turned on - _haContextMock.Verify( - x => x.CallService("switch", "turn_on", It.Is(t => t.EntityIds!.Contains(BoilerSwitch)), null), - Times.Never); + VerifyTurnOn(AutoManagement, 1); + VerifyTurnOn(BoilerSwitch, 0); + VerifyNotificationDismissed(1); } [Fact] public void ResetLimitBreach_WhenNotActive_ShouldDoNothing() { + // Arrange var sut = CreateSut(); + // Act sut.ResetLimitBreach(); - _haContextMock.Verify( - x => x.CallService(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), - Times.Never); + // Assert + VerifyNoServiceCalls(); } [Fact] public void TriggerLimitBreach_WhenDisabled_ShouldStillEnforce() { + // Arrange _options.EnforceLimitEnabled = false; var sut = CreateSut(); + // Act sut.TriggerLimitBreach(); + // Assert sut.IsLimitActive.Should().BeTrue("debug trigger bypasses EnforceLimitEnabled so the button always works"); - _haContextMock.Verify( - x => x.CallService("switch", "turn_off", It.IsAny(), It.IsAny()), - Times.AtLeastOnce); + VerifyTurnOff(BoilerSwitch, 1); + VerifyNotificationCreated(1); } -} \ No newline at end of file + + #endregion +} diff --git a/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj b/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj index 5bbe0f3..66b8ebf 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj +++ b/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj @@ -8,19 +8,19 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + diff --git a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs index e1e2ac8..ac96e8c 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs @@ -10,6 +10,24 @@ namespace PowerMonitor.Manager.Tests; public class PowerMonitorEntityServiceTests { + private static readonly string[] SystemEntityIds = + [ + "sensor.powermonitor_total_power", + "sensor.powermonitor_total_cost_15min", + "sensor.powermonitor_total_cost_1h", + "sensor.powermonitor_total_cost_daily", + "sensor.powermonitor_total_cost_monthly", + "sensor.powermonitor_other_power", + "sensor.powermonitor_other_cost_15min", + "sensor.powermonitor_other_cost_1h", + "sensor.powermonitor_other_cost_daily", + "sensor.powermonitor_other_cost_monthly", + "binary_sensor.powermonitor_anomaly", + "sensor.powermonitor_status", + "button.powermonitor_rediscover_sensors", + "button.powermonitor_trigger_limit_breach" + ]; + private readonly Mock _entityManagerMock; private readonly Mock> _loggerMock; private readonly PowerMonitorEntityService _sut; @@ -18,6 +36,10 @@ public class PowerMonitorEntityServiceTests { _entityManagerMock = new Mock(); _loggerMock = new Mock>(); + _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())).Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())).Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())).Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())).Returns(Task.CompletedTask); _sut = new PowerMonitorEntityService(_entityManagerMock.Object, _loggerMock.Object); } @@ -26,77 +48,138 @@ public class PowerMonitorEntityServiceTests [Fact] public void GetSystemEntitiesList_ShouldReturnAll14SystemEntities() { + // Act var result = _sut.GetSystemEntitiesList(); + // Assert result.Should().HaveCount(14); } - [Fact] - public void GetSystemEntitiesList_ShouldContainAllExpectedEntityIds() + [Theory] + [InlineData("sensor.powermonitor_total_power")] + [InlineData("sensor.powermonitor_total_cost_15min")] + [InlineData("sensor.powermonitor_total_cost_1h")] + [InlineData("sensor.powermonitor_total_cost_daily")] + [InlineData("sensor.powermonitor_total_cost_monthly")] + [InlineData("sensor.powermonitor_other_power")] + [InlineData("sensor.powermonitor_other_cost_15min")] + [InlineData("sensor.powermonitor_other_cost_1h")] + [InlineData("sensor.powermonitor_other_cost_daily")] + [InlineData("sensor.powermonitor_other_cost_monthly")] + [InlineData("binary_sensor.powermonitor_anomaly")] + [InlineData("sensor.powermonitor_status")] + [InlineData("button.powermonitor_rediscover_sensors")] + [InlineData("button.powermonitor_trigger_limit_breach")] + public void GetSystemEntitiesList_ShouldContainExpectedEntityId(string entityId) { + // Act var result = _sut.GetSystemEntitiesList(); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_power"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_15min"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_1h"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_daily"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_monthly"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_power"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_15min"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_1h"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_daily"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_monthly"); - result.Should().Contain(e => e.EntityId == "binary_sensor.powermonitor_anomaly"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_status"); - result.Should().Contain(e => e.EntityId == "button.powermonitor_rediscover_sensors"); - result.Should().Contain(e => e.EntityId == "button.powermonitor_trigger_limit_breach"); + // Assert + result.Should().Contain(entity => entity.EntityId == entityId); } [Fact] public void GetSystemEntitiesList_AllEntities_ShouldHaveUniqueEntityIds() { + // Act var result = _sut.GetSystemEntitiesList(); - result.Select(e => e.EntityId).Should().OnlyHaveUniqueItems(); + // Assert + result.Select(entity => entity.EntityId).Should().OnlyHaveUniqueItems(); + } + + [Fact] + public void GetSystemEntitiesList_AllEntities_ShouldExposeCreationOptions() + { + // Act + var result = _sut.GetSystemEntitiesList(); + + // Assert + result.Should().OnlyContain(entity => entity.Options != null && entity.Options.UniqueId == entity.EntityId); } #endregion - #region GetDeviceEntities + #region GetPowerDeviceEntitiesNames + + public static IEnumerable 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"] + ]; + + [Theory] + [MemberData(nameof(DeviceEntityCases))] + public void GetPowerDeviceEntitiesNames_ShouldReturnFourCostEntitiesPerDevice( + string scenario, + string entityId, + string friendlyName, + string expectedDeviceName) + { + // Arrange + var sensor = PowerMonitorTestData.CreateSensor(entityId, friendlyName); + + // Act + var result = PowerMonitorEntityService.GetPowerDeviceEntitiesNames(sensor).ToList(); + + // Assert + result.Should().HaveCount(4, $"scenario: {scenario}"); + result.Select(entity => entity.EntityId).Should().BeEquivalentTo(new[] + { + $"sensor.powermonitor_{expectedDeviceName}_cost_15min", + $"sensor.powermonitor_{expectedDeviceName}_cost_1h", + $"sensor.powermonitor_{expectedDeviceName}_cost_daily", + $"sensor.powermonitor_{expectedDeviceName}_cost_monthly" + }, $"scenario: {scenario}"); + result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}"); + result.Select(entity => entity.Name).Should().BeEquivalentTo(new[] + { + $"{friendlyName} cost (15 min)", + $"{friendlyName} cost (1h)", + $"{friendlyName} cost (daily)", + $"{friendlyName} cost (monthly)" + }, $"scenario: {scenario}"); + } [Fact] - public void GetDeviceEntities_ShouldReturn4CostEntitiesPerDevice() + public void PowerMonitorEntity_WhenNameIsBlank_ShouldFallBackToIdentifier() { - var sensor = new PowerSensorInfo - { - EntityId = "sensor.sonoff_1002230e32_power", - FriendlyName = "Sonoff Power", - DeviceName = "sonoff_1002230e32" - }; + // Arrange - PowerMonitorEntity falls back to the identifier so MQTT entities always have a name. + var entity = new PowerMonitorEntity("sensor", "powermonitor_test", " "); - var result = PowerMonitorEntityService.GetDeviceEntities(sensor).ToList(); - - result.Should().HaveCount(4); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_15min"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_1h"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_daily"); - result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_monthly"); + // Assert + entity.EntityId.Should().Be("sensor.powermonitor_test"); + entity.Name.Should().Be("powermonitor_test"); + entity.Options.Should().NotBeNull(); + entity.Options!.UniqueId.Should().Be("sensor.powermonitor_test"); + entity.Options!.Name.Should().Be("powermonitor_test"); } #endregion #region GetDeviceCostEntityIds - [Fact] - public void GetDeviceCostEntityIds_ShouldReturn4EntityIds() + [Theory] + [InlineData("sonoff_abc")] + [InlineData("tv")] + [InlineData("akvariumas")] + public void GetDeviceCostEntityIds_ShouldReturnFourEntityIds(string deviceName) { - var result = PowerMonitorEntityService.GetDeviceCostEntityIds("sonoff_abc").ToList(); + // Act + var result = PowerMonitorEntityService.GetDeviceCostEntityIds(deviceName).ToList(); + // Assert result.Should().HaveCount(4); - result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_15min"); - result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_1h"); - result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_daily"); - result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_monthly"); + result.Should().BeEquivalentTo(new[] + { + $"sensor.powermonitor_{deviceName}_cost_15min", + $"sensor.powermonitor_{deviceName}_cost_1h", + $"sensor.powermonitor_{deviceName}_cost_daily", + $"sensor.powermonitor_{deviceName}_cost_monthly" + }); } #endregion @@ -106,32 +189,25 @@ public class PowerMonitorEntityServiceTests [Fact] public async Task CreateSystemEntitiesAsync_ShouldCreateAll14Entities() { - _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) - .Returns(Task.CompletedTask); - + // Act await _sut.CreateSystemEntitiesAsync(); + // Assert _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(14)); } [Fact] - public async Task CreateSystemEntitiesAsync_WhenOneEntityFails_ShouldContinueWithOthers() + public async Task CreateSystemEntitiesAsync_WhenSomeEntitiesFail_ShouldContinueWithOthers() { - var callCount = 0; - _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) - .Returns(() => - { - callCount++; - if (callCount == 3) - { - throw new InvalidOperationException("Entity creation failed"); - } - - return Task.CompletedTask; - }); + // Arrange - both 1h cost entities fail, the remaining twelve must still be created. + _entityManagerMock + .Setup(em => em.CreateEntityAsync(It.Is(entity => entity.Identifier.EndsWith("_cost_1h")))) + .ThrowsAsync(new InvalidOperationException("Entity creation failed")); + // Act await _sut.CreateSystemEntitiesAsync(); + // Assert _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(14)); } @@ -139,69 +215,143 @@ public class PowerMonitorEntityServiceTests #region CreateDeviceEntitiesAsync - [Fact] - public async Task CreateDeviceEntitiesAsync_ShouldCreate4EntitiesPerDevice() + [Theory] + [InlineData(0, 0)] + [InlineData(1, 4)] + [InlineData(2, 8)] + [InlineData(5, 20)] + public async Task CreateDeviceEntitiesAsync_ShouldCreateFourEntitiesPerSensor(int sensorCount, int expectedCreates) { - _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) - .Returns(Task.CompletedTask); - - var sensors = new List - { - new() { EntityId = "sensor.sonoff_100215c534_power", FriendlyName = "AC Power", DeviceName = "sonoff_100215c534" }, - new() { EntityId = "sensor.sonoff_10018909cb_power", FriendlyName = "Induction Power", DeviceName = "sonoff_10018909cb" } - }; + // Arrange + var sensors = Enumerable.Range(0, sensorCount) + .Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}")) + .ToList(); + // Act await _sut.CreateDeviceEntitiesAsync(sensors); - _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(8)); + // Assert + _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(expectedCreates)); } #endregion #region ResetEntitiesAsync - [Fact] - public async Task ResetEntitiesAsync_ShouldSetDefaultStates() + [Theory] + [InlineData("sensor.powermonitor_total_power", "0")] + [InlineData("sensor.powermonitor_total_cost_15min", "0")] + [InlineData("sensor.powermonitor_total_cost_1h", "0")] + [InlineData("sensor.powermonitor_total_cost_daily", "0")] + [InlineData("sensor.powermonitor_total_cost_monthly", "0")] + [InlineData("sensor.powermonitor_other_power", "0")] + [InlineData("sensor.powermonitor_other_cost_15min", "0")] + [InlineData("sensor.powermonitor_other_cost_1h", "0")] + [InlineData("sensor.powermonitor_other_cost_daily", "0")] + [InlineData("sensor.powermonitor_other_cost_monthly", "0")] + [InlineData("binary_sensor.powermonitor_anomaly", "off")] + [InlineData("sensor.powermonitor_status", "initializing")] + public async Task ResetEntitiesAsync_ShouldSetExpectedDefaultState(string entityId, string expectedState) { - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - + // Act await _sut.ResetEntitiesAsync(); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", "0"), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", "0"), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "off"), Times.Once); + // Assert + _entityManagerMock.Verify(em => em.SetEntityState(entityId, expectedState), Times.Once); + } + + [Fact] + public async Task ResetEntitiesAsync_ShouldSetExactlyTwelveStates() + { + // Act + await _sut.ResetEntitiesAsync(); + + // Assert + _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(12)); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "initializing"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "off"), Times.Once); + } + + [Fact] + public async Task ResetEntitiesAsync_WhenStateWriteFails_ShouldNotRethrow() + { + // Arrange + _entityManagerMock + .Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("Failed")); + + // Act + var act = () => _sut.ResetEntitiesAsync(); + + // Assert + await act.Should().NotThrowAsync(); _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(12)); } #endregion - #region CleanupEntitiesAsync + #region RemoveSystemEntitiesAsync [Fact] - public async Task CleanupEntitiesAsync_ShouldRemoveAllSystemEntities() + public async Task RemoveSystemEntitiesAsync_ShouldRemoveAllSystemEntities() { - _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())) - .Returns(Task.CompletedTask); + // Act + await _sut.RemoveSystemEntitiesAsync(); - await _sut.CleanupEntitiesAsync(); + // Assert + _entityManagerMock.Verify(em => em.RemoveEntity(It.Is(id => SystemEntityIds.Contains(id))), Times.Exactly(14)); + } - _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Exactly(14)); + [Fact] + public async Task RemoveSystemEntitiesAsync_WhenRemovalFails_ShouldRethrow() + { + // Arrange + _entityManagerMock + .Setup(em => em.RemoveEntity(It.IsAny())) + .ThrowsAsync(new InvalidOperationException("Removal failed")); + + // Act + var act = () => _sut.RemoveSystemEntitiesAsync(); + + // Assert + await act.Should().ThrowAsync(); } #endregion - #region CleanupDeviceEntitiesAsync + #region RemoveDeviceEntitiesAsync + + [Theory] + [InlineData(0, 0)] + [InlineData(1, 4)] + [InlineData(2, 8)] + public async Task RemoveDeviceEntitiesAsync_ShouldRemoveFourEntitiesPerDevice(int deviceCount, int expectedRemovals) + { + // Arrange + var deviceNames = Enumerable.Range(0, deviceCount) + .Select(index => $"device_{index}") + .ToList(); + + // Act + await _sut.RemoveDeviceEntitiesAsync(deviceNames); + + // Assert + _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Exactly(expectedRemovals)); + } [Fact] - public async Task CleanupDeviceEntitiesAsync_ShouldRemove4EntitiesPerDevice() + public async Task RemoveDeviceEntitiesAsync_WhenOneRemovalFails_ShouldContinueWithOthers() { - _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())) - .Returns(Task.CompletedTask); + // Arrange + _entityManagerMock + .Setup(em => em.RemoveEntity(It.Is(id => id.Contains("_cost_daily")))) + .ThrowsAsync(new InvalidOperationException("Removal failed")); - await _sut.CleanupDeviceEntitiesAsync(["device_a", "device_b"]); + // Act + var act = () => _sut.RemoveDeviceEntitiesAsync(["device_a", "device_b"]); + // Assert + await act.Should().NotThrowAsync(); _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Exactly(8)); } @@ -209,55 +359,117 @@ public class PowerMonitorEntityServiceTests #region UpdateEntitiesAsync - [Fact] - public async Task UpdateEntitiesAsync_ShouldUpdateAllSystemEntities() + [Theory] + [InlineData("sensor.powermonitor_total_power")] + [InlineData("sensor.powermonitor_total_cost_15min")] + [InlineData("sensor.powermonitor_total_cost_1h")] + [InlineData("sensor.powermonitor_total_cost_daily")] + [InlineData("sensor.powermonitor_total_cost_monthly")] + [InlineData("sensor.powermonitor_other_power")] + [InlineData("sensor.powermonitor_other_cost_15min")] + [InlineData("sensor.powermonitor_other_cost_1h")] + [InlineData("sensor.powermonitor_other_cost_daily")] + [InlineData("sensor.powermonitor_other_cost_monthly")] + [InlineData("binary_sensor.powermonitor_anomaly")] + [InlineData("sensor.powermonitor_status")] + public async Task UpdateEntitiesAsync_ShouldWriteStateAndAttributesForSystemEntity(string entityId) { - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - - var context = CreateDefaultContext(); + // Arrange + var context = PowerMonitorTestData.CreateUpdateContext(); + // Act await _sut.UpdateEntitiesAsync(context); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "off"), Times.Once); + // Assert + _entityManagerMock.Verify(em => em.SetEntityState(entityId, It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes(entityId, It.IsAny()), Times.Once); + } + + [Theory] + [InlineData("sensor.tv_power", "tv")] + [InlineData("sensor.akvariumas_power", "akvariumas")] + public async Task UpdateEntitiesAsync_WithDeviceCosts_ShouldUpdateDeviceEntities(string entityId, string deviceName) + { + // Arrange + var context = PowerMonitorTestData.CreateUpdateContext( + deviceReadings: PowerMonitorTestData.CreateReadings((entityId, 42.0))); + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + foreach (var window in new[] { "15min", "1h", "daily", "monthly" }) + { + _entityManagerMock.Verify( + em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny()), + Times.Once); + } + } + + [Theory] + [InlineData(false, "off")] + [InlineData(true, "on")] + public async Task UpdateEntitiesAsync_ShouldProjectAnomalyState(bool isAnomaly, string expectedState) + { + // Arrange + var context = PowerMonitorTestData.CreateUpdateContext(isAnomaly: isAnomaly); + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + _entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState), Times.Once); + } + + [Theory] + [InlineData("ok")] + [InlineData("degraded")] + [InlineData("initializing")] + public async Task UpdateEntitiesAsync_ShouldProjectSystemStatus(string systemStatus) + { + // Arrange + var context = PowerMonitorTestData.CreateUpdateContext(systemStatus: systemStatus); + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", systemStatus), Times.Once); + } + + [Fact] + public async Task UpdateEntitiesAsync_ShouldFormatStatesWithInvariantPrecision() + { + // Arrange + var context = PowerMonitorTestData.CreateUpdateContext( + deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.tv_power", 42.0))); + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", "342.0"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", "128.5"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_cost_daily", "1.0000"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once); + } + + [Fact] + public async Task UpdateEntitiesAsync_WhenStateWriteFails_ShouldStillWriteRemainingEntities() + { + // Arrange + _entityManagerMock + .Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny())) + .ThrowsAsync(new InvalidOperationException("Failed")); + var context = PowerMonitorTestData.CreateUpdateContext(); + + // Act + var act = () => _sut.UpdateEntitiesAsync(context); + + // Assert + await act.Should().NotThrowAsync(); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "ok"), Times.Once); - } - - [Fact] - public async Task UpdateEntitiesAsync_WithDeviceCosts_ShouldUpdateDeviceEntities() - { - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - - var context = CreateDefaultContext(); - - await _sut.UpdateEntitiesAsync(context); - - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_15min", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_1h", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_daily", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_monthly", It.IsAny()), Times.Once); - } - - [Fact] - public async Task UpdateEntitiesAsync_WhenAnomaly_ShouldSetAnomalyOn() - { - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); - - var context = CreateDefaultContext(isAnomaly: true); - - await _sut.UpdateEntitiesAsync(context); - - _entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "on"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny()), Times.Once); } #endregion @@ -267,70 +479,67 @@ public class PowerMonitorEntityServiceTests [Fact] public async Task SetEntityStateSafe_WhenExceptionThrown_ShouldNotRethrow() { - _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + // Arrange + _entityManagerMock + .Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .ThrowsAsync(new InvalidOperationException("Failed")); + // Act var act = () => _sut.SetEntityStateSafe("sensor.test", "42"); + // Assert await act.Should().NotThrowAsync(); } [Fact] public async Task SetEntityAttributesSafe_WhenExceptionThrown_ShouldNotRethrow() { - _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + // Arrange + _entityManagerMock + .Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .ThrowsAsync(new InvalidOperationException("Failed")); + // Act var act = () => _sut.SetEntityAttributesSafe("sensor.test", new { }); + // Assert await act.Should().NotThrowAsync(); } #endregion - private static PowerUpdateContext CreateDefaultContext(bool isAnomaly = false) + #region Cancellation + + public static IEnumerable CancelledOperations() { - return new PowerUpdateContext - { - Calculation = new PowerCalculationResult - { - TotalPowerWatts = 341.97, - KnownDevicesSumWatts = 210.93, - RawOtherPowerWatts = 131.04, - SmoothedOtherPowerWatts = 128.5, - DataQuality = "ok", - DevicePowerReadings = new Dictionary - { - ["sensor.sonoff_100215c534_power"] = 8.55, - ["sensor.sonoff_10018909cb_power"] = 36.93, - ["sensor.tv_power"] = 101.0, - ["sensor.akvariumas_power"] = 21.0, - ["sensor.sonoff_1002230a48_power"] = 20.06, - ["sensor.temp_power"] = 14.0, - ["sensor.balkony_laps_power"] = 9.39 - } - }, - CurrentNordPoolPrice = 0.1791, - PriceUnit = "EUR/kWh", - PriceSource = "live", - DeviceCosts = new Dictionary - { - ["sensor.sonoff_100215c534_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.004, CostDaily = 0.03, CostMonthly = 0.9 }, - ["sensor.sonoff_10018909cb_power"] = new() { Cost15Min = 0.002, Cost1Hour = 0.009, CostDaily = 0.11, CostMonthly = 3.3 }, - ["sensor.tv_power"] = new() { Cost15Min = 0.006, Cost1Hour = 0.024, CostDaily = 0.30, CostMonthly = 9.0 }, - ["sensor.akvariumas_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.005, CostDaily = 0.06, CostMonthly = 1.8 }, - ["sensor.sonoff_1002230a48_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.005, CostDaily = 0.06, CostMonthly = 1.8 }, - ["sensor.temp_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.003, CostDaily = 0.04, CostMonthly = 1.2 }, - ["sensor.balkony_laps_power"] = new() { Cost15Min = 0.0005, Cost1Hour = 0.002, CostDaily = 0.03, CostMonthly = 0.9 } - }, - TotalCost = new CostSnapshot { Cost15Min = 0.02, Cost1Hour = 0.08, CostDaily = 1.00, CostMonthly = 30.0 }, - OtherCost = new CostSnapshot { Cost15Min = 0.008, Cost1Hour = 0.031, CostDaily = 0.38, CostMonthly = 11.4 }, - IsAnomaly = isAnomaly, - AnomalyDuration = TimeSpan.Zero, - AnomalyThresholdWatts = 1000, - TrackedSensorCount = 7, - DegradedSensors = [], - SystemStatus = "ok" - }; + var cancelled = new CancellationToken(canceled: true); + var sensors = new List { PowerMonitorTestData.CreateSensor("sensor.tv_power") }; + var context = PowerMonitorTestData.CreateUpdateContext(); + + yield return ["create system entities", (Func)(sut => sut.CreateSystemEntitiesAsync(cancelled))]; + yield return ["create device entities", (Func)(sut => sut.CreateDeviceEntitiesAsync(sensors, cancelled))]; + yield return ["update entities", (Func)(sut => sut.UpdateEntitiesAsync(context, cancelled))]; + yield return ["reset entities", (Func)(sut => sut.ResetEntitiesAsync(cancelled))]; + yield return ["remove system entities", (Func)(sut => sut.RemoveSystemEntitiesAsync(cancelled))]; + yield return ["remove device entities", (Func)(sut => sut.RemoveDeviceEntitiesAsync(["tv"], cancelled))]; } + + [Theory] + [MemberData(nameof(CancelledOperations))] + public async Task Operation_WithCancelledToken_ShouldThrowAndNotTouchEntities( + string scenario, + Func operation) + { + // Act + var act = () => operation(_sut); + + // Assert + await act.Should().ThrowAsync($"scenario: {scenario}"); + _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Never); + } + + #endregion } diff --git a/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs b/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs index b6658a9..0e57b34 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs @@ -6,52 +6,81 @@ namespace PowerMonitor.Manager.Tests; public class PowerMonitorOptionsTests { - [Fact] - public void Defaults_ShouldHaveEnabledTrue() + /// + /// Expected defaults for every public, configurable option. Only public properties are + /// inspected here - no private state is read through reflection. + /// + public static TheoryData 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))] + public void Defaults_ShouldExposeExpectedValue(string propertyName, object expected) + { + // Arrange + var options = new PowerMonitorOptions(); + var property = typeof(PowerMonitorOptions).GetProperty(propertyName); + + // Act + var actual = property!.GetValue(options); + + // Assert + property.Should().NotBeNull($"PowerMonitorOptions.{propertyName} should be a public property"); + actual.Should().Be(expected); + } + + public static TheoryData CollectionProperties => new() + { + nameof(PowerMonitorOptions.ExcludedSensorPatterns), + nameof(PowerMonitorOptions.EnforceSwitchOffEntityIds), + nameof(PowerMonitorOptions.PauseAndRestoreEntityIds) + }; + + [Theory] + [MemberData(nameof(CollectionProperties))] + public void Defaults_ShouldExposeEmptyCollection(string propertyName) + { + // Arrange var options = new PowerMonitorOptions(); - options.Enabled.Should().BeTrue(); + // Act + var value = typeof(PowerMonitorOptions).GetProperty(propertyName)!.GetValue(options); + + // Assert + value.Should().BeOfType(); + ((string[])value!).Should().BeEmpty(); } [Fact] - public void Defaults_ShouldHaveExpectedPollInterval() + public void Defaults_ShouldNotShareCollectionInstancesBetweenOptionObjects() { - var options = new PowerMonitorOptions(); + // Arrange - two option objects must not mutate each other's array contents. + var first = new PowerMonitorOptions(); + var second = new PowerMonitorOptions(); - options.PollIntervalSeconds.Should().Be(PowerMonitorConsts.DefaultPollIntervalSeconds); - } + // Act + first.ExcludedSensorPatterns = ["sensor.custom_*"]; + first.EnforceSwitchOffEntityIds = ["switch.custom"]; + first.PauseAndRestoreEntityIds = ["switch.custom_monitor"]; - [Fact] - public void Defaults_ShouldHaveExpectedSmoothingWindowSize() - { - var options = new PowerMonitorOptions(); - - options.SmoothingWindowSize.Should().Be(PowerMonitorConsts.DefaultSmoothingWindowSize); - } - - [Fact] - public void Defaults_ShouldHaveExpectedAnomalyThreshold() - { - var options = new PowerMonitorOptions(); - - options.AnomalyThresholdWatts.Should().Be(PowerMonitorConsts.DefaultAnomalyThresholdWatts); - } - - [Fact] - public void Defaults_ShouldHaveEmptyMainMeterEntityId() - { - var options = new PowerMonitorOptions(); - - options.MainMeterEntityId.Should().BeEmpty(); - } - - [Fact] - public void Defaults_ShouldHaveEmptyExcludedSensorPatterns() - { - var options = new PowerMonitorOptions(); - - options.ExcludedSensorPatterns.Should().BeEmpty(); + // Assert + first.ExcludedSensorPatterns.Should().NotBeSameAs(second.ExcludedSensorPatterns); + first.EnforceSwitchOffEntityIds.Should().NotBeSameAs(second.EnforceSwitchOffEntityIds); + first.PauseAndRestoreEntityIds.Should().NotBeSameAs(second.PauseAndRestoreEntityIds); + second.ExcludedSensorPatterns.Should().BeEmpty(); + second.EnforceSwitchOffEntityIds.Should().BeEmpty(); + second.PauseAndRestoreEntityIds.Should().BeEmpty(); } [Fact] @@ -59,60 +88,4 @@ public class PowerMonitorOptionsTests { PowerMonitorOptions.SectionName.Should().Be("PowerMonitor"); } - - [Fact] - public void Enabled_WhenSetToFalse_ShouldReturnFalse() - { - var options = new PowerMonitorOptions { Enabled = false }; - - options.Enabled.Should().BeFalse(); - } - - [Fact] - public void Defaults_ShouldHaveEnforceLimitEnabledTrue() - { - var options = new PowerMonitorOptions(); - - options.EnforceLimitEnabled.Should().BeTrue(); - } - - [Fact] - public void Defaults_ShouldHaveExpectedPowerLimitWatts() - { - var options = new PowerMonitorOptions(); - - options.PowerLimitWatts.Should().Be(PowerMonitorConsts.DefaultPowerLimitWatts); - } - - [Fact] - public void Defaults_ShouldHaveExpectedRecoverySeconds() - { - var options = new PowerMonitorOptions(); - - options.RecoverySeconds.Should().Be(PowerMonitorConsts.DefaultRecoverySeconds); - } - - [Fact] - public void Defaults_ShouldHaveExpectedLimitCooldownSeconds() - { - var options = new PowerMonitorOptions(); - - options.LimitCooldownSeconds.Should().Be(PowerMonitorConsts.DefaultLimitCooldownSeconds); - } - - [Fact] - public void Defaults_ShouldHaveEmptyEnforceSwitchOffEntityIds() - { - var options = new PowerMonitorOptions(); - - options.EnforceSwitchOffEntityIds.Should().BeEmpty(); - } - - [Fact] - public void Defaults_ShouldHaveEmptyPauseAndRestoreEntityIds() - { - var options = new PowerMonitorOptions(); - - options.PauseAndRestoreEntityIds.Should().BeEmpty(); - } } diff --git a/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs b/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs new file mode 100644 index 0000000..55cbeef --- /dev/null +++ b/PowerMonitor.Manager.Tests/PowerMonitorTestData.cs @@ -0,0 +1,217 @@ +using System.Text.Json; +using PowerMonitor.Models; +using PowerMonitorManager; +using PowerMonitorManager.Models; +using PowerMonitorManager.Models.Consts; + +namespace PowerMonitor.Manager.Tests; + +/// +/// Shared, deterministic datasets and builders used by the PowerMonitor tests. +/// Keeping the builders and generated series here avoids copy-pasted setup and +/// hard-coded clocks across test classes. +/// +internal static class PowerMonitorTestData +{ + public const double DefaultTotalWatts = 341.97; + public const double DefaultSmoothedOtherWatts = 131.04; + public const double DefaultPricePerKwh = 0.1791; + + public const string BoilerSwitchEntityId = "switch.sonoff_1002230e32"; + public const string AutoManagementEntityId = "switch.boilermonitor_auto_management"; + public const string MainMeterEntityId = "sensor.sonoff_100267d63f_power"; + + public static readonly DateTime FixedNow = new(2026, 3, 17, 10, 0, 0); + + public static readonly DateTime FixedDayStart = new(2026, 3, 17, 0, 0, 0); + + public static readonly DateTimeOffset FixedUtcNow = new(2026, 3, 17, 8, 0, 0, TimeSpan.Zero); + + /// + /// Two-device reading set used by the cost calculation tests. + /// + public static IReadOnlyDictionary CreateCostDeviceReadings() => new Dictionary + { + ["sensor.sonoff_100215c534_power"] = 101.0, + ["sensor.sonoff_10018909cb_power"] = 109.93 + }; + + /// + /// Realistic seven-device reading set used by the entity projection tests. + /// + public static IReadOnlyDictionary CreateDeviceReadings() => new Dictionary + { + ["sensor.sonoff_100215c534_power"] = 8.55, + ["sensor.sonoff_10018909cb_power"] = 36.93, + ["sensor.tv_power"] = 101.0, + ["sensor.akvariumas_power"] = 21.0, + ["sensor.sonoff_1002230a48_power"] = 20.06, + ["sensor.temp_power"] = 14.0, + ["sensor.balkony_laps_power"] = 9.39 + }; + + public static IReadOnlyDictionary CreateReadings(params (string EntityId, double Watts)[] readings) => + readings.ToDictionary(r => r.EntityId, r => r.Watts); + + public static PowerCalculationResult CreateCalculation( + double totalWatts = DefaultTotalWatts, + double smoothedOtherWatts = DefaultSmoothedOtherWatts, + IReadOnlyDictionary? deviceReadings = null, + string dataQuality = "ok") + { + var readings = deviceReadings ?? CreateCostDeviceReadings(); + + return new PowerCalculationResult + { + TotalPowerWatts = totalWatts, + KnownDevicesSumWatts = readings.Values.Sum(), + RawOtherPowerWatts = smoothedOtherWatts, + SmoothedOtherPowerWatts = smoothedOtherWatts, + DataQuality = dataQuality, + DevicePowerReadings = readings + }; + } + + public static CostSnapshot CreateCostSnapshot( + double cost15Min = 0.001, + double cost1Hour = 0.004, + double costDaily = 0.03, + double costMonthly = 0.9, + bool partialWindow = true) => new() + { + Cost15Min = cost15Min, + Cost1Hour = cost1Hour, + CostDaily = costDaily, + CostMonthly = costMonthly, + PartialWindow = partialWindow + }; + + public static PowerUpdateContext CreateUpdateContext( + bool isAnomaly = false, + double totalWatts = DefaultTotalWatts, + double smoothedOtherWatts = 128.5, + string systemStatus = "ok", + IReadOnlyDictionary? deviceReadings = null, + double currentNordPoolPrice = DefaultPricePerKwh, + string priceSource = "live") + { + var readings = deviceReadings ?? CreateDeviceReadings(); + var deviceCosts = readings + .Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot( + cost15Min: 0.0005 * (index + 1), + cost1Hour: 0.002 * (index + 1), + costDaily: 0.03 * (index + 1), + costMonthly: 0.9 * (index + 1)))) + .ToDictionary(entry => entry.Key, entry => entry.Snapshot); + + return new PowerUpdateContext + { + Calculation = CreateCalculation(totalWatts, smoothedOtherWatts, readings), + CurrentNordPoolPrice = currentNordPoolPrice, + PriceUnit = "EUR/kWh", + PriceSource = priceSource, + DeviceCosts = deviceCosts, + TotalCost = CreateCostSnapshot(0.02, 0.08, 1.00, 30.0), + OtherCost = CreateCostSnapshot(0.008, 0.031, 0.38, 11.4), + IsAnomaly = isAnomaly, + AnomalyDuration = TimeSpan.Zero, + AnomalyThresholdWatts = PowerMonitorConsts.DefaultAnomalyThresholdWatts, + TrackedSensorCount = readings.Count, + DegradedSensors = [], + SystemStatus = systemStatus + }; + } + + public static PowerMonitorOptions CreateOptions(Action? configure = null) + { + var options = new PowerMonitorOptions + { + Enabled = true, + MainMeterEntityId = MainMeterEntityId, + ExcludedSensorPatterns = ["sensor.nordpool_*", "sensor.powermonitor_*"] + }; + + configure?.Invoke(options); + return options; + } + + public static PowerMonitorOptions CreateLimitEnforcementOptions(Action? configure = null) => + CreateOptions(options => + { + options.EnforceLimitEnabled = true; + options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts; + options.RecoverySeconds = PowerMonitorConsts.DefaultRecoverySeconds; + options.LimitCooldownSeconds = PowerMonitorConsts.DefaultLimitCooldownSeconds; + options.EnforceSwitchOffEntityIds = [BoilerSwitchEntityId]; + options.PauseAndRestoreEntityIds = [AutoManagementEntityId]; + configure?.Invoke(options); + }); + + public static PowerSensorInfo CreateSensor( + string entityId, + string? friendlyName = null, + string? deviceName = null, + string unitOfMeasurement = PowerMonitorConsts.WattUnit) => new() + { + EntityId = entityId, + FriendlyName = friendlyName ?? entityId, + DeviceName = deviceName ?? PowerSensorDiscoveryService.ExtractDeviceName(entityId), + UnitOfMeasurement = unitOfMeasurement + }; + + public static JsonElement CreateAttributesJson( + string? deviceClass, + string? unitOfMeasurement, + string? friendlyName) + { + var attributes = new Dictionary(); + + if (deviceClass is not null) + { + attributes["device_class"] = deviceClass; + } + + if (unitOfMeasurement is not null) + { + attributes["unit_of_measurement"] = unitOfMeasurement; + } + + if (friendlyName is not null) + { + attributes["friendly_name"] = friendlyName; + } + + return JsonSerializer.SerializeToElement(attributes); + } + + /// + /// Deterministic, strictly positive and monotonically increasing power samples + /// used by the looping scenarios. + /// + public static IReadOnlyList CreatePowerSampleSeries(int count = 96) => + Enumerable.Range(0, count) + .Select(i => Math.Round(50.0 + (i * 37.5) + ((i % 7) * 0.5), 2)) + .ToArray(); + + /// + /// Deterministic, strictly positive hourly tariff series (EUR/kWh). + /// + public static IReadOnlyList CreateTariffPriceSeries(int count = 24) => + Enumerable.Range(0, count) + .Select(i => Math.Round(0.08 + (i * 0.03) + ((i % 5) * 0.0125), 4)) + .ToArray(); + + 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(); + } + + public static IReadOnlyList CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15) => + Enumerable.Range(0, count) + .Select(i => start.AddMinutes(i * intervalMinutes)) + .ToArray(); +} diff --git a/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs b/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs index 64b622a..f2e46b1 100644 --- a/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs @@ -1,4 +1,3 @@ -using System.Text.Json; using FluentAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -22,168 +21,258 @@ public class PowerSensorDiscoveryServiceTests } private PowerSensorDiscoveryService CreateSut( - string mainMeterEntityId = "sensor.sonoff_100267d63f_power", + string mainMeterEntityId = PowerMonitorTestData.MainMeterEntityId, string[]? excludedPatterns = null) { - var options = Options.Create(new PowerMonitorOptions + var options = Options.Create(PowerMonitorTestData.CreateOptions(option => { - MainMeterEntityId = mainMeterEntityId, - ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"] - }); + option.MainMeterEntityId = mainMeterEntityId; + option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"]; + })); return new PowerSensorDiscoveryService(_haContextMock.Object, options, _loggerMock.Object); } - private void SetupEntities(params (string entityId, string? deviceClass, string? unit, string? friendlyName)[] entities) + private Entity SetupEntity(string entityId, string? deviceClass, string? unit, string? friendlyName) { - var entityList = new List(); - - foreach (var (entityId, deviceClass, unit, friendlyName) in entities) + var entityState = new EntityState { - var attributes = new Dictionary(); - if (deviceClass is not null) - { - attributes["device_class"] = deviceClass; - } + AttributesJson = PowerMonitorTestData.CreateAttributesJson(deviceClass, unit, friendlyName) + }; - if (unit is not null) - { - attributes["unit_of_measurement"] = unit; - } - - if (friendlyName is not null) - { - attributes["friendly_name"] = friendlyName; - } - - var attributesJson = JsonSerializer.SerializeToElement(attributes); - var entityState = new EntityState { AttributesJson = attributesJson }; - - _haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState); - - var entity = new Entity(_haContextMock.Object, entityId); - entityList.Add(entity); - } - - _haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList); + _haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState); + return new Entity(_haContextMock.Object, entityId); } + private void SetupEntities( + 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()); + + private void SetupEntitiesWithoutState(params string[] entityIds) => + _haContextMock + .Setup(h => h.GetAllEntities()) + .Returns(entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId)).ToList()); + #region Discovery [Fact] public void DiscoverDeviceSensors_ShouldFindPowerSensors() { + // Arrange SetupEntities( - ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), ("sensor.sonoff_100215c534_power", "power", "W", "AC Power"), ("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"), - ("sensor.temperature", "temperature", "°C", "Temperature") - ); + ("sensor.temperature", "temperature", "°C", "Temperature")); var sut = CreateSut(); + + // Act var result = sut.DiscoverDeviceSensors(); + // Assert result.Should().HaveCount(2); - result.Should().Contain(s => s.EntityId == "sensor.sonoff_100215c534_power"); - result.Should().Contain(s => s.EntityId == "sensor.sonoff_10018909cb_power"); + result.Should().Contain(sensor => sensor.EntityId == "sensor.sonoff_100215c534_power"); + result.Should().Contain(sensor => sensor.EntityId == "sensor.sonoff_10018909cb_power"); } [Fact] public void DiscoverDeviceSensors_ShouldExcludeMainMeter() { + // Arrange SetupEntities( - ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), - ("sensor.tv_power", "power", "W", "TV Power") - ); + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.tv_power", "power", "W", "TV Power")); var sut = CreateSut(); + + // Act var result = sut.DiscoverDeviceSensors(); + // Assert result.Should().HaveCount(1); - result.Should().NotContain(s => s.EntityId == "sensor.sonoff_100267d63f_power"); + result.Should().NotContain(sensor => sensor.EntityId == PowerMonitorTestData.MainMeterEntityId); + } + + [Fact] + public void DiscoverDeviceSensors_WhenMainMeterNotConfigured_ShouldIncludeAllPowerSensors() + { + // Arrange + SetupEntities( + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.tv_power", "power", "W", "TV Power")); + + var sut = CreateSut(mainMeterEntityId: string.Empty); + + // Act + var result = sut.DiscoverDeviceSensors(); + + // Assert + result.Should().HaveCount(2); + result.Should().Contain(sensor => sensor.EntityId == PowerMonitorTestData.MainMeterEntityId); } [Fact] public void DiscoverDeviceSensors_ShouldApplyExclusionPatterns() { + // Arrange SetupEntities( - ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), ("sensor.tv_power", "power", "W", "TV Power"), ("sensor.nordpool_some_power", "power", "W", "NordPool"), - ("sensor.powermonitor_other_power", "power", "W", "PowerMonitor") - ); + ("sensor.powermonitor_other_power", "power", "W", "PowerMonitor")); var sut = CreateSut(); + + // Act var result = sut.DiscoverDeviceSensors(); + // Assert result.Should().HaveCount(1); - result.Should().Contain(s => s.EntityId == "sensor.tv_power"); + result.Should().Contain(sensor => sensor.EntityId == "sensor.tv_power"); } [Fact] - public void DiscoverDeviceSensors_ShouldHandleKilowattUnit() + public void DiscoverDeviceSensors_WhenNoExclusionPatternsConfigured_ShouldKeepMatchingSensors() { + // Arrange SetupEntities( - ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), - ("sensor.sonoff_1002230e32_power", "power", "kW", "Boiler Power") - ); + ("sensor.tv_power", "power", "W", "TV Power"), + ("sensor.powermonitor_other_power", "power", "W", "PowerMonitor")); - var sut = CreateSut(); + var sut = CreateSut(excludedPatterns: []); + + // Act var result = sut.DiscoverDeviceSensors(); - result.Should().HaveCount(1); - result.First().EntityId.Should().Be("sensor.sonoff_1002230e32_power"); - result.First().UnitOfMeasurement.Should().Be("kW"); + // Assert + result.Should().HaveCount(2); + } + + [Theory] + [InlineData("sensor.tv_power", "TV Power", "W", "TV Power", "W", "tv")] + [InlineData("sensor.boiler_power", "Boiler Power", "kW", "Boiler Power", "kW", "boiler")] + [InlineData("sensor.mystery_power", null, "W", "sensor.mystery_power", "W", "mystery")] + public void DiscoverDeviceSensors_ShouldExposeSensorMetadata( + string entityId, + string? friendlyName, + string unit, + string expectedFriendlyName, + string expectedUnit, + string expectedDeviceName) + { + // Arrange + SetupEntities((entityId, "power", unit, friendlyName)); + + var sut = CreateSut(); + + // Act + var result = sut.DiscoverDeviceSensors(); + + // Assert + result.Should().ContainSingle(); + var sensor = result.Single(); + sensor.EntityId.Should().Be(entityId); + sensor.FriendlyName.Should().Be(expectedFriendlyName); + sensor.UnitOfMeasurement.Should().Be(expectedUnit); + sensor.DeviceName.Should().Be(expectedDeviceName); } [Fact] public void DiscoverDeviceSensors_WhenNoPowerSensors_ShouldReturnEmpty() { + // Arrange SetupEntities( ("sensor.temperature", "temperature", "°C", "Temp"), - ("switch.some_switch", null, null, "Switch") - ); + ("switch.some_switch", null, null, "Switch"), + ("sensor.energy_usage", "energy", "kWh", "Energy")); var sut = CreateSut(); + + // Act var result = sut.DiscoverDeviceSensors(); + // Assert result.Should().BeEmpty(); } + [Fact] + public void DiscoverDeviceSensors_WhenEntityStateMissing_ShouldSkipEntity() + { + // Arrange - HA can report entities whose state has not been published yet. + var tv = SetupEntity("sensor.tv_power", "power", "W", "TV Power"); + _haContextMock + .Setup(h => h.GetAllEntities()) + .Returns(new List { new(_haContextMock.Object, "sensor.ghost_power"), tv }); + + var sut = CreateSut(); + + // Act + var result = sut.DiscoverDeviceSensors(); + + // Assert + result.Should().ContainSingle(); + result.Single().EntityId.Should().Be("sensor.tv_power"); + } + + [Fact] + public void DiscoverDeviceSensors_WhenHaReportsDuplicateEntities_ShouldMirrorTheEntityList() + { + // Arrange - discovery is a projection of HA's entity list; de-duplication is not its job. + SetupEntities( + ("sensor.tv_power", "power", "W", "TV Power"), + ("sensor.tv_power", "power", "W", "TV Power")); + + var sut = CreateSut(); + + // Act + var result = sut.DiscoverDeviceSensors(); + + // Assert + result.Should().HaveCount(2); + result.Select(sensor => sensor.DeviceName).Should().OnlyContain(name => name == "tv"); + } + [Fact] public void DiscoverDeviceSensors_ShouldUpdateCurrentDeviceSensors() { + // Arrange SetupEntities( - ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), - ("sensor.akvariumas_power", "power", "W", "Akvariumas Power") - ); + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.akvariumas_power", "power", "W", "Akvariumas Power")); var sut = CreateSut(); sut.CurrentDeviceSensors.Should().BeEmpty(); + // Act sut.DiscoverDeviceSensors(); + // Assert sut.CurrentDeviceSensors.Should().HaveCount(1); } [Fact] public void DiscoverDeviceSensors_ReDiscovery_ShouldReplacePreviousList() { + // Arrange SetupEntities( - ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), - ("sensor.sonoff_100215c534_power", "power", "W", "AC Power") - ); + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), + ("sensor.sonoff_100215c534_power", "power", "W", "AC Power")); var sut = CreateSut(); sut.DiscoverDeviceSensors(); sut.CurrentDeviceSensors.Should().HaveCount(1); SetupEntities( - ("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"), + (PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"), ("sensor.sonoff_100215c534_power", "power", "W", "AC Power"), - ("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power") - ); + ("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power")); + // Act sut.DiscoverDeviceSensors(); + + // Assert sut.CurrentDeviceSensors.Should().HaveCount(2); } @@ -197,6 +286,11 @@ public class PowerSensorDiscoveryServiceTests [InlineData("sensor.tv_power", "tv")] [InlineData("sensor.temp_power", "temp")] [InlineData("sensor.power", "power")] + [InlineData("sensor.TV_POWER", "TV")] + [InlineData("sensor.boiler_output_power", "boiler_output")] + [InlineData("sensor.temperature", "temperature")] + [InlineData("tv_power", "tv")] + [InlineData("sensor.", "")] public void ExtractDeviceName_ShouldStripDomainAndPowerSuffix(string entityId, string expected) { PowerSensorDiscoveryService.ExtractDeviceName(entityId).Should().Be(expected); @@ -209,8 +303,14 @@ public class PowerSensorDiscoveryServiceTests [Theory] [InlineData("sensor.nordpool_*", "sensor.nordpool_current_price", true)] [InlineData("sensor.nordpool_*", "sensor.tv_power", false)] + [InlineData("sensor.nordpool_*", "SENSOR.NORDPOOL_CURRENT_PRICE", true)] [InlineData("sensor.powermonitor_*", "sensor.powermonitor_other_power", true)] [InlineData("*_power", "sensor.sonoff_100215c534_power", true)] + [InlineData("*_power", "sensor.sonoff_100215c534_energy", false)] + [InlineData("sensor.tv_power", "sensor.tv_power", true)] + [InlineData("sensor.tv_power", "sensor.tv_power_2", false)] + [InlineData("sensor.?.power", "sensor.a.power", false)] + [InlineData("*", "anything at all", true)] public void GlobToRegex_ShouldMatchCorrectly(string glob, string input, bool expected) { var regex = PowerSensorDiscoveryService.GlobToRegex(glob); @@ -221,34 +321,50 @@ public class PowerSensorDiscoveryServiceTests #region IsPowerSensor - [Fact] - public void IsPowerSensor_WithPowerDeviceClassAndWattUnit_ShouldReturnTrue() + [Theory] + [InlineData("power device class with watts", "sensor.ac_power", "power", "W", true)] + [InlineData("power device class with kilowatts", "sensor.boiler_power", "power", "kW", true)] + [InlineData("lowercase unit", "sensor.tv_power", "power", "w", true)] + [InlineData("uppercase device class", "sensor.pc_power", "POWER", "W", true)] + [InlineData("power device class with megawatts", "sensor.plant_power", "power", "MW", false)] + [InlineData("power device class without unit", "sensor.mystery_power", "power", null, false)] + [InlineData("power device class with whitespace unit", "sensor.odd_power", "power", " ", false)] + [InlineData("energy device class", "sensor.energy_usage", "energy", "kWh", false)] + [InlineData("temperature device class", "sensor.hall_temp", "temperature", "°C", false)] + [InlineData("missing device class", "sensor.mystery", null, "W", false)] + [InlineData("non sensor domain", "switch.sonoff_100215c534_power", "power", "W", false)] + [InlineData("binary sensor domain", "binary_sensor.washer_power", "power", "W", false)] + public void IsPowerSensor_ShouldMatchOnlySensorEntitiesWithPowerDeviceClassAndPowerUnit( + string scenario, + string entityId, + string? deviceClass, + string? unit, + bool expected) { - SetupEntities(("sensor.sonoff_100215c534_power", "power", "W", "AC Power")); - var entity = new Entity(_haContextMock.Object, "sensor.sonoff_100215c534_power"); - + // Arrange + var entity = SetupEntity(entityId, deviceClass, unit, "Test"); var sut = CreateSut(); - sut.IsPowerSensor(entity).Should().BeTrue(); + + // Act + var result = sut.IsPowerSensor(entity); + + // Assert + result.Should().Be(expected, $"scenario: {scenario}"); } [Fact] - public void IsPowerSensor_WithNonSensorDomain_ShouldReturnFalse() + public void IsPowerSensor_WhenEntityStateMissing_ShouldReturnFalse() { - SetupEntities(("switch.sonoff_100215c534_power", "power", "W", "AC Power")); - var entity = new Entity(_haContextMock.Object, "switch.sonoff_100215c534_power"); - + // Arrange + SetupEntitiesWithoutState("sensor.ghost_power"); + var entity = new Entity(_haContextMock.Object, "sensor.ghost_power"); var sut = CreateSut(); - sut.IsPowerSensor(entity).Should().BeFalse(); - } - [Fact] - public void IsPowerSensor_WithTemperatureDeviceClass_ShouldReturnFalse() - { - SetupEntities(("sensor.sonoff_100215c534_temp", "temperature", "°C", "AC Temp")); - var entity = new Entity(_haContextMock.Object, "sensor.sonoff_100215c534_temp"); + // Act + var result = sut.IsPowerSensor(entity); - var sut = CreateSut(); - sut.IsPowerSensor(entity).Should().BeFalse(); + // Assert + result.Should().BeFalse(); } #endregion diff --git a/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs b/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs index 39765d0..c2c2beb 100644 --- a/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs +++ b/PowerMonitor.Manager/Interface/IPowerMonitorEntityService.cs @@ -9,6 +9,6 @@ public interface IPowerMonitorEntityService Task CreateDeviceEntitiesAsync(IReadOnlyList sensors, CancellationToken cancellationToken = default); Task UpdateEntitiesAsync(PowerUpdateContext context, CancellationToken cancellationToken = default); Task ResetEntitiesAsync(CancellationToken cancellationToken = default); - Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); - Task CleanupDeviceEntitiesAsync(IReadOnlyList removedDeviceNames, CancellationToken cancellationToken = default); + Task RemoveSystemEntitiesAsync(CancellationToken cancellationToken = default); + Task RemoveDeviceEntitiesAsync(IReadOnlyList removedDeviceNames, CancellationToken cancellationToken = default); } diff --git a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs index 3a554be..b2e4d51 100644 --- a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs +++ b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs @@ -6,7 +6,7 @@ public sealed class PowerMonitorOptions { public const string SectionName = "PowerMonitor"; - public bool Enabled { get; set; } = true; + public bool Enabled { get; set; } public string MainMeterEntityId { get; set; } = string.Empty; public int PollIntervalSeconds { get; set; } = PowerMonitorConsts.DefaultPollIntervalSeconds; public int SmoothingWindowSize { get; set; } = PowerMonitorConsts.DefaultSmoothingWindowSize; diff --git a/PowerMonitor.Manager/PowerMonitor.Manager.csproj b/PowerMonitor.Manager/PowerMonitor.Manager.csproj index 6d79ea3..9d8e692 100644 --- a/PowerMonitor.Manager/PowerMonitor.Manager.csproj +++ b/PowerMonitor.Manager/PowerMonitor.Manager.csproj @@ -20,8 +20,8 @@ - - + + diff --git a/PowerMonitor.Manager/PowerMonitorEntityService.cs b/PowerMonitor.Manager/PowerMonitorEntityService.cs index 3d90f09..df00b0b 100644 --- a/PowerMonitor.Manager/PowerMonitorEntityService.cs +++ b/PowerMonitor.Manager/PowerMonitorEntityService.cs @@ -64,7 +64,7 @@ public sealed class PowerMonitorEntityService( { cancellationToken.ThrowIfCancellationRequested(); - var entities = sensors.SelectMany(GetDeviceEntities).ToList(); + var entities = sensors.SelectMany(GetPowerDeviceEntitiesNames).ToList(); var tasks = entities.Select(async entity => { try @@ -139,14 +139,16 @@ public sealed class PowerMonitorEntityService( logger.LogInformation("All PowerMonitor entity states reset to defaults"); } - public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) + public async Task RemoveSystemEntitiesAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); try { - var tasks = SystemEntityIds.Select(id => entityManager.RemoveEntity(id)); + var tasks = SystemEntityIds.Select(entityManager.RemoveEntity); + await Task.WhenAll(tasks).ConfigureAwait(false); + logger.LogInformation("PowerMonitor system entities cleaned up"); } catch (Exception ex) @@ -156,16 +158,19 @@ public sealed class PowerMonitorEntityService( } } - public async Task CleanupDeviceEntitiesAsync(IReadOnlyList removedDeviceNames, CancellationToken cancellationToken = default) + public async Task RemoveDeviceEntitiesAsync(IReadOnlyList removedDeviceNames, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var entityIds = removedDeviceNames.SelectMany(GetDeviceCostEntityIds).ToList(); + var tasks = entityIds.Select(async id => { try { await entityManager.RemoveEntity(id).ConfigureAwait(false); + + logger.LogDebug("Entity removed: {EntityId}", id); } catch (Exception ex) { @@ -175,6 +180,7 @@ public sealed class PowerMonitorEntityService( await Task.WhenAll(tasks).ConfigureAwait(false); } + internal ICollection GetSystemEntitiesList() { @@ -222,27 +228,27 @@ public sealed class PowerMonitorEntityService( }; } - internal static IEnumerable GetDeviceEntities(PowerSensorInfo sensor) + internal static IEnumerable GetPowerDeviceEntitiesNames(PowerSensorInfo sensor) { var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(sensor.EntityId); - return new[] - { + return + [ CreateCostEntity($"powermonitor_{deviceName}_cost_15min", $"{sensor.FriendlyName} cost (15 min)"), CreateCostEntity($"powermonitor_{deviceName}_cost_1h", $"{sensor.FriendlyName} cost (1h)"), CreateCostEntity($"powermonitor_{deviceName}_cost_daily", $"{sensor.FriendlyName} cost (daily)"), CreateCostEntity($"powermonitor_{deviceName}_cost_monthly", $"{sensor.FriendlyName} cost (monthly)") - }; + ]; } internal static IEnumerable GetDeviceCostEntityIds(string deviceName) { - return new[] - { + return + [ $"sensor.powermonitor_{deviceName}_cost_15min", $"sensor.powermonitor_{deviceName}_cost_1h", $"sensor.powermonitor_{deviceName}_cost_daily", $"sensor.powermonitor_{deviceName}_cost_monthly" - }; + ]; } private async Task UpdateTotalPowerAsync(PowerUpdateContext context, string timestamp) diff --git a/PowerMonitor.Manager/PowerMonitorInit.cs b/PowerMonitor.Manager/PowerMonitorInit.cs index d3692ce..b7b073f 100644 --- a/PowerMonitor.Manager/PowerMonitorInit.cs +++ b/PowerMonitor.Manager/PowerMonitorInit.cs @@ -5,6 +5,7 @@ using NetDaemon.AppModel; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using NordPool.Models; +using PowerMonitor.Models; using PowerMonitorManager.Interface; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; @@ -60,10 +61,22 @@ public sealed class PowerMonitorInit : IPowerMonitorInit { try { - await InitializeAsync(); - SubscribeToMainMeterChanges(); - SubscribeToRediscoverButton(); - SubscribeToLimitBreachDebugButton(); + if (_options.Enabled) + { + await InitializeAsync(); + SubscribeToMainMeterChanges(); + SubscribeToRediscoverButton(); + SubscribeToLimitBreachDebugButton(); + } + else + { + await CleanupEntitiesAsync(); + + var sensoresToRemove = GetPowerSensorEntitiesNames(); + + await _entityService.RemoveDeviceEntitiesAsync([.. sensoresToRemove.Select(s => s.DeviceName)]); + await _entityService.RemoveSystemEntitiesAsync(); + } } catch (Exception ex) { @@ -82,7 +95,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit await Task.Delay(TimeSpan.FromSeconds(5)); - var sensors = _discoveryService.DiscoverDeviceSensors(); + var sensors = GetPowerSensorEntitiesNames(); await _entityService.CreateDeviceEntitiesAsync(sensors); _logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count); @@ -96,9 +109,16 @@ public sealed class PowerMonitorInit : IPowerMonitorInit } } + private IReadOnlyList GetPowerSensorEntitiesNames() + { + var sensors = _discoveryService.DiscoverDeviceSensors(); + + return sensors; + } + public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) { - await _entityService.CleanupEntitiesAsync(cancellationToken); + await _entityService.RemoveSystemEntitiesAsync(cancellationToken); } private void SubscribeToMainMeterChanges() @@ -175,9 +195,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit if (removed.Count > 0) { - var removedNames = removed.Select(s => s.DeviceName).ToList(); - await _entityService.CleanupDeviceEntitiesAsync(removedNames); - _logger.LogInformation("Removed entities for {Count} sensors", removed.Count); + await RemoreDevicePriceEntities(removed); } _logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)", newSensors.Count, added.Count, removed.Count); @@ -188,6 +206,14 @@ public sealed class PowerMonitorInit : IPowerMonitorInit } } + private async Task RemoreDevicePriceEntities(List removed) + { + var removedNames = removed.Select(s => s.DeviceName).ToList(); + await _entityService.RemoveDeviceEntitiesAsync(removedNames); + + _logger.LogInformation("Removed entities for {Count} sensors", removed.Count); + } + private async Task PollAndUpdateAsync() { try diff --git a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs index 2d82bc7..777aeb5 100644 --- a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs +++ b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs @@ -14,11 +14,6 @@ public static class PowerMonitorServiceRegistration .GetSection(PowerMonitorOptions.SectionName) .Get() ?? new PowerMonitorOptions(); - if (!options.Enabled) - { - return services; - } - services .AddNetDaemonApp() .AddScoped() diff --git a/PowerMonitor.Models/PowerMonitor.Models.csproj b/PowerMonitor.Models/PowerMonitor.Models.csproj index babb160..fdc44f8 100644 --- a/PowerMonitor.Models/PowerMonitor.Models.csproj +++ b/PowerMonitor.Models/PowerMonitor.Models.csproj @@ -12,7 +12,7 @@ - + diff --git a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs index b026f49..d3fe05b 100644 --- a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs +++ b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs @@ -1,4 +1,6 @@ +using FluentAssertions; using Microsoft.Extensions.Options; +using Microsoft.Extensions.Time.Testing; using Moq; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; @@ -12,104 +14,267 @@ public class ExhaustFanControlServiceTests { private const string FanEntityId = "switch.exhaust_fan"; - private readonly ShowerMonitorOptions _defaultOptions = new() - { - ExhaustFanEntityId = FanEntityId, - FanRunAfterShowerMinutes = 10 - }; - + private readonly ShowerMonitorOptions _defaultOptions = ShowerMonitorTestData.CreateOptions(); + private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider(); private readonly Mock _haContextMock = new(); + private DateTimeOffset Now => _timeProvider.GetUtcNow(); + + public static IEnumerable 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 IEnumerable 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 IEnumerable 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] + ]; + + [Theory] + [MemberData(nameof(ShowerProgressFanStateCases))] + public void Evaluate_WhileShowerInProgress_TurnsFanOnOnlyWhenNotAlreadyRunning( + string scenario, + ShowerState state, + string? fanState, + bool expectTurnOn) + { + SetupFanState(fanState); + var service = CreateService(); + + service.Evaluate(state, Now); + + VerifySwitchCall("turn_on", expectTurnOn ? 1 : 0, because: $"scenario: {scenario}"); + VerifySwitchCall("turn_off", 0, because: $"scenario: {scenario}"); + } + + [Theory] + [MemberData(nameof(FanRunAfterCases))] + public void Evaluate_AfterShowerEnds_TurnsFanOffOnlyOnceRunPeriodElapsed( + string scenario, + int runAfterMinutes, + int idleOffsetSecondsFromShowerEnd, + bool expectTurnOff) + { + SetupFanState("off"); + var service = CreateService(ShowerMonitorTestData.CreateOptions( + fanRunAfterShowerMinutes: runAfterMinutes)); + var showerEnd = Now.AddMinutes(5); + + service.Evaluate(ShowerState.Active, Now); + service.Evaluate(ShowerState.Completed, showerEnd); + service.Evaluate(ShowerState.Idle, showerEnd.AddSeconds(idleOffsetSecondsFromShowerEnd)); + + VerifySwitchCall("turn_on", 1, because: $"scenario: {scenario}"); + VerifySwitchCall("turn_off", expectTurnOff ? 1 : 0, because: $"scenario: {scenario}"); + } + + [Theory] + [InlineData(ShowerState.Completed)] + [InlineData(ShowerState.Declining)] + public void Evaluate_EndingStates_StartRunAfterPeriod(ShowerState endingState) + { + SetupFanState("off"); + var service = CreateService(); + + service.Evaluate(ShowerState.Active, Now); + service.Evaluate(endingState, Now.AddMinutes(5)); + + VerifySwitchCall("turn_off", 0); + + service.Evaluate(ShowerState.Idle, Now.AddMinutes(15)); + + VerifySwitchCall("turn_off", 1); + VerifySwitchCall("turn_on", 1); + } + + [Theory] + [InlineData(ShowerState.Idle)] + [InlineData(ShowerState.Declining)] + [InlineData(ShowerState.Completed)] + public void Evaluate_AfterShowerEnds_WhenFanWasNotTurnedOnByUs_DoesNotTurnFanOff(ShowerState state) + { + SetupFanState("off"); + var service = CreateService(); + + service.Evaluate(state, Now); + service.Evaluate(ShowerState.Idle, Now.AddHours(1)); + + VerifySwitchCall("turn_on", 0); + VerifySwitchCall("turn_off", 0); + } + + [Fact] + public void Evaluate_WhenShowerStaysActive_TurnsFanOnOnlyOnce() + { + SetupFanState("off"); + var service = CreateService(); + + service.Evaluate(ShowerState.Active, Now); + service.Evaluate(ShowerState.Active, Now.AddSeconds(30)); + service.Evaluate(ShowerState.Suspected, Now.AddMinutes(1)); + + VerifySwitchCall("turn_on", 1); + VerifySwitchCall("turn_off", 0); + } + + [Fact] + public void Evaluate_WhenShowerResumesDuringRunPeriod_CancelsPendingFanOff() + { + SetupFanState("off"); + var service = CreateService(); + + service.Evaluate(ShowerState.Active, Now); + service.Evaluate(ShowerState.Completed, Now.AddMinutes(5)); + service.Evaluate(ShowerState.Active, Now.AddMinutes(8)); + service.Evaluate(ShowerState.Idle, Now.AddMinutes(30)); + + VerifySwitchCall("turn_on", 1); + VerifySwitchCall("turn_off", 0); + } + + [Fact] + public void Evaluate_WhenAnewShowerStartsAfterFanStopped_TurnsFanOnAgain() + { + SetupFanState("off"); + var service = CreateService(); + + service.Evaluate(ShowerState.Active, Now); + service.Evaluate(ShowerState.Completed, Now.AddMinutes(15)); + service.Evaluate(ShowerState.Idle, Now.AddMinutes(26)); + service.Evaluate(ShowerState.Active, Now.AddMinutes(40)); + + VerifySwitchCall("turn_on", 2); + VerifySwitchCall("turn_off", 1); + } + + [Fact] + public void Evaluate_AfterShowerEnds_WhenFanWasAlreadyOn_DoesNotTurnItOff() + { + SetupFanState("on"); + var service = CreateService(); + + service.Evaluate(ShowerState.Active, Now); + service.Evaluate(ShowerState.Completed, Now.AddMinutes(5)); + service.Evaluate(ShowerState.Idle, Now.AddMinutes(20)); + + VerifySwitchCall("turn_on", 0); + VerifySwitchCall("turn_off", 0); + } + + [Theory] + [MemberData(nameof(ResetCases))] + public void Reset_TurnsFanOffOnlyWhenWeTurnedItOnAndItIsStillOn( + string scenario, + bool turnOnFirst, + string? currentFanState, + bool expectTurnOff) + { + SetupFanState("off"); + var service = CreateService(); + + if (turnOnFirst) + { + service.Evaluate(ShowerState.Active, Now); + SetupFanState(currentFanState); + } + + service.Reset(); + + VerifySwitchCall("turn_off", expectTurnOff ? 1 : 0, because: $"scenario: {scenario}"); + } + + [Fact] + public void Reset_IsIdempotent_AndPreventsLaterFanOff() + { + SetupFanState("off"); + var service = CreateService(); + + service.Evaluate(ShowerState.Active, Now); + SetupFanState("on"); + + service.Reset(); + service.Reset(); + + VerifySwitchCall("turn_off", 1); + + SetupFanState("off"); + service.Evaluate(ShowerState.Idle, Now.AddMinutes(20)); + + VerifySwitchCall("turn_off", 1); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("switch.unknown_fan")] + [InlineData(null)] + public void Evaluate_WithConfiguredFanEntityId_TargetsThatExactEntity(string? entityId) + { + var service = CreateService(ShowerMonitorTestData.CreateOptions(exhaustFanEntityId: entityId!)); + + service.Evaluate(ShowerState.Active, Now); + + VerifySwitchCall("turn_on", 1, entityId); + } + private ExhaustFanControlService CreateService(ShowerMonitorOptions? options = null) { return new ExhaustFanControlService(_haContextMock.Object, Options.Create(options ?? _defaultOptions)); } - [Fact] - public void Evaluate_WhenActive_TurnsFanOn() + private void SetupFanState(string? state) { - var entityState = new EntityState { State = "off" }; - _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); - - var service = CreateService(); - service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow); - - _haContextMock.Verify(x => x.CallService("switch", "turn_on", - It.IsAny(), It.IsAny()), Times.Once); + _haContextMock + .Setup(x => x.GetState(_defaultOptions.ExhaustFanEntityId)) + .Returns(ShowerMonitorTestData.FanState(state)); } - [Fact] - public void Evaluate_WhenActiveAndFanAlreadyOn_DoesNotCallAgain() + private void VerifySwitchCall( + string service, + int expectedCount, + string? expectedEntityId = FanEntityId, + string? because = null) { - var entityState = new EntityState { State = "on" }; - _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); + var targets = _haContextMock.Invocations + .Where(invocation => invocation.Method.Name == nameof(IHaContext.CallService) + && (string?)invocation.Arguments[0] == "switch" + && (string?)invocation.Arguments[1] == service) + .Select(invocation => (ServiceTarget?)invocation.Arguments[2]) + .ToList(); - var service = CreateService(); - service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow); - - _haContextMock.Verify(x => x.CallService("switch", "turn_on", - It.IsAny(), It.IsAny()), Times.Never); - } - - [Fact] - public void Evaluate_AfterShowerEndsAndRunPeriodElapsed_TurnsFanOff() - { - var entityState = new EntityState { State = "off" }; - _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); - - var service = CreateService(); - var now = DateTimeOffset.UtcNow; - - service.Evaluate(ShowerState.Active, now); - service.Evaluate(ShowerState.Completed, now.AddMinutes(5)); - service.Evaluate(ShowerState.Idle, now.AddMinutes(16)); - - _haContextMock.Verify(x => x.CallService("switch", "turn_off", - It.IsAny(), It.IsAny()), Times.Once); - } - - [Fact] - public void Evaluate_AfterShowerEndsButRunPeriodNotElapsed_KeepsFanOn() - { - var entityState = new EntityState { State = "off" }; - _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); - - var service = CreateService(); - var now = DateTimeOffset.UtcNow; - - service.Evaluate(ShowerState.Active, now); - service.Evaluate(ShowerState.Completed, now.AddMinutes(5)); - service.Evaluate(ShowerState.Idle, now.AddMinutes(8)); - - _haContextMock.Verify(x => x.CallService("switch", "turn_off", - It.IsAny(), It.IsAny()), Times.Never); - } - - [Fact] - public void Reset_WhenFanWasTurnedOnByUs_TurnsFanOff() - { - var entityState = new EntityState { State = "off" }; - _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); - - var service = CreateService(); - service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow); - - var fanOnState = new EntityState { State = "on" }; - _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(fanOnState); - - service.Reset(); - - _haContextMock.Verify(x => x.CallService("switch", "turn_off", - It.IsAny(), It.IsAny()), Times.Once); - } - - [Fact] - public void Reset_WhenFanWasNotTurnedOnByUs_DoesNotTurnFanOff() - { - var service = CreateService(); - service.Reset(); - - _haContextMock.Verify(x => x.CallService("switch", "turn_off", - It.IsAny(), It.IsAny()), Times.Never); + targets.Should().HaveCount(expectedCount, because); + targets.Should().OnlyContain( + target => target != null + && target.EntityIds != null + && target.EntityIds.Count == 1 + && target.EntityIds.Single() == expectedEntityId, + because); } } diff --git a/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs b/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs index 222de91..17d830c 100644 --- a/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs +++ b/ShowerMonitor.Manager.Tests/HumidityRateCalculatorTests.cs @@ -1,105 +1,128 @@ using FluentAssertions; +using Microsoft.Extensions.Time.Testing; +using ShowerMonitor.Models; using ShowerMonitorManager; namespace ShowerMonitor.Manager.Tests; public class HumidityRateCalculatorTests { - private const int DefaultWindowSize = 5; + private const int DefaultWindowSize = ShowerMonitorConsts.DefaultRateWindowSize; + + private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider(); + + private DateTimeOffset Now => _timeProvider.GetUtcNow(); + + public static IEnumerable RateCases => + [ + ["no readings", 5, Array.Empty(), Array.Empty(), 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] + ]; + + [Theory] + [MemberData(nameof(RateCases))] + public void GetRatePerMinute_ShouldReturnExpectedRate( + string scenario, + int windowSize, + double[] humidities, + int[] offsetSeconds, + double expectedRate) + { + humidities.Should().HaveSameCount(offsetSeconds); + var calculator = new HumidityRateCalculator(windowSize); + + for (var i = 0; i < humidities.Length; i++) + { + calculator.RecordReading(humidities[i], Now.AddSeconds(offsetSeconds[i])); + } + + calculator.GetRatePerMinute().Should().BeApproximately(expectedRate, 1e-6, $"scenario: {scenario}"); + } [Fact] - public void GetRatePerMinute_WithNoReadings_ReturnsZero() + public void GetRatePerMinute_WithGeneratedLinearSeries_ReturnsSlopeForEveryWindowSize() + { + const double ratePerMinute = 2.5; + var series = ShowerMonitorTestData.CreateLinearHumiditySeries( + startHumidity: 45.0, + ratePerMinute: ratePerMinute, + sampleCount: 12); + + for (var windowSize = 2; windowSize <= series.Count; windowSize++) + { + var calculator = new HumidityRateCalculator(windowSize); + + foreach (var sample in series) + { + calculator.RecordReading(sample.Humidity, Now + sample.Offset); + } + + calculator.GetRatePerMinute() + .Should() + .BeApproximately(ratePerMinute, 1e-9, $"window size {windowSize}"); + } + } + + [Fact] + public void GetRatePerMinute_AfterReset_AndWithASingleNewReading_ReturnsZero() { var calculator = new HumidityRateCalculator(DefaultWindowSize); + calculator.RecordReading(52.9, Now); + calculator.RecordReading(62.9, Now.AddMinutes(1)); + + calculator.Reset(); + calculator.RecordReading(70.0, Now.AddMinutes(2)); calculator.GetRatePerMinute().Should().Be(0.0); } [Fact] - public void GetRatePerMinute_WithSingleReading_ReturnsZero() + public void PreviousReading_IsNullBeforeAnyReading() { var calculator = new HumidityRateCalculator(DefaultWindowSize); - calculator.RecordReading(52.9, DateTimeOffset.UtcNow); - calculator.GetRatePerMinute().Should().Be(0.0); + calculator.PreviousReading.Should().BeNull(); } [Fact] - public void GetRatePerMinute_WithRisingHumidity_ReturnsPositiveRate() + public void PreviousReading_TracksMostRecentReadingEvenAfterWindowEviction() { - var calculator = new HumidityRateCalculator(DefaultWindowSize); - var baseTime = DateTimeOffset.UtcNow; + var calculator = new HumidityRateCalculator(2); - calculator.RecordReading(52.9, baseTime); - calculator.RecordReading(62.9, baseTime.AddMinutes(1)); + calculator.RecordReading(52.9, Now); + calculator.RecordReading(57.9, Now.AddMinutes(1)); + calculator.RecordReading(64.9, Now.AddMinutes(2)); - calculator.GetRatePerMinute().Should().BeApproximately(10.0, 0.01); + calculator.PreviousReading.Should().Be(64.9); } [Fact] - public void GetRatePerMinute_WithFallingHumidity_ReturnsNegativeRate() + public void Reset_ClearsReadingsAndPreviousReading() { var calculator = new HumidityRateCalculator(DefaultWindowSize); - var baseTime = DateTimeOffset.UtcNow; - - calculator.RecordReading(62.9, baseTime); - calculator.RecordReading(52.9, baseTime.AddMinutes(2)); - - calculator.GetRatePerMinute().Should().BeApproximately(-5.0, 0.01); - } - - [Fact] - public void GetRatePerMinute_ExceedingWindowSize_DropsStalestReading() - { - var calculator = new HumidityRateCalculator(3); - var baseTime = DateTimeOffset.UtcNow; - - calculator.RecordReading(52.9, baseTime); - calculator.RecordReading(57.9, baseTime.AddMinutes(1)); - calculator.RecordReading(62.9, baseTime.AddMinutes(2)); - calculator.RecordReading(64.9, baseTime.AddMinutes(3)); - - var rate = calculator.GetRatePerMinute(); - rate.Should().BeApproximately(3.5, 0.01); - } - - [Fact] - public void GetRatePerMinute_WithSameTimestamp_ReturnsZero() - { - var calculator = new HumidityRateCalculator(DefaultWindowSize); - var sameTime = DateTimeOffset.UtcNow; - - calculator.RecordReading(52.9, sameTime); - calculator.RecordReading(62.9, sameTime); - - calculator.GetRatePerMinute().Should().Be(0.0); - } - - [Fact] - public void Reset_ClearsAllReadings() - { - var calculator = new HumidityRateCalculator(DefaultWindowSize); - var baseTime = DateTimeOffset.UtcNow; - - calculator.RecordReading(52.9, baseTime); - calculator.RecordReading(62.9, baseTime.AddMinutes(1)); + calculator.RecordReading(52.9, Now); + calculator.RecordReading(62.9, Now.AddMinutes(1)); calculator.Reset(); calculator.GetRatePerMinute().Should().Be(0.0); - } - - [Fact] - public void GetRatePerMinute_SimulatesShowerSpike_DetectsHighRate() - { - var calculator = new HumidityRateCalculator(DefaultWindowSize); - var baseTime = DateTimeOffset.UtcNow; - - calculator.RecordReading(52.9, baseTime); - calculator.RecordReading(59.9, baseTime.AddSeconds(30)); - calculator.RecordReading(64.9, baseTime.AddSeconds(60)); - - var rate = calculator.GetRatePerMinute(); - rate.Should().BeGreaterThan(4.0); + calculator.PreviousReading.Should().BeNull(); } } diff --git a/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs b/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs index 36f7031..b1c6c84 100644 --- a/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs +++ b/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs @@ -1,5 +1,6 @@ using FluentAssertions; using Microsoft.Extensions.Options; +using Microsoft.Extensions.Time.Testing; using ShowerMonitor.Models.Enums; using ShowerMonitorManager; using ShowerMonitorManager.Interface; @@ -9,16 +10,456 @@ namespace ShowerMonitor.Manager.Tests; public class ShowerDetectionServiceTests { - private readonly ShowerMonitorOptions _defaultOptions = new() + private readonly ShowerMonitorOptions _defaultOptions = ShowerMonitorTestData.CreateOptions(); + private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider(); + + private DateTimeOffset Now => _timeProvider.GetUtcNow(); + + public static IEnumerable 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 IEnumerable 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 IEnumerable 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 IEnumerable 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] + ]; + + [Fact] + public void InitialState_IsIdle() { - SpikeRateThreshold = 4.0, - MinDifferentialHumidity = 8.0, - PeakHumidityThreshold = 58.0, - ConfirmationWindowMinutes = 2, - RecoveryDifferentialThreshold = 5.0, - MaxShowerDurationMinutes = 60, - RateWindowSize = 5 - }; + var service = CreateService(); + + service.CurrentState.Should().Be(ShowerState.Idle); + service.CurrentSession.Should().BeNull(); + service.LastCompletedSession.Should().BeNull(); + service.TodaySessionCount.Should().Be(0); + service.LastRate.Should().Be(0.0); + } + + [Theory] + [MemberData(nameof(IdleThresholdCases))] + public void Evaluate_FromIdle_EntersSuspectedOnlyWhenRateAndDifferentialMeetThresholds( + string scenario, + double bathroomHumidity, + double mainHomeHumidity, + ShowerState expectedState) + { + var service = CreateService(); + var start = Now; + service.Evaluate(50.0, 42.0, start); + + var state = service.Evaluate(bathroomHumidity, mainHomeHumidity, start.AddSeconds(30)); + + state.Should().Be(expectedState, $"scenario: {scenario}"); + service.CurrentState.Should().Be(expectedState, $"scenario: {scenario}"); + service.TodaySessionCount.Should().Be(0); + service.LastCompletedSession.Should().BeNull(); + + if (expectedState == ShowerState.Suspected) + { + service.CurrentSession.Should().NotBeNull(); + service.CurrentSession!.StartTime.Should().Be(start.AddSeconds(30)); + } + else + { + service.CurrentSession.Should().BeNull(); + } + } + + [Fact] + public void Evaluate_FromIdle_WithGradualRise_RemainsIdle() + { + var service = CreateService(); + var start = Now; + service.Evaluate(52.9, 50.5, start); + + var state = service.Evaluate(53.2, 50.5, start.AddSeconds(30)); + + state.Should().Be(ShowerState.Idle); + service.LastRate.Should().BeApproximately(0.6, 1e-9); + service.CurrentSession.Should().BeNull(); + } + + [Fact] + public void Evaluate_FromIdle_WithNoPreviousSample_RemainsIdle() + { + var service = CreateService(); + + var state = service.Evaluate(60.0, 50.0, Now); + + state.Should().Be(ShowerState.Idle); + service.LastRate.Should().Be(0.0); + service.CurrentSession.Should().BeNull(); + } + + [Fact] + public void Evaluate_FromIdle_WithStaleTimestamp_RemainsIdle() + { + var service = CreateService(); + var start = Now; + service.Evaluate(52.9, 50.5, start); + + var state = service.Evaluate(70.0, 50.0, start.AddSeconds(-30)); + + state.Should().Be(ShowerState.Idle); + service.LastRate.Should().Be(0.0); + service.CurrentSession.Should().BeNull(); + } + + [Theory] + [MemberData(nameof(ConfirmationCases))] + public void Evaluate_FromSuspected_ConfirmsOnlyAfterWindowPeakAndDifferential( + string scenario, + double bathroomHumidity, + double mainHomeHumidity, + int secondsAfterSpike, + ShowerState expectedState) + { + var service = CreateService(); + var start = Now; + EvaluateBaselineAndSpike(service, start); + + var state = service.Evaluate( + bathroomHumidity, + mainHomeHumidity, + start.AddSeconds(30 + secondsAfterSpike)); + + state.Should().Be(expectedState, $"scenario: {scenario}"); + service.CurrentState.Should().Be(expectedState, $"scenario: {scenario}"); + service.TodaySessionCount.Should().Be(0); + service.LastCompletedSession.Should().BeNull(); + + if (expectedState == ShowerState.Active) + { + service.CurrentSession.Should().NotBeNull(); + } + } + + [Fact] + public void Evaluate_FromSuspected_WithFallingRateButHighDifferential_RemainsSuspected() + { + var service = CreateService(); + var start = Now; + EvaluateBaselineAndSpike(service, start); + + var state = service.Evaluate(52.0, 43.0, start.AddMinutes(2)); + + state.Should().Be(ShowerState.Suspected); + service.CurrentSession.Should().NotBeNull(); + } + + [Fact] + public void Evaluate_FromSuspected_WhenRateAndDifferentialDrop_ReturnsToIdleWithoutSession() + { + var service = CreateService(); + var start = Now; + EvaluateBaselineAndSpike(service, start); + + var state = service.Evaluate(50.0, 43.0, start.AddMinutes(2)); + + state.Should().Be(ShowerState.Idle); + service.CurrentState.Should().Be(ShowerState.Idle); + service.CurrentSession.Should().BeNull(); + service.TodaySessionCount.Should().Be(0); + service.LastCompletedSession.Should().BeNull(); + } + + [Fact] + public void Evaluate_WithSustainedSpike_TransitionsToActive() + { + var service = CreateService(); + var start = Now; + EvaluateBaselineAndSpike(service, start); + + var state = service.Evaluate(68.0, 49.5, start.AddMinutes(3)); + + state.Should().Be(ShowerState.Active); + service.CurrentState.Should().Be(ShowerState.Active); + } + + [Fact] + public void Evaluate_TracksLastRate() + { + var service = CreateService(); + var start = Now; + + service.LastRate.Should().Be(0.0); + + EvaluateBaselineAndSpike(service, start); + + service.LastRate.Should().BeApproximately(13.1, 1e-6); + } + + [Fact] + public void Evaluate_TracksCurrentSessionPeakAndPreEventHumidity() + { + var service = CreateService(); + var start = Now; + service.Evaluate(52.9, 50.5, start); + service.Evaluate(58.5, 49.5, start.AddSeconds(30)); + + var session = service.CurrentSession!; + session.StartTime.Should().Be(start.AddSeconds(30)); + session.PreEventHumidity.Should().Be(58.5); + session.PeakHumidity.Should().Be(58.5); + session.PeakTime.Should().Be(start.AddSeconds(30)); + session.EndTime.Should().BeNull(); + + service.Evaluate(66.0, 49.5, start.AddSeconds(60)); + + session.PeakHumidity.Should().Be(66.0); + session.PeakTime.Should().Be(start.AddSeconds(60)); + + service.Evaluate(64.0, 49.5, start.AddSeconds(90)); + + session.PeakHumidity.Should().Be(66.0); + session.PeakTime.Should().Be(start.AddSeconds(60)); + } + + [Fact] + public void Evaluate_FullShowerCycle_CompletesSession() + { + var service = CreateService(); + var start = Now; + + DriveToActive(service, start); + service.CurrentState.Should().Be(ShowerState.Active); + service.TodaySessionCount.Should().Be(0); + + DryDownToCompletion(service, start); + + service.CurrentState.Should().Be(ShowerState.Completed); + service.TodaySessionCount.Should().Be(1); + service.CurrentSession.Should().BeNull(); + + service.LastCompletedSession.Should().NotBeNull(); + var session = service.LastCompletedSession!; + session.StartTime.Should().Be(start.AddSeconds(30)); + session.EndTime.Should().Be(start.AddMinutes(13)); + session.PeakHumidity.Should().Be(70.0); + session.PeakTime.Should().Be(start.AddMinutes(4)); + } + + [Fact] + public void Evaluate_Active_DeclinesWhenRateTurnsNegativeAndDifferentialDropsBelowThreshold() + { + var service = CreateService(); + var start = Now; + DriveToActive(service, start); + + service.Evaluate(66.0, 49.5, start.AddMinutes(4)); + service.Evaluate(64.0, 49.5, start.AddMinutes(5)); + service.Evaluate(62.0, 49.5, start.AddMinutes(6)); + service.Evaluate(60.0, 49.5, start.AddMinutes(7)); + var stillActive = service.Evaluate(58.0, 49.5, start.AddMinutes(8)); + var declining = service.Evaluate(56.0, 49.5, start.AddMinutes(9)); + + stillActive.Should().Be(ShowerState.Active); + declining.Should().Be(ShowerState.Declining); + service.TodaySessionCount.Should().Be(0); + } + + [Theory] + [MemberData(nameof(RecoveryBoundaryCases))] + public void Evaluate_Declining_CompletesOnlyWhenDifferentialRecovers( + string scenario, + double mainHomeHumidity, + ShowerState expectedState) + { + var service = CreateService(); + var start = Now; + DriveToActive(service, start); + DryDownToThreshold(service, start); + + var declining = service.Evaluate(55.0, mainHomeHumidity, start.AddMinutes(11)); + var state = service.Evaluate(55.0, mainHomeHumidity, start.AddMinutes(12)); + + declining.Should().Be(ShowerState.Declining, $"scenario: {scenario}"); + state.Should().Be(expectedState, $"scenario: {scenario}"); + + if (expectedState == ShowerState.Completed) + { + service.TodaySessionCount.Should().Be(1); + service.LastCompletedSession.Should().NotBeNull(); + service.LastCompletedSession!.EndTime.Should().Be(start.AddMinutes(12)); + } + else + { + service.TodaySessionCount.Should().Be(0); + service.LastCompletedSession.Should().BeNull(); + } + } + + [Theory] + [MemberData(nameof(MaxDurationCases))] + public void Evaluate_Active_DeclinesAtMaxShowerDuration( + string scenario, + int secondsAfterSessionStart, + ShowerState expectedState) + { + var service = CreateService(); + var start = Now; + DriveToActive(service, start); + + var state = service.Evaluate(68.0, 49.5, start.AddSeconds(30 + secondsAfterSessionStart)); + + state.Should().Be(expectedState, $"scenario: {scenario}"); + } + + [Fact] + public void Evaluate_Declining_PastMaxDuration_CompletesEvenWithHighDifferential() + { + var service = CreateService(); + var start = Now; + DriveToActive(service, start); + + var declining = service.Evaluate(68.0, 49.5, start.AddSeconds(30 + 3_600)); + var completed = service.Evaluate(68.0, 49.5, start.AddSeconds(30 + 3_601)); + + declining.Should().Be(ShowerState.Declining); + completed.Should().Be(ShowerState.Completed); + service.TodaySessionCount.Should().Be(1); + service.LastCompletedSession!.EndTime.Should().Be(start.AddSeconds(30 + 3_601)); + } + + [Fact] + public void Evaluate_Completed_TransitionsToIdleAndResetsRateWindow() + { + var service = CreateService(); + var start = Now; + DriveToCompleted(service, start); + service.CurrentState.Should().Be(ShowerState.Completed); + + var idle = service.Evaluate(53.0, 50.5, start.AddMinutes(14)); + idle.Should().Be(ShowerState.Idle); + service.LastRate.Should().NotBe(0.0); + + var stillIdle = service.Evaluate(53.1, 50.5, start.AddMinutes(15)); + stillIdle.Should().Be(ShowerState.Idle); + service.LastRate.Should().Be(0.0); + service.TodaySessionCount.Should().Be(1); + } + + [Fact] + public void Evaluate_BackToBackShowers_CountsAsTwoSessions() + { + var service = CreateService(); + var start = Now; + + DriveToCompleted(service, start); + service.TodaySessionCount.Should().Be(1); + + service.Evaluate(53.0, 50.5, start.AddMinutes(14)); + DriveToCompleted(service, start.AddMinutes(15)); + + service.TodaySessionCount.Should().Be(2); + service.LastCompletedSession.Should().NotBeNull(); + service.LastCompletedSession!.StartTime.Should().Be(start.AddMinutes(15).AddSeconds(30)); + service.LastCompletedSession!.EndTime.Should().Be(start.AddMinutes(28)); + } + + [Fact] + public void ResetDailyCounters_AfterCompletedSession_ClearsCounters() + { + var service = CreateService(); + var start = Now; + DriveToCompleted(service, start); + + service.ResetDailyCounters(); + + service.TodaySessionCount.Should().Be(0); + service.LastCompletedSession.Should().BeNull(); + service.CurrentState.Should().Be(ShowerState.Completed); + } + + [Fact] + public void ResetDailyCounters_WhileActive_KeepsLiveSession() + { + var service = CreateService(); + var start = Now; + DriveToActive(service, start); + var session = service.CurrentSession; + + service.ResetDailyCounters(); + + service.CurrentState.Should().Be(ShowerState.Active); + service.CurrentSession.Should().BeSameAs(session); + service.TodaySessionCount.Should().Be(0); + service.LastCompletedSession.Should().BeNull(); + } + + [Fact] + public void Evaluate_WithCustomSpikeThreshold_RequiresConfiguredRate() + { + var service = CreateService(options: ShowerMonitorTestData.CreateOptions(spikeRateThreshold: 20.0)); + var start = Now; + + service.Evaluate(50.0, 42.0, start); + var state = service.Evaluate(52.0, 44.0, start.AddSeconds(30)); + + state.Should().Be(ShowerState.Idle); + service.LastRate.Should().BeApproximately(4.0, 1e-9); + } + + [Fact] + public void Evaluate_WithCustomConfirmationWindow_UsesConfiguredWindow() + { + var service = CreateService(options: ShowerMonitorTestData.CreateOptions(confirmationWindowMinutes: 5)); + var start = Now; + EvaluateBaselineAndSpike(service, start); + + var early = service.Evaluate(68.0, 49.5, start.AddMinutes(3)); + var confirmed = service.Evaluate(68.0, 49.5, start.AddMinutes(5).AddSeconds(30)); + + early.Should().Be(ShowerState.Suspected); + confirmed.Should().Be(ShowerState.Active); + } + + [Fact] + public void Evaluate_WithGeneratedHumiditySweep_ActivatesOnlyAtOrAbovePeakThreshold() + { + var start = Now; + + for (var humidity = 57.0; humidity <= 61.0; humidity += 0.5) + { + var service = CreateService(); + EvaluateBaselineAndSpike(service, start); + + var state = service.Evaluate(humidity, 49.0, start.AddSeconds(30 + 120)); + var expected = humidity >= 58.0 ? ShowerState.Active : ShowerState.Suspected; + + state.Should().Be(expected, $"humidity {humidity:F1} at confirmation time"); + } + } private ShowerDetectionService CreateService( IHumidityRateCalculator? rateCalculator = null, @@ -27,141 +468,44 @@ public class ShowerDetectionServiceTests var opts = options ?? _defaultOptions; var calculator = rateCalculator ?? new HumidityRateCalculator(opts.RateWindowSize); - return new ShowerDetectionService( - calculator, - Options.Create(opts)); + return new ShowerDetectionService(calculator, Options.Create(opts)); } - [Fact] - public void InitialState_IsIdle() + private static void EvaluateBaselineAndSpike(ShowerDetectionService service, DateTimeOffset start) { - var service = CreateService(); - service.CurrentState.Should().Be(ShowerState.Idle); + service.Evaluate(52.9, 50.5, start); + service.Evaluate(58.5, 49.5, start.AddSeconds(30)); + service.Evaluate(66.0, 49.5, start.AddSeconds(60)); } - [Fact] - public void Evaluate_WithNoSpike_RemainsIdle() + private static void DriveToActive(ShowerDetectionService service, DateTimeOffset start) { - var service = CreateService(); - var baseTime = DateTimeOffset.UtcNow; - - service.Evaluate(52.9, 50.5, baseTime); - service.Evaluate(53.2, 50.5, baseTime.AddSeconds(30)); - - service.CurrentState.Should().Be(ShowerState.Idle); + EvaluateBaselineAndSpike(service, start); + service.Evaluate(68.0, 49.5, start.AddMinutes(3)); } - [Fact] - public void Evaluate_WithShowerSpike_TransitionsToSuspected() + private static void DriveToCompleted(ShowerDetectionService service, DateTimeOffset start) { - var service = CreateService(); - var baseTime = DateTimeOffset.UtcNow; - - service.Evaluate(52.9, 50.5, baseTime); - service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); - var state = service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); - - state.Should().Be(ShowerState.Suspected); + DriveToActive(service, start); + DryDownToCompletion(service, start); } - [Fact] - public void Evaluate_WithSustainedSpike_TransitionsToActive() + private static void DryDownToThreshold(ShowerDetectionService service, DateTimeOffset start) { - var service = CreateService(); - var baseTime = DateTimeOffset.UtcNow; - - service.Evaluate(52.9, 50.5, baseTime); - service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); - service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); - - var state = service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3)); - - state.Should().Be(ShowerState.Active); + service.Evaluate(70.0, 50.0, start.AddMinutes(4)); + service.Evaluate(68.0, 50.0, start.AddMinutes(5)); + service.Evaluate(66.0, 50.0, start.AddMinutes(6)); + service.Evaluate(64.0, 50.0, start.AddMinutes(7)); + service.Evaluate(62.0, 50.0, start.AddMinutes(8)); + service.Evaluate(60.0, 50.0, start.AddMinutes(9)); + service.Evaluate(58.0, 50.0, start.AddMinutes(10)); } - [Fact] - public void Evaluate_FullShowerCycle_CompletesSession() + private static void DryDownToCompletion(ShowerDetectionService service, DateTimeOffset start) { - var service = CreateService(); - var baseTime = DateTimeOffset.UtcNow; - - service.Evaluate(52.9, 50.5, baseTime); - service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); - service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); - service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3)); - - service.CurrentState.Should().Be(ShowerState.Active); - - service.Evaluate(61.0, 50.0, baseTime.AddMinutes(10)); - service.Evaluate(56.0, 50.5, baseTime.AddMinutes(15)); - - service.Evaluate(53.5, 50.5, baseTime.AddMinutes(20)); - - service.TodaySessionCount.Should().BeGreaterThanOrEqualTo(1); - service.LastCompletedSession.Should().NotBeNull(); - } - - [Fact] - public void Evaluate_SuspectedThenDrops_ReturnsToIdle() - { - var service = CreateService(); - var baseTime = DateTimeOffset.UtcNow; - - service.Evaluate(52.9, 50.5, baseTime); - service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); - service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); - - service.CurrentState.Should().Be(ShowerState.Suspected); - - service.Evaluate(57.0, 50.0, baseTime.AddMinutes(2)); - service.Evaluate(54.0, 50.0, baseTime.AddMinutes(3)); - service.Evaluate(52.5, 50.5, baseTime.AddMinutes(4)); - service.Evaluate(52.0, 50.5, baseTime.AddMinutes(5)); - - service.CurrentState.Should().Be(ShowerState.Idle); - } - - [Fact] - public void ResetDailyCounters_ClearsSessionCount() - { - var service = CreateService(); - var baseTime = DateTimeOffset.UtcNow; - - service.Evaluate(52.9, 50.5, baseTime); - service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); - service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); - service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3)); - service.Evaluate(56.0, 50.5, baseTime.AddMinutes(15)); - service.Evaluate(53.5, 50.5, baseTime.AddMinutes(20)); - - service.ResetDailyCounters(); - - service.TodaySessionCount.Should().Be(0); - service.LastCompletedSession.Should().BeNull(); - } - - [Fact] - public void Evaluate_BackToBackShowers_CountsAsTwoSessions() - { - var service = CreateService(); - var baseTime = DateTimeOffset.UtcNow; - - service.Evaluate(52.9, 50.5, baseTime); - service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30)); - service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60)); - service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3)); - service.Evaluate(56.0, 50.5, baseTime.AddMinutes(10)); - service.Evaluate(53.5, 50.5, baseTime.AddMinutes(15)); - - var firstCount = service.TodaySessionCount; - - service.Evaluate(52.9, 50.5, baseTime.AddMinutes(20)); - service.Evaluate(58.5, 49.5, baseTime.AddMinutes(20).AddSeconds(30)); - service.Evaluate(66.0, 49.5, baseTime.AddMinutes(21)); - service.Evaluate(68.0, 49.5, baseTime.AddMinutes(23)); - service.Evaluate(56.0, 50.5, baseTime.AddMinutes(30)); - service.Evaluate(53.5, 50.5, baseTime.AddMinutes(35)); - - service.TodaySessionCount.Should().BeGreaterThan(firstCount); + DryDownToThreshold(service, start); + service.Evaluate(57.0, 50.0, start.AddMinutes(11)); + service.Evaluate(56.0, 50.0, start.AddMinutes(12)); + service.Evaluate(55.0, 50.0, start.AddMinutes(13)); } } diff --git a/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj b/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj index 00bf47d..7d8480c 100644 --- a/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj +++ b/ShowerMonitor.Manager.Tests/ShowerMonitor.Manager.Tests.csproj @@ -8,19 +8,19 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + diff --git a/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs b/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs new file mode 100644 index 0000000..1a49bb7 --- /dev/null +++ b/ShowerMonitor.Manager.Tests/ShowerMonitorTestData.cs @@ -0,0 +1,78 @@ +using Microsoft.Extensions.Time.Testing; +using NetDaemon.HassModel.Entities; +using ShowerMonitor.Models; +using ShowerMonitorManager.Models; + +namespace ShowerMonitor.Manager.Tests; + +/// +/// Shared, deterministic fixtures for the shower monitor tests. +/// Keeping options, fan states and sample series here avoids copy-pasted setup +/// across test classes and keeps every timestamp independent of the wall clock. +/// +internal static class ShowerMonitorTestData +{ + /// Fixed base time used by all timestamp-sensitive tests. + public static readonly DateTimeOffset BaseTimestamp = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero); + + /// Creates a fake clock positioned at unless overridden. + public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? start = null) => new(start ?? BaseTimestamp); + + /// + /// Builds monitor options from the production defaults, overriding only the + /// values a test cares about. + /// + public static ShowerMonitorOptions CreateOptions( + string exhaustFanEntityId = ShowerMonitorConsts.ExhaustFanEntityId, + int? fanRunAfterShowerMinutes = null, + double spikeRateThreshold = ShowerMonitorConsts.DefaultSpikeRateThreshold, + double minDifferentialHumidity = ShowerMonitorConsts.DefaultMinDifferentialHumidity, + double peakHumidityThreshold = ShowerMonitorConsts.DefaultPeakHumidityThreshold, + int confirmationWindowMinutes = ShowerMonitorConsts.DefaultConfirmationWindowMinutes, + double recoveryDifferentialThreshold = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold, + int? maxShowerDurationMinutes = null, + int rateWindowSize = ShowerMonitorConsts.DefaultRateWindowSize) + { + return new ShowerMonitorOptions + { + ExhaustFanEntityId = exhaustFanEntityId, + FanRunAfterShowerMinutes = fanRunAfterShowerMinutes + ?? (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes, + SpikeRateThreshold = spikeRateThreshold, + MinDifferentialHumidity = minDifferentialHumidity, + PeakHumidityThreshold = peakHumidityThreshold, + ConfirmationWindowMinutes = confirmationWindowMinutes, + RecoveryDifferentialThreshold = recoveryDifferentialThreshold, + MaxShowerDurationMinutes = maxShowerDurationMinutes + ?? (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes, + RateWindowSize = rateWindowSize + }; + } + + /// Creates the HA state payload for the exhaust fan. + public static EntityState FanState(string? state) => new() { State = state }; + + /// A humidity sample with its offset from a test's base timestamp. + public readonly record struct HumiditySample(double Humidity, TimeSpan Offset); + + /// Builds a sample series from (humidity, offset-in-seconds) pairs. + public static IReadOnlyList CreateHumiditySeries( + params (double Humidity, int OffsetSeconds)[] samples) => + samples.Select(sample => new HumiditySample(sample.Humidity, TimeSpan.FromSeconds(sample.OffsetSeconds))) + .ToArray(); + + /// + /// Generates evenly spaced samples along a constant humidity slope, useful for + /// exercising every window size against a known rate. + /// + public static IReadOnlyList CreateLinearHumiditySeries( + double startHumidity, + double ratePerMinute, + int sampleCount, + int intervalSeconds = 60) => + Enumerable.Range(0, sampleCount) + .Select(i => new HumiditySample( + startHumidity + (ratePerMinute * i * intervalSeconds / 60.0), + TimeSpan.FromSeconds(i * intervalSeconds))) + .ToArray(); +} diff --git a/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj b/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj index 32dc900..22f9bb2 100644 --- a/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj +++ b/ShowerMonitor.Manager/ShowerMonitor.Manager.csproj @@ -19,9 +19,9 @@ - - - + + + diff --git a/ShowerMonitor.Models/ShowerMonitor.Models.csproj b/ShowerMonitor.Models/ShowerMonitor.Models.csproj index 2b2ef03..4c156c4 100644 --- a/ShowerMonitor.Models/ShowerMonitor.Models.csproj +++ b/ShowerMonitor.Models/ShowerMonitor.Models.csproj @@ -12,7 +12,7 @@ - + diff --git a/qodana.yaml b/qodana.yaml new file mode 100644 index 0000000..7a58035 --- /dev/null +++ b/qodana.yaml @@ -0,0 +1,81 @@ +#-------------------------------------------------------------------------------# +# Qodana analysis is configured by qodana.yaml file # +# https://www.jetbrains.com/help/qodana/qodana-yaml.html # +#-------------------------------------------------------------------------------# +################################################################################# +# WARNING: Do not store sensitive information in this file, # +# as its contents will be included in the Qodana report. # +################################################################################# +version: "1.0" +#Specify IDE code to run analysis without container (Applied in CI/CD pipeline) +ide: QDNET +#Specify inspection profile for code analysis +profile: + name: qodana.starter +include: + - name: ConvertIfStatementToReturnStatement + - name: ConvertIfStatementToConditionalTernaryExpression + - name: AutoPropertyCanBeMadeGetOnly.Global + - name: ConvertIfStatementToSwitchStatement + - name: ConvertConstructorToMemberInitializers + - name: ConvertToPrimaryConstructor + - name: ConvertToExtensionBlock + - name: ConvertClosureToMethodGroup + - name: ConvertToConstant.Global + - name: ConvertToConstant.Local + - name: ConvertToAutoPropertyWithPrivateSetter + - name: DuplicatedSequentialIfBodies + - name: InlineTemporaryVariable + - name: InvertIf + - name: LoopCanBeConvertedToQuery + - name: MemberCanBePrivate.Global + - name: MemberCanBeMadeStatic.Global + - name: MemberCanBeMadeStatic.Local + - name: MergeIntoPattern + - name: UnusedMethodReturnValue.Global + - name: PreferExplicitlyProvidedTupleComponentName + - name: PropertyCanBeMadeInitOnly.Global + - name: MoveLocalFunctionAfterJumpStatement + - name: RedundantExplicitParamsArrayCreation + - name: ArrangeRedundantParentheses + - name: CA1861 + - name: CA1873 + - name: xUnit1045 + - name: CA1822 + - name: xUnit1042 + - name: CA1859 + - name: SwitchStatementHandlesSomeKnownEnumValuesWithDefault + - name: UnusedMemberInSuper.Global + - name: UnusedMember.Global + - name: UnusedParameter.Global + - name: UseCollectionExpression + - name: SuggestVarOrType_SimpleTypes + +#Enable inspections +#include: +# - name: +#Disable inspections +#exclude: +# - name: +# paths: +# - +#Execute shell command before Qodana execution (Applied in CI/CD pipeline) +#bootstrap: sh ./prepare-qodana.sh +#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline) +#plugins: +# - id: #(plugin id can be found at https://plugins.jetbrains.com) +# Quality gate. Will fail the CI/CD pipeline if any condition is not met +# severityThresholds - configures maximum thresholds for different problem severities +# testCoverageThresholds - configures minimum code coverage on a whole project and newly added code +# dependencyLicenses - fails the run on prohibited or unknown dependency licenses +# Code Coverage is available in Ultimate and Ultimate Plus plans +#failureConditions: +# severityThresholds: +# any: 15 +# critical: 5 +# testCoverageThresholds: +# fresh: 70 +# total: 50 +# dependencyLicenses: +# failOnProhibited: true +# failOnUnknown: false