Files
HomeAssistant/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs
T
gitea_admin 5777e641f6 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
2026-11-29 21:30:13 +02:00

546 lines
20 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 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<IEntityManager> _entityManagerMock;
private readonly Mock<ILogger<PowerMonitorEntityService>> _loggerMock;
private readonly PowerMonitorEntityService _sut;
public PowerMonitorEntityServiceTests()
{
_entityManagerMock = new Mock<IEntityManager>();
_loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>())).Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())).Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())).Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>())).Returns(Task.CompletedTask);
_sut = new PowerMonitorEntityService(_entityManagerMock.Object, _loggerMock.Object);
}
#region GetSystemEntitiesList
[Fact]
public void GetSystemEntitiesList_ShouldReturnAll14SystemEntities()
{
// Act
var result = _sut.GetSystemEntitiesList();
// Assert
result.Should().HaveCount(14);
}
[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();
// Assert
result.Should().Contain(entity => entity.EntityId == entityId);
}
[Fact]
public void GetSystemEntitiesList_AllEntities_ShouldHaveUniqueEntityIds()
{
// Act
var result = _sut.GetSystemEntitiesList();
// 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 GetPowerDeviceEntitiesNames
public static IEnumerable<object[]> DeviceEntityCases =>
[
["sonoff device", "sensor.sonoff_1002230e32_power", "Sonoff Power", "sonoff_1002230e32"],
["simple device", "sensor.tv_power", "TV Power", "tv"],
["device with suffix in name", "sensor.akvariumas_power", "Akvariumas Power", "akvariumas"],
["uppercase entity id", "sensor.TV_POWER", "TV Power", "TV"]
];
[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 PowerMonitorEntity_WhenNameIsBlank_ShouldFallBackToIdentifier()
{
// Arrange - PowerMonitorEntity falls back to the identifier so MQTT entities always have a name.
var entity = new PowerMonitorEntity("sensor", "powermonitor_test", " ");
// 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
[Theory]
[InlineData("sonoff_abc")]
[InlineData("tv")]
[InlineData("akvariumas")]
public void GetDeviceCostEntityIds_ShouldReturnFourEntityIds(string deviceName)
{
// Act
var result = PowerMonitorEntityService.GetDeviceCostEntityIds(deviceName).ToList();
// Assert
result.Should().HaveCount(4);
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
#region CreateSystemEntitiesAsync
[Fact]
public async Task CreateSystemEntitiesAsync_ShouldCreateAll14Entities()
{
// Act
await _sut.CreateSystemEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(14));
}
[Fact]
public async Task CreateSystemEntitiesAsync_WhenSomeEntitiesFail_ShouldContinueWithOthers()
{
// Arrange - both 1h cost entities fail, the remaining twelve must still be created.
_entityManagerMock
.Setup(em => em.CreateEntityAsync(It.Is<PowerMonitorEntity>(entity => entity.Identifier.EndsWith("_cost_1h"))))
.ThrowsAsync(new InvalidOperationException("Entity creation failed"));
// Act
await _sut.CreateSystemEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(14));
}
#endregion
#region CreateDeviceEntitiesAsync
[Theory]
[InlineData(0, 0)]
[InlineData(1, 4)]
[InlineData(2, 8)]
[InlineData(5, 20)]
public async Task CreateDeviceEntitiesAsync_ShouldCreateFourEntitiesPerSensor(int sensorCount, int expectedCreates)
{
// Arrange
var sensors = Enumerable.Range(0, sensorCount)
.Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}"))
.ToList();
// Act
await _sut.CreateDeviceEntitiesAsync(sensors);
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(expectedCreates));
}
#endregion
#region ResetEntitiesAsync
[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)
{
// Act
await _sut.ResetEntitiesAsync();
// 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<string>(), It.IsAny<string>()), 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<string>(), It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Failed"));
// Act
var act = () => _sut.ResetEntitiesAsync();
// Assert
await act.Should().NotThrowAsync();
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(12));
}
#endregion
#region RemoveSystemEntitiesAsync
[Fact]
public async Task RemoveSystemEntitiesAsync_ShouldRemoveAllSystemEntities()
{
// Act
await _sut.RemoveSystemEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.RemoveEntity(It.Is<string>(id => SystemEntityIds.Contains(id))), Times.Exactly(14));
}
[Fact]
public async Task RemoveSystemEntitiesAsync_WhenRemovalFails_ShouldRethrow()
{
// Arrange
_entityManagerMock
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Removal failed"));
// Act
var act = () => _sut.RemoveSystemEntitiesAsync();
// Assert
await act.Should().ThrowAsync<InvalidOperationException>();
}
#endregion
#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<string>()), Times.Exactly(expectedRemovals));
}
[Fact]
public async Task RemoveDeviceEntitiesAsync_WhenOneRemovalFails_ShouldContinueWithOthers()
{
// Arrange
_entityManagerMock
.Setup(em => em.RemoveEntity(It.Is<string>(id => id.Contains("_cost_daily"))))
.ThrowsAsync(new InvalidOperationException("Removal failed"));
// Act
var act = () => _sut.RemoveDeviceEntitiesAsync(["device_a", "device_b"]);
// Assert
await act.Should().NotThrowAsync();
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(8));
}
#endregion
#region UpdateEntitiesAsync
[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)
{
// Arrange
var context = PowerMonitorTestData.CreateUpdateContext();
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(entityId, It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes(entityId, It.IsAny<object>()), 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<string>()),
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<string>()))
.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);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny<object>()), Times.Once);
}
#endregion
#region SetEntityStateSafe / SetEntityAttributesSafe
[Fact]
public async Task SetEntityStateSafe_WhenExceptionThrown_ShouldNotRethrow()
{
// Arrange
_entityManagerMock
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Failed"));
// Act
var act = () => _sut.SetEntityStateSafe("sensor.test", "42");
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task SetEntityAttributesSafe_WhenExceptionThrown_ShouldNotRethrow()
{
// Arrange
_entityManagerMock
.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.ThrowsAsync(new InvalidOperationException("Failed"));
// Act
var act = () => _sut.SetEntityAttributesSafe("sensor.test", new { });
// Assert
await act.Should().NotThrowAsync();
}
#endregion
#region Cancellation
public static IEnumerable<object[]> CancelledOperations()
{
var cancelled = new CancellationToken(canceled: true);
var sensors = new List<PowerSensorInfo> { PowerMonitorTestData.CreateSensor("sensor.tv_power") };
var context = PowerMonitorTestData.CreateUpdateContext();
yield return ["create system entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.CreateSystemEntitiesAsync(cancelled))];
yield return ["create device entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.CreateDeviceEntitiesAsync(sensors, cancelled))];
yield return ["update entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.UpdateEntitiesAsync(context, cancelled))];
yield return ["reset entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.ResetEntitiesAsync(cancelled))];
yield return ["remove system entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.RemoveSystemEntitiesAsync(cancelled))];
yield return ["remove device entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.RemoveDeviceEntitiesAsync(["tv"], cancelled))];
}
[Theory]
[MemberData(nameof(CancelledOperations))]
public async Task Operation_WithCancelledToken_ShouldThrowAndNotTouchEntities(
string scenario,
Func<PowerMonitorEntityService, Task> operation)
{
// Act
var act = () => operation(_sut);
// Assert
await act.Should().ThrowAsync<OperationCanceledException>($"scenario: {scenario}");
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Never);
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Never);
}
#endregion
}