605 lines
24 KiB
C#
605 lines
24 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));
|
|
}
|
|
|
|
#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);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task UpdateEntitiesAsync_WithTodayAndTomorrowPrices_ShouldUpdateCombinedSensor()
|
|
{
|
|
// Arrange
|
|
var todayStart = new DateTime(2026, 3, 31, 6, 0, 0, DateTimeKind.Utc);
|
|
var tomorrowStart = new DateTime(2026, 4, 1, 6, 0, 0, DateTimeKind.Utc);
|
|
var todayPrice = new NordPoolPrice
|
|
{
|
|
Prices =
|
|
[
|
|
new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
|
|
new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 12.50 }
|
|
]
|
|
};
|
|
var tomorrowPrice = new NordPoolPrice
|
|
{
|
|
Prices =
|
|
[
|
|
new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }
|
|
]
|
|
};
|
|
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
|
|
|
|
_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 - state is update time in yyyy-MM-dd HH:mm:ss format
|
|
_entityManagerMock.Verify(
|
|
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(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<object>(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 = 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.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s =>
|
|
s.Length > 0 && s.Contains('-') && s != "0")),
|
|
Times.Once);
|
|
_entityManagerMock.Verify(
|
|
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is<object>(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.71 }]
|
|
};
|
|
var context = CreateDefaultContext(todayPrice: new NordPoolPrice { Prices = [] }, tomorrowPrice: tomorrowPrice);
|
|
|
|
_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_tomorrow_prices", It.Is<string>(s =>
|
|
s.Length > 0 && s.Contains('-') && s != "0")),
|
|
Times.Once);
|
|
_entityManagerMock.Verify(
|
|
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is<object>(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, 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");
|
|
}
|
|
|
|
#endregion
|
|
}
|