#region using System.Text; using System.Text.Json; using FluentAssertions; using HomeAssistant.Entities.Interfaces; using Microsoft.Extensions.Logging; using Moq; using NordPool.Models; using NordPoolManager; using NordPoolManager.Models; #endregion namespace NordPool.Manager.Tests; public class NordPoolEntityServiceTests { private readonly Mock _entityManagerMock; private readonly Mock> _loggerMock; private readonly NordPoolEntityService _sut; public NordPoolEntityServiceTests() { _entityManagerMock = new Mock(); _loggerMock = new Mock>(); _sut = new NordPoolEntityService(_entityManagerMock.Object, _loggerMock.Object); } #region GetInitEntitiesList [Fact] public void GetInitEntitiesList_ShouldReturnAllEntities() { // Act var result = NordPoolEntityService.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 = NordPoolEntityService.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 = NordPoolEntityService.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 = NordPoolEntityService.GetInitEntitiesList("EUR/kWh"); // Assert result.Should().OnlyContain(e => e.Domain == "sensor" || e.Domain == "button"); } [Fact] public void GetInitEntitiesList_AllEntities_ShouldHaveUniqueEntityIds() { // Act var result = NordPoolEntityService.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())) .Returns(Task.CompletedTask); // Act await _sut.CreateEntitiesAsync("EUR/kWh"); // Assert _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(7)); } [Fact] public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldContinueWithOthers() { // Arrange var callCount = 0; _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) .Returns(() => { callCount++; return callCount == 2 ? throw new InvalidOperationException("Entity creation failed") : Task.CompletedTask; }); // Act await _sut.CreateEntitiesAsync("EUR/kWh"); // Assert _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(7)); } [Fact] public async Task CreateEntitiesAsync_WithNullUnitOfMeasurement_ShouldStillCreateAllEntities() { // Arrange _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) .Returns(Task.CompletedTask); // Act await _sut.CreateEntitiesAsync(null); // Assert _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(7)); } #endregion #region CleanupEntitiesAsync [Fact] public async Task CleanupEntitiesAsync_ShouldRemoveAllEntities() { // Arrange _entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny())) .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())) .ThrowsAsync(new InvalidOperationException("Remove failed")); // Act var act = () => _sut.CleanupEntitiesAsync(); // Assert await act.Should().ThrowAsync().WithMessage("Remove failed"); } #endregion #region SetEntityStateSafe [Fact] public async Task SetEntityStateSafe_ShouldCallSetEntityState() { // Arrange _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .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(), It.IsAny())) .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(), It.IsAny())) .Returns(Task.CompletedTask); // Act await _sut.SetEntityAttributesSafe("sensor.test", attributes); // Assert _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.test", It.IsAny()), 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(), It.IsAny())) .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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .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", string.Empty), 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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); // Act await _sut.ResetEntitiesAsync(); // Assert _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), Times.Once); _entityManagerMock.Verify( em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), Times.Once); _entityManagerMock.Verify( em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny()), Times.Once); } [Fact] public async Task ResetEntitiesAsync_WhenOneEntityFails_ShouldNotThrow() { // Arrange _entityManagerMock.Setup(em => em.SetEntityState("sensor.nordpool_current_price", It.IsAny())) .ThrowsAsync(new InvalidOperationException("State update failed")); _entityManagerMock.Setup(em => em.SetEntityState(It.Is(id => id != "sensor.nordpool_current_price"), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); // Act await _sut.ResetEntitiesAsync(); // Assert _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(7)); _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), 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 { new NordPoolDayPrice { Price = 12.50 } } }, TomorrowNordPoolPrice = tomorrowPrice ?? new NordPoolPrice { Prices = new List { new NordPoolDayPrice { 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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); // Act await _sut.UpdateEntitiesAsync(context); // Assert _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny()), 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(s => s.Contains('-') && s.Contains(':'))), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny()), Times.Once); } [Fact] public async Task UpdateEntitiesAsync_ShouldSetAttributesForPriceEntities() { // Arrange var context = CreateDefaultContext(); _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); // Act await _sut.UpdateEntitiesAsync(context); // Assert _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), Times.Once); _entityManagerMock.Verify( em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), 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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .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(s => s.Length > 0 && s != "0" && s.Contains('-'))), Times.Once); } [Fact] public async Task UpdateEntitiesAsync_WithMergedPriceScenarios_ShouldPublishSortedFilteredPrices() { // Arrange - xUnit cannot serialize NordPoolPrice rows, so the matrix is exercised in one test var todayStart = new DateTime(2026, 3, 31, 6, 0, 0, DateTimeKind.Utc); var tomorrowStart = new DateTime(2026, 4, 1, 6, 0, 0, DateTimeKind.Utc); (string Scenario, NordPoolPrice? TodayPrice, NordPoolPrice? TomorrowPrice, int ExpectedMergedCount)[] cases = [ ( "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 ), ( "only today", new NordPoolPrice { Prices = [ new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 } ] }, new NordPoolPrice { Prices = [] }, 1 ), ( "only tomorrow", new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [ new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 } ] }, 1 ), ("empty lists", new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] }, 0), ("null lists", new NordPoolPrice { Prices = null }, new NordPoolPrice { Prices = null }, 0), ("null price objects", null, null, 0) ]; foreach (var (scenario, todayPrice, tomorrowPrice, expectedMergedCount) in cases) { // Arrange object? capturedAttributes = null; _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) .Callback((_, attrs) => capturedAttributes = attrs) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny())) .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)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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); // Act await _sut.UpdateEntitiesAsync(context); // Assert _entityManagerMock.Verify( em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(o => o.GetType().GetProperty("prices")!.GetValue(o) is List)), 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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) .Callback((_, attrs) => capturedAttributes = attrs) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny())) .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 = JsonSerializer.Serialize(capturedAttributes); var byteCount = 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(price); _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny())) .Callback((_, attrs) => capturedAttributes = attrs) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_current_price"), It.IsAny())) .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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny())) .Callback((_, attrs) => capturedAttributes = attrs) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny())) .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)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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny())) .Callback((_, attrs) => capturedAttributes = attrs) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny())) .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)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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny())) .Callback((_, attrs) => capturedAttributes = attrs) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny())) .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)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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) .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(), It.Is((state, _) => state != null && state.ToString()!.Contains("exceeds expected maximum")), It.IsAny(), It.IsAny>()), Times.Once); } #endregion #region Cancellation public static TheoryData> CancelledOperations() { var data = new TheoryData>(); var cancelled = new CancellationToken(true); var context = CreateDefaultContext(); data.Add("create entities", sut => sut.CreateEntitiesAsync("EUR/kWh", cancelled)); data.Add("reset entities", sut => sut.ResetEntitiesAsync(cancelled)); data.Add("update entities", sut => sut.UpdateEntitiesAsync(context, cancelled)); data.Add("cleanup entities", sut => sut.CleanupEntitiesAsync(cancelled)); return data; } [Theory] [MemberData(nameof(CancelledOperations))] public async Task Operation_WithCancelledToken_ShouldThrowAndNotWriteAnything( string scenario, Func operation) { // Act var act = () => operation(_sut); // Assert await act.Should().ThrowAsync($"scenario: {scenario}"); _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Never); _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Never); _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), Times.Never); _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Never); } #endregion }