Files
HomeAssistant/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs
T

336 lines
14 KiB
C#

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<IEntityManager> _entityManagerMock;
private readonly Mock<ILogger<PowerMonitorEntityService>> _loggerMock;
private readonly PowerMonitorEntityService _sut;
public PowerMonitorEntityServiceTests()
{
_entityManagerMock = new Mock<IEntityManager>();
_loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
_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<PowerMonitorEntity>()))
.Returns(Task.CompletedTask);
await _sut.CreateSystemEntitiesAsync();
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(13));
}
[Fact]
public async Task CreateSystemEntitiesAsync_WhenOneEntityFails_ShouldContinueWithOthers()
{
var callCount = 0;
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.Returns(() =>
{
callCount++;
if (callCount == 3)
{
throw new InvalidOperationException("Entity creation failed");
}
return Task.CompletedTask;
});
await _sut.CreateSystemEntitiesAsync();
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(13));
}
#endregion
#region CreateDeviceEntitiesAsync
[Fact]
public async Task CreateDeviceEntitiesAsync_ShouldCreate4EntitiesPerDevice()
{
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.Returns(Task.CompletedTask);
var sensors = new List<PowerSensorInfo>
{
new() { EntityId = "sensor.sonoff_100215c534_power", FriendlyName = "AC Power", DeviceName = "sonoff_100215c534" },
new() { EntityId = "sensor.sonoff_10018909cb_power", FriendlyName = "Induction Power", DeviceName = "sonoff_10018909cb" }
};
await _sut.CreateDeviceEntitiesAsync(sensors);
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(8));
}
#endregion
#region ResetEntitiesAsync
[Fact]
public async Task ResetEntitiesAsync_ShouldSetDefaultStates()
{
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.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<string>(), It.IsAny<string>()), Times.Exactly(12));
}
#endregion
#region CleanupEntitiesAsync
[Fact]
public async Task CleanupEntitiesAsync_ShouldRemoveAllSystemEntities()
{
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
await _sut.CleanupEntitiesAsync();
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(13));
}
#endregion
#region CleanupDeviceEntitiesAsync
[Fact]
public async Task CleanupDeviceEntitiesAsync_ShouldRemove4EntitiesPerDevice()
{
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
await _sut.CleanupDeviceEntitiesAsync(["device_a", "device_b"]);
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(8));
}
#endregion
#region UpdateEntitiesAsync
[Fact]
public async Task UpdateEntitiesAsync_ShouldUpdateAllSystemEntities()
{
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext();
await _sut.UpdateEntitiesAsync(context);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", It.IsAny<string>()), 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<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext();
await _sut.UpdateEntitiesAsync(context);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_15min", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_1h", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_daily", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_monthly", It.IsAny<string>()), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WhenAnomaly_ShouldSetAnomalyOn()
{
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
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<string>(), It.IsAny<string>()))
.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<string>(), It.IsAny<object>()))
.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 = 341.97,
KnownDevicesSumWatts = 210.93,
RawOtherPowerWatts = 131.04,
SmoothedOtherPowerWatts = 128.5,
DataQuality = "ok",
DevicePowerReadings = new Dictionary<string, double>
{
["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<string, CostSnapshot>
{
["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"
};
}
}