using FluentAssertions; using HomeAssistant.Entities.Interfaces; using Microsoft.Extensions.Logging; using Moq; using PowerMonitor.Models; using PowerMonitorManager; using PowerMonitorManager.Models; namespace PowerMonitor.Manager.Tests; public class PowerMonitorEntityServiceTests { private readonly Mock _entityManagerMock; private readonly Mock> _loggerMock; private readonly PowerMonitorEntityService _sut; public PowerMonitorEntityServiceTests() { _entityManagerMock = new Mock(); _loggerMock = new Mock>(); _sut = new PowerMonitorEntityService(_entityManagerMock.Object, _loggerMock.Object); } #region GetSystemEntitiesList [Fact] public void GetSystemEntitiesList_ShouldReturnAll13SystemEntities() { var result = _sut.GetSystemEntitiesList(); result.Should().HaveCount(13); } [Fact] public void GetSystemEntitiesList_ShouldContainAllExpectedEntityIds() { 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"); } [Fact] public void GetSystemEntitiesList_AllEntities_ShouldHaveUniqueEntityIds() { var result = _sut.GetSystemEntitiesList(); result.Select(e => e.EntityId).Should().OnlyHaveUniqueItems(); } #endregion #region GetDeviceEntities [Fact] public void GetDeviceEntities_ShouldReturn4CostEntitiesPerDevice() { var sensor = new PowerSensorInfo { EntityId = "sensor.sonoff_1002230e32_power", FriendlyName = "Sonoff Power", DeviceName = "sonoff_1002230e32" }; 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"); } #endregion #region GetDeviceCostEntityIds [Fact] public void GetDeviceCostEntityIds_ShouldReturn4EntityIds() { var result = PowerMonitorEntityService.GetDeviceCostEntityIds("sonoff_abc").ToList(); 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"); } #endregion #region CreateSystemEntitiesAsync [Fact] public async Task CreateSystemEntitiesAsync_ShouldCreateAll13Entities() { _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) .Returns(Task.CompletedTask); await _sut.CreateSystemEntitiesAsync(); _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(13)); } [Fact] public async Task CreateSystemEntitiesAsync_WhenOneEntityFails_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; }); await _sut.CreateSystemEntitiesAsync(); _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(13)); } #endregion #region CreateDeviceEntitiesAsync [Fact] public async Task CreateDeviceEntitiesAsync_ShouldCreate4EntitiesPerDevice() { _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) .Returns(Task.CompletedTask); var sensors = new List { new() { EntityId = "sensor.device_a_power", FriendlyName = "Device A", DeviceName = "device_a" }, new() { EntityId = "sensor.device_b_power", FriendlyName = "Device B", DeviceName = "device_b" } }; await _sut.CreateDeviceEntitiesAsync(sensors); _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(8)); } #endregion #region ResetEntitiesAsync [Fact] public async Task ResetEntitiesAsync_ShouldSetDefaultStates() { _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); 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); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "initializing"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(12)); } #endregion #region CleanupEntitiesAsync [Fact] public async Task CleanupEntitiesAsync_ShouldRemoveAllSystemEntities() { _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())) .Returns(Task.CompletedTask); await _sut.CleanupEntitiesAsync(); _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Exactly(13)); } #endregion #region CleanupDeviceEntitiesAsync [Fact] public async Task CleanupDeviceEntitiesAsync_ShouldRemove4EntitiesPerDevice() { _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())) .Returns(Task.CompletedTask); await _sut.CleanupDeviceEntitiesAsync(["device_a", "device_b"]); _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Exactly(8)); } #endregion #region UpdateEntitiesAsync [Fact] public async Task UpdateEntitiesAsync_ShouldUpdateAllSystemEntities() { _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_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); _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_device_a_cost_15min", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_1h", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_cost_daily", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_device_a_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); } #endregion #region SetEntityStateSafe / SetEntityAttributesSafe [Fact] public async Task SetEntityStateSafe_WhenExceptionThrown_ShouldNotRethrow() { _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .ThrowsAsync(new InvalidOperationException("Failed")); var act = () => _sut.SetEntityStateSafe("sensor.test", "42"); await act.Should().NotThrowAsync(); } [Fact] public async Task SetEntityAttributesSafe_WhenExceptionThrown_ShouldNotRethrow() { _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .ThrowsAsync(new InvalidOperationException("Failed")); var act = () => _sut.SetEntityAttributesSafe("sensor.test", new { }); await act.Should().NotThrowAsync(); } #endregion private static PowerUpdateContext CreateDefaultContext(bool isAnomaly = false) { return new PowerUpdateContext { Calculation = new PowerCalculationResult { TotalPowerWatts = 1000, KnownDevicesSumWatts = 800, RawOtherPowerWatts = 200, SmoothedOtherPowerWatts = 195, DataQuality = "ok", DevicePowerReadings = new Dictionary { ["sensor.device_a_power"] = 500, ["sensor.device_b_power"] = 300 } }, CurrentNordPoolPrice = 0.10, PriceUnit = "EUR/kWh", PriceSource = "live", DeviceCosts = new Dictionary { ["sensor.device_a_power"] = new() { Cost15Min = 0.01, Cost1Hour = 0.04, CostDaily = 0.50, CostMonthly = 15.0 }, ["sensor.device_b_power"] = new() { Cost15Min = 0.005, Cost1Hour = 0.02, CostDaily = 0.30, CostMonthly = 9.0 } }, TotalCost = new CostSnapshot { Cost15Min = 0.02, Cost1Hour = 0.08, CostDaily = 1.00, CostMonthly = 30.0 }, OtherCost = new CostSnapshot { Cost15Min = 0.005, Cost1Hour = 0.02, CostDaily = 0.20, CostMonthly = 6.0 }, IsAnomaly = isAnomaly, AnomalyDuration = TimeSpan.Zero, AnomalyThresholdWatts = 500, TrackedSensorCount = 2, DegradedSensors = [], SystemStatus = "ok" }; } }