Files
HomeAssistant/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs
T
gitea_admin f919d6b25b Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
2026-12-01 12:33:31 +02:00

575 lines
21 KiB
C#

#region
using FluentAssertions;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
using Moq;
using PowerMonitor.Models;
using PowerMonitorManager;
#endregion
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 = new Mock<IEntityManager>();
private readonly PowerMonitorEntityService _sut;
public PowerMonitorEntityServiceTests()
{
var loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>())).Returns(Task.CompletedTask);
_sut = new PowerMonitorEntityService(_entityManagerMock.Object, loggerMock.Object);
}
#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);
string[] expectedEntityIds =
[
$"sensor.powermonitor_{deviceName}_cost_15min",
$"sensor.powermonitor_{deviceName}_cost_1h",
$"sensor.powermonitor_{deviceName}_cost_daily",
$"sensor.powermonitor_{deviceName}_cost_monthly"
];
result.Should().BeEquivalentTo(expectedEntityIds);
}
#endregion
#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 GetSystemEntitiesList
[Fact]
public void GetSystemEntitiesList_ShouldReturnAll14SystemEntities()
{
// Act
var result = PowerMonitorEntityService.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 = PowerMonitorEntityService.GetSystemEntitiesList();
// Assert
result.Should().Contain(entity => entity.EntityId == entityId);
}
[Fact]
public void GetSystemEntitiesList_AllEntities_ShouldHaveUniqueEntityIds()
{
// Act
var result = PowerMonitorEntityService.GetSystemEntitiesList();
// Assert
result.Select(entity => entity.EntityId).Should().OnlyHaveUniqueItems();
}
[Fact]
public void GetSystemEntitiesList_AllEntities_ShouldExposeCreationOptions()
{
// Act
var result = PowerMonitorEntityService.GetSystemEntitiesList();
// Assert
result.Should().OnlyContain(entity => entity.Options != null && entity.Options.UniqueId == entity.EntityId);
}
#endregion
#region GetPowerDeviceEntitiesNames
public static TheoryData<string, string, string, string> DeviceEntityCases => new TheoryData<string, string, string, string>
{
{ "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}");
string[] expectedEntityIds =
[
$"sensor.powermonitor_{expectedDeviceName}_cost_15min",
$"sensor.powermonitor_{expectedDeviceName}_cost_1h",
$"sensor.powermonitor_{expectedDeviceName}_cost_daily",
$"sensor.powermonitor_{expectedDeviceName}_cost_monthly"
];
result.Select(entity => entity.EntityId).Should().BeEquivalentTo(expectedEntityIds, $"scenario: {scenario}");
result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}");
string[] expectedNames =
[
$"{friendlyName} cost (15 min)",
$"{friendlyName} cost (1h)",
$"{friendlyName} cost (daily)",
$"{friendlyName} cost (monthly)"
];
result.Select(entity => entity.Name).Should().BeEquivalentTo(expectedNames, $"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 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 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);
// 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 TheoryData<string, Func<PowerMonitorEntityService, Task>> CancelledOperations()
{
var data = new TheoryData<string, Func<PowerMonitorEntityService, Task>>();
var cancelled = new CancellationToken(true);
List<PowerSensorInfo> sensors = [PowerMonitorTestData.CreateSensor("sensor.tv_power")];
var context = PowerMonitorTestData.CreateUpdateContext();
data.Add("create system entities", sut => sut.CreateSystemEntitiesAsync(cancelled));
data.Add("create device entities", sut => sut.CreateDeviceEntitiesAsync(sensors, cancelled));
data.Add("update entities", sut => sut.UpdateEntitiesAsync(context, cancelled));
data.Add("reset entities", sut => sut.ResetEntitiesAsync(cancelled));
data.Add("remove system entities", sut => sut.RemoveSystemEntitiesAsync(cancelled));
data.Add("remove device entities", sut => sut.RemoveDeviceEntitiesAsync(["tv"], cancelled));
return data;
}
[Theory]
[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
}