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 _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 = _sut.GetInitEntitiesList("EUR/kWh"); // Assert result.Should().NotBeNull(); result.Should().HaveCount(6); 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"); } [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"); } [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())) .Returns(Task.CompletedTask); // Act await _sut.CreateEntitiesAsync("EUR/kWh"); // Assert _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(6)); } [Fact] public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldContinueWithOthers() { // Arrange var callCount = 0; _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) .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()), Times.Exactly(6)); } #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); } [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", ""), 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); } [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); } [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 - 6 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(6)); _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), Times.Exactly(6)); } #endregion #region UpdateEntitiesAsync private static EntityUpdateContext CreateDefaultContext( double currentPrice = 12.5, 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() { Price = 10.0 } } }, TomorrowNordPoolPrice = tomorrowPrice ?? new NordPoolPrice { Prices = new List { new() { Price = 20.0 } } }, CheapestIntervals = [], ConfiguredHours = 1.0, ConfiguredIntervalCount = 4, ConfiguredPriceCap = 100.0, SkipPriceCap = false, ConfiguredReadyBy = "06: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", "12.50"), 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_WithTodayAndTomorrowPrices_ShouldUpdateCombinedSensor() { // Arrange var todayStart = new DateTime(2025, 3, 16, 6, 0, 0, DateTimeKind.Utc); var tomorrowStart = new DateTime(2025, 3, 17, 6, 0, 0, DateTimeKind.Utc); var todayPrice = new NordPoolPrice { Prices = [ new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 15.0 }, new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 10.0 } ] }; var tomorrowPrice = new NordPoolPrice { Prices = [ new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 20.0 } ] }; var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice); _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 - state is update time in yyyy-MM-dd HH:mm:ss format _entityManagerMock.Verify( em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => s.Length > 0 && s.Contains('-') && s.Contains(':') && s != "0" && s != "3")), Times.Once); // Assert - attributes contain merged, sorted prices (today 06:00, today 08:00, tomorrow 06:00) _entityManagerMock.Verify( em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(o => o.GetType().GetProperty("prices_count")!.GetValue(o)!.Equals(3))), Times.Once); } [Fact] public async Task UpdateEntitiesAsync_WithOnlyTodayPrices_ShouldUpdateCombinedSensor() { // Arrange var todayPrice = new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddMinutes(15), Price = 12.0 }] }; 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.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => s.Length > 0 && s.Contains('-') && s != "0")), Times.Once); _entityManagerMock.Verify( em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(o => o.GetType().GetProperty("prices_count")!.GetValue(o)!.Equals(1))), Times.Once); } [Fact] public async Task UpdateEntitiesAsync_WithOnlyTomorrowPrices_ShouldUpdateCombinedSensor() { // Arrange var tomorrowPrice = new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow.AddDays(1), End = DateTime.UtcNow.AddDays(1).AddMinutes(15), Price = 18.0 }] }; var context = CreateDefaultContext(todayPrice: new NordPoolPrice { Prices = [] }, tomorrowPrice: tomorrowPrice); _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_tomorrow_prices", It.Is(s => s.Length > 0 && s.Contains('-') && s != "0")), Times.Once); _entityManagerMock.Verify( em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(o => o.GetType().GetProperty("prices_count")!.GetValue(o)!.Equals(1))), Times.Once); } [Fact] public async Task UpdateEntitiesAsync_TodayTomorrowPrices_ShouldUseCompactFormat() { // Arrange var todayPrice = new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = new DateTime(2026, 3, 19, 10, 0, 0, DateTimeKind.Utc), End = new DateTime(2026, 3, 19, 10, 15, 0, DateTimeKind.Utc), Price = 12.0 }] }; 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, 19, 0, 0, 0, DateTimeKind.Utc); var tomorrowStart = new DateTime(2026, 3, 20, 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 = 5.0 + i * 0.1 }).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 = 8.0 + i * 0.1 }).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 = 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"); } #endregion }