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
This commit is contained in:
2026-11-29 21:30:13 +02:00
parent 1152462765
commit 5777e641f6
79 changed files with 7162 additions and 3196 deletions
@@ -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<IEntityManager> _entityManagerMock;
private readonly Mock<ILogger<PowerMonitorEntityService>> _loggerMock;
private readonly PowerMonitorEntityService _sut;
@@ -18,6 +36,10 @@ public class 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);
}
@@ -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<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 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<PowerMonitorEntity>()))
.Returns(Task.CompletedTask);
// Act
await _sut.CreateSystemEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), 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<PowerMonitorEntity>()))
.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<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));
}
@@ -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<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" }
};
// 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<PowerMonitorEntity>()), Times.Exactly(8));
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), 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<string>(), It.IsAny<string>()))
.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<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 CleanupEntitiesAsync
#region RemoveSystemEntitiesAsync
[Fact]
public async Task CleanupEntitiesAsync_ShouldRemoveAllSystemEntities()
public async Task RemoveSystemEntitiesAsync_ShouldRemoveAllSystemEntities()
{
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
// Act
await _sut.RemoveSystemEntitiesAsync();
await _sut.CleanupEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.RemoveEntity(It.Is<string>(id => SystemEntityIds.Contains(id))), Times.Exactly(14));
}
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), 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 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<string>()), Times.Exactly(expectedRemovals));
}
[Fact]
public async Task CleanupDeviceEntitiesAsync_ShouldRemove4EntitiesPerDevice()
public async Task RemoveDeviceEntitiesAsync_WhenOneRemovalFails_ShouldContinueWithOthers()
{
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
// Arrange
_entityManagerMock
.Setup(em => em.RemoveEntity(It.Is<string>(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<string>()), 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<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.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<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);
// 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);
}
[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);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny<object>()), Times.Once);
}
#endregion
@@ -267,70 +479,67 @@ public class PowerMonitorEntityServiceTests
[Fact]
public async Task SetEntityStateSafe_WhenExceptionThrown_ShouldNotRethrow()
{
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
// 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()
{
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
// 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
private static PowerUpdateContext CreateDefaultContext(bool isAnomaly = false)
#region Cancellation
public static IEnumerable<object[]> CancelledOperations()
{
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"
};
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
}