Files
HomeAssistant/NordPool.Manager.Tests/NordPoolEntityServiceTests.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

865 lines
36 KiB
C#

using FluentAssertions;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
using Moq;
using NordPool.Models;
using NordPoolManager;
using NordPoolManager.Models;
namespace NordPool.Manager.Tests;
public class NordPoolEntityServiceTests
{
private readonly Mock<IEntityManager> _entityManagerMock;
private readonly Mock<ILogger<NordPoolEntityService>> _loggerMock;
private readonly NordPoolEntityService _sut;
public NordPoolEntityServiceTests()
{
_entityManagerMock = new Mock<IEntityManager>();
_loggerMock = new Mock<ILogger<NordPoolEntityService>>();
_sut = new NordPoolEntityService(_entityManagerMock.Object, _loggerMock.Object);
}
#region GetInitEntitiesList
[Fact]
public void GetInitEntitiesList_ShouldReturnAllEntities()
{
// Act
var result = _sut.GetInitEntitiesList("EUR/kWh");
// Assert
result.Should().NotBeNull();
result.Should().HaveCount(7);
result.Should().Contain(e => e.EntityId == "sensor.nordpool_last_update_time");
result.Should().Contain(e => e.EntityId == "sensor.nordpool_current_price");
result.Should().Contain(e => e.EntityId == "sensor.nordpool_today_prices");
result.Should().Contain(e => e.EntityId == "sensor.nordpool_tomorrow_prices");
result.Should().Contain(e => e.EntityId == "sensor.nordpool_today_tomorrow_prices");
result.Should().Contain(e => e.EntityId == "sensor.nordpool_cheapest_intervals");
result.Should().Contain(e => e.EntityId == "button.nordpool_fetch_prices");
}
[Fact]
public void GetInitEntitiesList_ShouldHaveCorrectEntityProperties()
{
// Act
var result = _sut.GetInitEntitiesList("EUR/kWh");
// Assert
var entity = result.First(e => e.EntityId == "sensor.nordpool_current_price");
entity.Domain.Should().Be("sensor");
entity.Identifier.Should().Be("nordpool_current_price");
entity.Name.Should().Be("NordPool current price");
}
[Fact]
public void GetInitEntitiesList_CurrentPriceEntity_ShouldHaveMonetaryDeviceClassConfig()
{
// Act
var result = _sut.GetInitEntitiesList("EUR/kWh");
// Assert
var currentPriceEntity = result.First(e => e.EntityId == "sensor.nordpool_current_price");
currentPriceEntity.Options.Should().NotBeNull();
currentPriceEntity.Options!.UniqueId.Should().Be("sensor.nordpool_current_price");
currentPriceEntity.Options!.Name.Should().Be("NordPool current price");
currentPriceEntity.AdditionalConfig.Should().NotBeNull();
}
[Fact]
public void GetInitEntitiesList_ShouldContainExpectedDomains()
{
// Act
var result = _sut.GetInitEntitiesList("EUR/kWh");
// Assert
result.Should().OnlyContain(e => e.Domain == "sensor" || e.Domain == "button");
}
[Fact]
public void GetInitEntitiesList_AllEntities_ShouldHaveUniqueEntityIds()
{
// Act
var result = _sut.GetInitEntitiesList("EUR/kWh");
// Assert
result.Select(e => e.EntityId).Should().OnlyHaveUniqueItems();
}
#endregion
#region CreateEntitiesAsync
[Fact]
public async Task CreateEntitiesAsync_ShouldCreateAllEntities()
{
// Arrange
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
.Returns(Task.CompletedTask);
// Act
await _sut.CreateEntitiesAsync("EUR/kWh");
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(7));
}
[Fact]
public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldContinueWithOthers()
{
// Arrange
var callCount = 0;
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
.Returns(() =>
{
callCount++;
if (callCount == 2)
{
throw new InvalidOperationException("Entity creation failed");
}
return Task.CompletedTask;
});
// Act
await _sut.CreateEntitiesAsync("EUR/kWh");
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(7));
}
[Fact]
public async Task CreateEntitiesAsync_WithNullUnitOfMeasurement_ShouldStillCreateAllEntities()
{
// Arrange
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
.Returns(Task.CompletedTask);
// Act
await _sut.CreateEntitiesAsync(null);
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(7));
}
#endregion
#region CleanupEntitiesAsync
[Fact]
public async Task CleanupEntitiesAsync_ShouldRemoveAllEntities()
{
// Arrange
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
// Act
await _sut.CleanupEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_last_update_time"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_current_price"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_today_prices"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_tomorrow_prices"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_today_tomorrow_prices"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_cheapest_intervals"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("button.nordpool_fetch_prices"), Times.Once);
}
[Fact]
public async Task CleanupEntitiesAsync_WhenRemoveThrows_ShouldRethrow()
{
// Arrange
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Remove failed"));
// Act
var act = () => _sut.CleanupEntitiesAsync();
// Assert
await act.Should().ThrowAsync<InvalidOperationException>().WithMessage("Remove failed");
}
#endregion
#region SetEntityStateSafe
[Fact]
public async Task SetEntityStateSafe_ShouldCallSetEntityState()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
// Act
await _sut.SetEntityStateSafe("sensor.test", "42");
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.test", "42"), Times.Once);
}
[Fact]
public async Task SetEntityStateSafe_WhenExceptionThrown_ShouldNotRethrow()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("State update failed"));
// Act
var act = () => _sut.SetEntityStateSafe("sensor.test", "42");
// Assert
await act.Should().NotThrowAsync();
}
#endregion
#region SetEntityAttributesSafe
[Fact]
public async Task SetEntityAttributesSafe_ShouldCallSetEntityAttributes()
{
// Arrange
var attributes = new { unit_of_measurement = "EUR/kWh" };
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
await _sut.SetEntityAttributesSafe("sensor.test", attributes);
// Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.test", It.IsAny<object>()), Times.Once);
}
[Fact]
public async Task SetEntityAttributesSafe_WhenExceptionThrown_ShouldNotRethrow()
{
// Arrange
var attributes = new { unit_of_measurement = "EUR/kWh" };
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.ThrowsAsync(new InvalidOperationException("Attributes update failed"));
// Act
var act = () => _sut.SetEntityAttributesSafe("sensor.test", attributes);
// Assert
await act.Should().NotThrowAsync();
}
#endregion
#region ResetEntitiesAsync
[Fact]
public async Task ResetEntitiesAsync_ShouldSetDefaultStateForAllEntities()
{
// Arrange
_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);
// Act
await _sut.ResetEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", "unknown"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", ""), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("button.nordpool_fetch_prices", "unknown"), Times.Once);
}
[Fact]
public async Task ResetEntitiesAsync_ShouldSetDefaultAttributesForAllEntities()
{
// Arrange
_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);
// Act
await _sut.ResetEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny<object>()), Times.Once);
}
[Fact]
public async Task ResetEntitiesAsync_WhenOneEntityFails_ShouldNotThrow()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState("sensor.nordpool_current_price", It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("State update failed"));
_entityManagerMock.Setup(em => em.SetEntityState(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
var act = () => _sut.ResetEntitiesAsync();
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task ResetEntitiesAsync_ShouldCallSetStateAndAttributesCorrectly()
{
// Arrange - 7 entities get state and attributes
_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);
// Act
await _sut.ResetEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(7));
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Exactly(7));
}
#endregion
#region UpdateEntitiesAsync
private static EntityUpdateContext CreateDefaultContext(
double currentPrice = 17.91,
NordPoolPrice? todayPrice = null,
NordPoolPrice? tomorrowPrice = null)
{
return new EntityUpdateContext
{
CurrentPrice = currentPrice,
UnitOfMeasurement = "EUR/kWh",
DayQuartersIndex = 5,
LastApiUpdateDate = DateTime.UtcNow,
UsingCachedData = false,
TodayNordPoolPrice = todayPrice ?? new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
},
TomorrowNordPoolPrice = tomorrowPrice ?? new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
},
CheapestIntervals = [],
ConfiguredHours = 2.0,
ConfiguredIntervalCount = 4,
ConfiguredPriceCap = 25.0,
SkipPriceCap = false,
ConfiguredReadyBy = "18:00",
IsNowCheap = false,
NextCheapIntervalStart = null
};
}
[Fact]
public async Task UpdateEntitiesAsync_ShouldSetStateForAllEntities()
{
// Arrange
var context = CreateDefaultContext();
_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);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "17.91"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "1"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "1"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_ShouldSetAttributesForPriceEntities()
{
// Arrange
var context = CreateDefaultContext();
_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);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WhenNoPrices_ShouldSetZeroCounts()
{
// Arrange
var context = CreateDefaultContext(
todayPrice: new NordPoolPrice { Prices = null },
tomorrowPrice: new NordPoolPrice { Prices = null });
_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);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s =>
s.Length > 0 && s != "0" && s.Contains('-'))),
Times.Once);
}
public static IEnumerable<object?[]> MergedPriceScenarios()
{
var todayStart = new DateTime(2026, 3, 31, 6, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 6, 0, 0, DateTimeKind.Utc);
yield return
[
"today and tomorrow with null-start entry filtered",
new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
new NordPoolDayPrice { Start = null, End = todayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
]
},
new NordPoolPrice
{
Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }]
},
2
];
yield return
[
"only today",
new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 }] },
new NordPoolPrice { Prices = [] },
1
];
yield return
[
"only tomorrow",
new NordPoolPrice { Prices = [] },
new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] },
1
];
yield return ["empty lists", new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] }, 0];
yield return ["null lists", new NordPoolPrice { Prices = null }, new NordPoolPrice { Prices = null }, 0];
yield return ["null price objects", (NordPoolPrice?)null, (NordPoolPrice?)null, 0];
}
[Theory]
[MemberData(nameof(MergedPriceScenarios))]
public async Task UpdateEntitiesAsync_WithMergedPriceScenarios_ShouldPublishSortedFilteredPrices(
string scenario,
NordPoolPrice? todayPrice,
NordPoolPrice? tomorrowPrice,
int expectedMergedCount)
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext() with
{
TodayNordPoolPrice = todayPrice,
TomorrowNordPoolPrice = tomorrowPrice
};
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
var prices = (List<CompactNordPoolDayPrice>)type.GetProperty("prices")!.GetValue(attributes)!;
prices.Should().HaveCount(expectedMergedCount, $"scenario: {scenario}");
prices.Select(p => p.Start).Should().BeInAscendingOrder();
type.GetProperty("prices_count")!.GetValue(attributes).Should().Be(expectedMergedCount);
}
[Fact]
public async Task UpdateEntitiesAsync_TodayTomorrowPrices_ShouldUseCompactFormat()
{
// Arrange
var todayPrice = new NordPoolPrice
{
Prices = [new NordPoolDayPrice
{
Start = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc),
End = new DateTime(2026, 3, 31, 10, 15, 0, DateTimeKind.Utc),
Price = 17.91
}]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
_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);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is<object>(o =>
o.GetType().GetProperty("prices")!.GetValue(o) is List<CompactNordPoolDayPrice>)),
Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WithFullDayPrices_AttributesShouldBeUnderSizeLimit()
{
// Arrange
const int intervalsPerDay = 96;
const int haAttributeByteLimitBytes = 16_384;
var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
var todayPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice
{
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 4.93 + i * 0.22
}).ToList();
var tomorrowPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice
{
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 5.50 + i * 0.22
}).ToList();
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext(
todayPrice: new NordPoolPrice { Prices = todayPrices },
tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices });
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
capturedAttributes.Should().NotBeNull();
var json = System.Text.Json.JsonSerializer.Serialize(capturedAttributes);
var byteCount = System.Text.Encoding.UTF8.GetByteCount(json);
byteCount.Should().BeLessThan(haAttributeByteLimitBytes,
$"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
}
[Theory]
[InlineData(17.91, "17.91")]
[InlineData(0.0, "0.00")]
[InlineData(-5.25, "-5.25")]
[InlineData(1234.5, "1234.50")]
[InlineData(17.916, "17.92")]
public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price, string expected)
{
// Arrange
var context = CreateDefaultContext(currentPrice: price);
_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);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", expected), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_CurrentPriceAttributes_ShouldReflectContext()
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext() with
{
UnitOfMeasurement = "EUR/MWh",
DayQuartersIndex = 42,
LastApiUpdateDate = null,
UsingCachedData = true
};
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
type.GetProperty("unit_of_measurement")!.GetValue(attributes).Should().Be("EUR/MWh");
type.GetProperty("device_class")!.GetValue(attributes).Should().Be("monetary");
type.GetProperty("state_class")!.GetValue(attributes).Should().Be("measurement");
type.GetProperty("last_api_fetch")!.GetValue(attributes).Should().BeNull();
type.GetProperty("using_cached_data")!.GetValue(attributes).Should().Be(true);
type.GetProperty("current_quarter_index")!.GetValue(attributes).Should().Be(42);
type.GetProperty("last_updated")!.GetValue(attributes).Should().NotBeNull();
}
[Fact]
public async Task UpdateEntitiesAsync_CheapestIntervalsAttributes_ShouldSummarizeSchedule()
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var first = new CheapestIntervalResult
{
Start = new DateTime(2026, 3, 31, 22, 0, 0, DateTimeKind.Utc),
End = new DateTime(2026, 3, 31, 22, 15, 0, DateTimeKind.Utc),
Price = 4.93,
Rank = 1
};
var second = new CheapestIntervalResult
{
Start = new DateTime(2026, 3, 31, 23, 0, 0, DateTimeKind.Utc),
End = new DateTime(2026, 3, 31, 23, 15, 0, DateTimeKind.Utc),
Price = 5.63,
Rank = 2
};
var context = CreateDefaultContext() with
{
CheapestIntervals = [first, second],
ConfiguredHours = 0.5,
ConfiguredIntervalCount = 2,
ConfiguredPriceCap = 25.0,
SkipPriceCap = true,
ConfiguredReadyBy = "06:30",
IsNowCheap = true,
NextCheapIntervalStart = first.Start
};
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "2"), Times.Once);
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should().HaveCount(2);
type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(30);
type.GetProperty("is_now_cheap")!.GetValue(attributes).Should().Be(true);
type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().Be(first.Start.ToString("O"));
type.GetProperty("skip_price_cap")!.GetValue(attributes).Should().Be(true);
type.GetProperty("configured_hours")!.GetValue(attributes).Should().Be(0.5);
type.GetProperty("configured_interval_count")!.GetValue(attributes).Should().Be(2);
type.GetProperty("configured_price_cap")!.GetValue(attributes).Should().Be(25.0);
type.GetProperty("configured_ready_by")!.GetValue(attributes).Should().Be("06:30");
}
[Fact]
public async Task UpdateEntitiesAsync_WhenCheapestIntervalsAreNull_ShouldPublishEmptyIntervals()
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext() with { CheapestIntervals = null };
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once);
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should().BeEmpty();
type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(0);
type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().BeNull();
}
[Fact]
public async Task UpdateEntitiesAsync_MergedPrices_ShouldDropEntriesWithoutStartAndSortByStart()
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var todayPrice = new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = dayStart.AddHours(2), End = dayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
]
};
var tomorrowPrice = new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 }
]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
var prices = (List<CompactNordPoolDayPrice>)type.GetProperty("prices")!.GetValue(attributes)!;
prices.Should().HaveCount(2);
prices.Select(p => p.Start).Should().BeInAscendingOrder();
type.GetProperty("prices_count")!.GetValue(attributes).Should().Be(2);
}
[Fact]
public async Task UpdateEntitiesAsync_WhenMergedPricesExceedExpectedMaximum_ShouldLogWarning()
{
// Arrange
_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 todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
var todayPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice
{
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 10.0
}).ToList();
var tomorrowPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice
{
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 10.0
}).ToList();
var context = CreateDefaultContext(
todayPrice: new NordPoolPrice { Prices = todayPrices },
tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices });
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_loggerMock.Verify(
l => l.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((state, _) => state != null && state.ToString()!.Contains("exceeds expected maximum")),
It.IsAny<Exception?>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
Times.Once);
}
#endregion
#region Cancellation
public static IEnumerable<object[]> CancelledOperations()
{
var cancelled = new CancellationToken(canceled: true);
var context = CreateDefaultContext();
yield return ["create entities", (Func<NordPoolEntityService, Task>)(sut => sut.CreateEntitiesAsync("EUR/kWh", cancelled))];
yield return ["reset entities", (Func<NordPoolEntityService, Task>)(sut => sut.ResetEntitiesAsync(cancelled))];
yield return ["update entities", (Func<NordPoolEntityService, Task>)(sut => sut.UpdateEntitiesAsync(context, cancelled))];
yield return ["cleanup entities", (Func<NordPoolEntityService, Task>)(sut => sut.CleanupEntitiesAsync(cancelled))];
}
[Theory]
[MemberData(nameof(CancelledOperations))]
public async Task Operation_WithCancelledToken_ShouldThrowAndNotWriteAnything(
string scenario,
Func<NordPoolEntityService, Task> operation)
{
// Act
var act = () => operation(_sut);
// Assert
await act.Should().ThrowAsync<OperationCanceledException>($"scenario: {scenario}");
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), 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
}