Apply code formatting cleanup across the monitor projects

- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
This commit is contained in:
2026-12-01 12:33:31 +02:00
parent 77458383d1
commit f919d6b25b
115 changed files with 3115 additions and 1959 deletions
@@ -1,9 +1,13 @@
#region
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using NordPool.Models;
using NordPoolManager;
#endregion
namespace NordPool.Manager.Tests;
public class CheapestIntervalsFinderTests
@@ -13,7 +17,7 @@ public class CheapestIntervalsFinderTests
private static readonly DateTime DayStart = NordPoolTestData.DayStart;
private static readonly DateTime DeadlineEndOfDay = DayStart.AddDays(1);
private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock = new();
private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock = new Mock<ILogger<CheapestIntervalsFinder>>();
private CheapestIntervalsFinder CreateSut()
{
@@ -26,7 +30,7 @@ public class CheapestIntervalsFinderTests
}
private static NordPoolPrice CreatePricesForDay(DateTime dayStart,
int intervalCount = NordPoolConsts.MaxDailyIntervals)
int intervalCount = NordPoolConsts.MaxDailyIntervals)
{
return new NordPoolPrice
{
@@ -55,7 +59,7 @@ public class CheapestIntervalsFinderTests
#region FindCheapestIntervals
public static TheoryData<string, double[], int, double, double, int> FilteringCases => new()
public static TheoryData<string, double[], int, double, double, int> FilteringCases => new TheoryData<string, double[], int, double, double, int>
{
{ "deadline includes interval ending exactly at it", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_800.0, 2 },
{ "deadline excludes interval ending one second late", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_799.0, 1 },
@@ -236,12 +240,13 @@ public class CheapestIntervalsFinderTests
{
// Arrange — duplicate payload entries are not deduplicated
var sut = CreateSut();
var prices = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 },
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }
new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 },
new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }
}
};
@@ -258,15 +263,16 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var prices = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 },
new() { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null },
new() { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 },
new() { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 },
new() { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 }
new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 },
new NordPoolDayPrice { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null },
new NordPoolDayPrice { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 },
new NordPoolDayPrice { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 },
new NordPoolDayPrice { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 }
}
};
@@ -287,12 +293,12 @@ public class CheapestIntervalsFinderTests
const double priceCap = 12.0;
var expected = prices.Prices!
.Where(p => p.Price <= priceCap)
.OrderBy(p => p.Price)
.ThenBy(p => p.Start)
.Take(requestedIntervals)
.OrderBy(p => p.Start)
.ToList();
.Where(p => p.Price <= priceCap)
.OrderBy(p => p.Price)
.ThenBy(p => p.Start)
.Take(requestedIntervals)
.OrderBy(p => p.Start)
.ToList();
// Act
var result = sut.FindCheapestIntervals(prices, requestedIntervals, priceCap, DeadlineEndOfDay);
@@ -315,30 +321,31 @@ public class CheapestIntervalsFinderTests
{
// Arrange - xUnit cannot serialize CheapestIntervalResult rows, so the matrix is exercised in one test
var sut = CreateSut();
(string Scenario, int NowSeconds, CheapestIntervalResult[] Intervals, bool Expected)[] cases =
[
("inside interval", 10 * Hour + 7 * 60, [Interval(10 * Hour, 10 * Hour + Quarter)], true),
("exactly at start", 10 * Hour, [Interval(10 * Hour, 10 * Hour + Quarter)], true),
("exactly at end", 10 * Hour + Quarter, [Interval(10 * Hour, 10 * Hour + Quarter)], false),
("outside all intervals", 12 * Hour,
[Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter)], false),
[Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter)], false),
("boundary between adjacent intervals", 10 * Hour + Quarter,
[
Interval(10 * Hour, 10 * Hour + Quarter, 8.96),
Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, 6.20, 2)
], true),
[
Interval(10 * Hour, 10 * Hour + Quarter, 8.96),
Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, 6.20, 2)
], true),
("unsorted intervals", 14 * Hour + 5 * 60,
[Interval(14 * Hour, 14 * Hour + Quarter, 4.93, 2), Interval(10 * Hour, 10 * Hour + Quarter, 6.20)],
true),
[Interval(14 * Hour, 14 * Hour + Quarter, 4.93, 2), Interval(10 * Hour, 10 * Hour + Quarter, 6.20)],
true),
("before first interval", 10 * Hour - 1, [Interval(10 * Hour, 10 * Hour + Quarter)], false),
("in gap between intervals", 10 * Hour + 2 * Quarter,
[Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter)], false),
[Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter)], false),
("middle of three consecutive intervals", 10 * Hour + Quarter + 5 * 60,
[
Interval(10 * Hour, 10 * Hour + Quarter, rank: 1),
Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, rank: 2),
Interval(10 * Hour + 2 * Quarter, 10 * Hour + 3 * Quarter, rank: 3)
], true),
[
Interval(10 * Hour, 10 * Hour + Quarter, rank: 1),
Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, rank: 2),
Interval(10 * Hour + 2 * Quarter, 10 * Hour + 3 * Quarter, rank: 3)
], true),
("empty interval list", 12 * Hour, [], false)
];
@@ -1,21 +1,25 @@
#region
using System.Text;
using System.Text.Json;
using FluentAssertions;
using NordPool.Models;
using static NordPool.Models.NordPoolConsts;
#endregion
namespace NordPool.Manager.Tests;
public class CompactNordPoolDayPriceTests
{
private const int IntervalDurationSeconds = MinutesPerInterval * 60;
private static readonly DateTime TestStart = new(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime TestStart = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime TestEnd = TestStart.AddMinutes(MinutesPerInterval);
private static readonly long TestStartEpoch = new DateTimeOffset(TestStart).ToUnixTimeSeconds();
private static readonly long TestEndEpoch = new DateTimeOffset(TestEnd).ToUnixTimeSeconds();
public static TheoryData<string, string> InvalidJsonPayloads => new()
public static TheoryData<string, string> InvalidJsonPayloads => new TheoryData<string, string>
{
{ "empty array", "[]" },
{ "too few elements", "[1,2]" },
@@ -157,8 +161,8 @@ public class CompactNordPoolDayPriceTests
{
var prices = new List<CompactNordPoolDayPrice>
{
new() { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 },
new() { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 }
new CompactNordPoolDayPrice { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 },
new CompactNordPoolDayPrice { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 }
};
var json = JsonSerializer.Serialize(prices);
@@ -198,8 +202,8 @@ public class CompactNordPoolDayPriceTests
{
var prices = new List<NordPoolDayPrice>
{
new() { Start = TestStart, End = TestEnd, Price = 12.50 },
new() { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 }
new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = 12.50 },
new NordPoolDayPrice { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 }
};
var result = prices.ToCompact();
@@ -240,8 +244,11 @@ public class CompactNordPoolDayPriceTests
result.Should().HaveCount(96);
result.Should().BeInAscendingOrder(p => p.Start);
result[0].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart).ToUnixTimeSeconds());
result[95].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval))
.ToUnixTimeSeconds());
result[95]
.Start.Should()
.Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval))
.ToUnixTimeSeconds());
}
[Fact]
@@ -262,7 +269,7 @@ public class CompactNordPoolDayPriceTests
{
var prices = new List<NordPoolDayPrice>
{
new() { Start = null, End = null, Price = null }
new NordPoolDayPrice { Start = null, End = null, Price = null }
};
var result = prices.ToCompact();
@@ -280,6 +287,7 @@ public class CompactNordPoolDayPriceTests
var prices = NordPoolTestData.CreateIntervals(MaxExpectedPriceEntries, i => 4.93 + i * 0.22);
var compactPrices = prices.ToCompact();
var attributePayload = new
{
prices = compactPrices,
@@ -287,10 +295,12 @@ public class CompactNordPoolDayPriceTests
friendly_name = "NordPool today and tomorrow prices",
last_updated = DateTime.UtcNow.ToString("O")
};
var json = JsonSerializer.Serialize(attributePayload);
var byteCount = Encoding.UTF8.GetByteCount(json);
byteCount.Should().BeLessThan(haAttributeByteLimitBytes,
$"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
byteCount.Should()
.BeLessThan(haAttributeByteLimitBytes,
$"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
}
}
@@ -1,3 +1,5 @@
#region
using System.Text;
using System.Text.Json;
using FluentAssertions;
@@ -8,6 +10,8 @@ using NordPool.Models;
using NordPoolManager;
using NordPoolManager.Models;
#endregion
namespace NordPool.Manager.Tests;
public class NordPoolEntityServiceTests
@@ -99,7 +103,7 @@ public class NordPoolEntityServiceTests
{
// Arrange
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
// Act
await _sut.CreateEntitiesAsync("EUR/kWh");
@@ -113,14 +117,16 @@ public class NordPoolEntityServiceTests
{
// Arrange
var callCount = 0;
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
.Returns(() =>
{
callCount++;
return callCount == 2
? throw new InvalidOperationException("Entity creation failed")
: Task.CompletedTask;
});
.Returns(() =>
{
callCount++;
return callCount == 2
? throw new InvalidOperationException("Entity creation failed")
: Task.CompletedTask;
});
// Act
await _sut.CreateEntitiesAsync("EUR/kWh");
@@ -134,7 +140,7 @@ public class NordPoolEntityServiceTests
{
// Arrange
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
// Act
await _sut.CreateEntitiesAsync(null);
@@ -152,7 +158,7 @@ public class NordPoolEntityServiceTests
{
// Arrange
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
// Act
await _sut.CleanupEntitiesAsync();
@@ -172,7 +178,7 @@ public class NordPoolEntityServiceTests
{
// Arrange
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Remove failed"));
.ThrowsAsync(new InvalidOperationException("Remove failed"));
// Act
var act = () => _sut.CleanupEntitiesAsync();
@@ -190,7 +196,7 @@ public class NordPoolEntityServiceTests
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
// Act
await _sut.SetEntityStateSafe("sensor.test", "42");
@@ -204,7 +210,7 @@ public class NordPoolEntityServiceTests
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("State update failed"));
.ThrowsAsync(new InvalidOperationException("State update failed"));
// Act
var act = () => _sut.SetEntityStateSafe("sensor.test", "42");
@@ -222,8 +228,9 @@ public class NordPoolEntityServiceTests
{
// Arrange
var attributes = new { unit_of_measurement = "EUR/kWh" };
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
// Act
await _sut.SetEntityAttributesSafe("sensor.test", attributes);
@@ -237,8 +244,9 @@ public class NordPoolEntityServiceTests
{
// 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"));
.ThrowsAsync(new InvalidOperationException("Attributes update failed"));
// Act
var act = () => _sut.SetEntityAttributesSafe("sensor.test", attributes);
@@ -256,20 +264,23 @@ public class NordPoolEntityServiceTests
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
.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_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);
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);
}
@@ -279,28 +290,35 @@ public class NordPoolEntityServiceTests
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
// Act
await _sut.ResetEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny<object>()),
Times.Once);
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()),
Times.Once);
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()),
Times.Once);
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
Times.Once);
Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
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);
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);
Times.Once);
}
[Fact]
@@ -308,12 +326,14 @@ public class NordPoolEntityServiceTests
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState("sensor.nordpool_current_price", It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("State update failed"));
.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);
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);
.Returns(Task.CompletedTask);
// Act
var act = () => _sut.ResetEntitiesAsync();
@@ -327,17 +347,19 @@ public class NordPoolEntityServiceTests
{
// Arrange - 7 entities get state and attributes
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
.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));
Times.Exactly(7));
}
#endregion
@@ -356,14 +378,16 @@ public class NordPoolEntityServiceTests
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 } }
},
TodayNordPoolPrice = todayPrice ??
new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
},
TomorrowNordPoolPrice = tomorrowPrice ??
new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
},
CheapestIntervals = [],
ConfiguredHours = 2.0,
ConfiguredIntervalCount = 4,
@@ -382,24 +406,28 @@ public class NordPoolEntityServiceTests
var context = CreateDefaultContext();
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny<string>()),
Times.Once);
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);
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);
Times.Once);
}
[Fact]
@@ -409,22 +437,26 @@ public class NordPoolEntityServiceTests
var context = CreateDefaultContext();
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()),
Times.Once);
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()),
Times.Once);
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
Times.Once);
Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
}
[Fact]
@@ -432,13 +464,14 @@ public class NordPoolEntityServiceTests
{
// Arrange
var context = CreateDefaultContext(
todayPrice: new NordPoolPrice { Prices = null },
tomorrowPrice: new NordPoolPrice { Prices = null });
todayPrice: new NordPoolPrice { Prices = null },
tomorrowPrice: new NordPoolPrice { Prices = null });
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
// Act
await _sut.UpdateEntitiesAsync(context);
@@ -446,12 +479,12 @@ public class NordPoolEntityServiceTests
// 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);
}
_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_WithMergedPriceScenarios_ShouldPublishSortedFilteredPrices()
@@ -519,16 +552,19 @@ public class NordPoolEntityServiceTests
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.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);
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);
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext() with
{
@@ -566,21 +602,23 @@ public class NordPoolEntityServiceTests
}
]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
.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);
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is<object>(o =>
o.GetType().GetProperty("prices")!.GetValue(o) is List<CompactNordPoolDayPrice>)),
Times.Once);
}
[Fact]
@@ -592,35 +630,42 @@ public class NordPoolEntityServiceTests
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 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();
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);
.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);
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);
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 });
todayPrice: new NordPoolPrice { Prices = todayPrices },
tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices });
// Act
await _sut.UpdateEntitiesAsync(context);
@@ -629,8 +674,10 @@ public class NordPoolEntityServiceTests
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");
byteCount.Should()
.BeLessThan(haAttributeByteLimitBytes,
$"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
}
[Theory]
@@ -640,15 +687,16 @@ public class NordPoolEntityServiceTests
[InlineData(1234.5, "1234.50")]
[InlineData(17.916, "17.92")]
public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price,
string expected)
string expected)
{
// Arrange
var context = CreateDefaultContext(price);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
// Act
await _sut.UpdateEntitiesAsync(context);
@@ -662,14 +710,17 @@ public class NordPoolEntityServiceTests
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
.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);
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext() with
{
@@ -700,15 +751,18 @@ public class NordPoolEntityServiceTests
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
.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);
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
It.IsAny<object>()))
.Returns(Task.CompletedTask);
var first = new CheapestIntervalResult
{
@@ -717,6 +771,7 @@ public class NordPoolEntityServiceTests
Price = 4.93,
Rank = 1
};
var second = new CheapestIntervalResult
{
Start = new DateTime(2026, 3, 31, 23, 0, 0, DateTimeKind.Utc),
@@ -746,8 +801,10 @@ public class NordPoolEntityServiceTests
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should()
.HaveCount(2);
.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"));
@@ -763,15 +820,18 @@ public class NordPoolEntityServiceTests
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
.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);
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext() with { CheapestIntervals = null };
@@ -794,18 +854,22 @@ public class NordPoolEntityServiceTests
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.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);
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);
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 =
@@ -815,6 +879,7 @@ public class NordPoolEntityServiceTests
new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
]
};
var tomorrowPrice = new NordPoolPrice
{
Prices =
@@ -823,6 +888,7 @@ public class NordPoolEntityServiceTests
{ Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 }
]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
// Act
@@ -843,42 +909,49 @@ public class NordPoolEntityServiceTests
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
.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 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 });
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);
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
@@ -895,6 +968,7 @@ public class NordPoolEntityServiceTests
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;
}
+50 -34
View File
@@ -1,3 +1,5 @@
#region
using System.Reactive.Concurrency;
using BoilerMonitor.Models;
using FluentAssertions;
@@ -11,6 +13,8 @@ using NordPoolManager;
using NordPoolManager.Interface;
using NordPoolManager.Models;
#endregion
namespace NordPool.Manager.Tests;
public class NordPoolInitTests
@@ -39,14 +43,18 @@ public class NordPoolInitTests
_services = new Services(_haContextMock.Object);
_priceServiceMock
.Setup(p => p.FetchPricesAsync(It.IsAny<Func<DateOnly, Task<NordPoolPrice>>>()))
.Returns(Task.CompletedTask);
.Setup(p => p.FetchPricesAsync(It.IsAny<Func<DateOnly, Task<NordPoolPrice>>>()))
.Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.CreateEntitiesAsync(It.IsAny<string>())).Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.ResetEntitiesAsync()).Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>()))
.Returns(Task.CompletedTask);
.Returns(Task.CompletedTask);
_priceServiceMock.Setup(p => p.GetCurrentPrice()).Returns(0.0);
_priceServiceMock.Setup(p => p.ShouldFetchNewPrices(It.IsAny<DateOnly>())).Returns(false);
_priceServiceMock.SetupGet(p => p.DayQuartersIndex).Returns(0);
@@ -54,36 +62,39 @@ public class NordPoolInitTests
_priceServiceMock.SetupGet(p => p.TomorrowNordPoolPrice).Returns((NordPoolPrice?)null);
_priceServiceMock.SetupGet(p => p.CurrentPrice).Returns(0.0);
_priceServiceMock.SetupGet(p => p.LastUpdatedDate).Returns((DateTime?)null);
_cheapestIntervalsFinderMock
.Setup(c => c.IsCurrentIntervalCheap(It.IsAny<IReadOnlyList<CheapestIntervalResult>>(),
It.IsAny<DateTime>()))
.Returns(false);
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()).Returns(new BoilerConfig
{
IntervalCount = 4,
PriceCap = double.MaxValue,
Deadline = DateTime.Today.AddDays(1),
SkipPriceCap = false
});
.Setup(c => c.IsCurrentIntervalCheap(It.IsAny<IReadOnlyList<CheapestIntervalResult>>(),
It.IsAny<DateTime>()))
.Returns(false);
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration())
.Returns(new BoilerConfig
{
IntervalCount = 4,
PriceCap = double.MaxValue,
Deadline = DateTime.Today.AddDays(1),
SkipPriceCap = false
});
}
private NordPoolInit CreateSut(NordPoolOptions? nordPoolOptions = null)
{
var options = Options.Create(
nordPoolOptions ?? new NordPoolOptions { CleanupEntitiesOnStartup = false });
nordPoolOptions ?? new NordPoolOptions { CleanupEntitiesOnStartup = false });
return new NordPoolInit(
_entities,
_services,
_haContextMock.Object,
_loggerMock.Object,
_priceServiceMock.Object,
_entityServiceMock.Object,
_schedulerMock.Object,
_cheapestIntervalsFinderMock.Object,
_boilerConfigProviderMock.Object,
options,
TimeProvider.System);
_entities,
_services,
_haContextMock.Object,
_loggerMock.Object,
_priceServiceMock.Object,
_entityServiceMock.Object,
_schedulerMock.Object,
_cheapestIntervalsFinderMock.Object,
_boilerConfigProviderMock.Object,
options,
TimeProvider.System);
}
[Fact]
@@ -107,29 +118,34 @@ public class NordPoolInitTests
// The constructor also starts the same init flow in the background, so calls may happen more than once.
_entityServiceMock.Verify(
es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()),
cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never());
es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()),
cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never());
_entityServiceMock.Verify(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()),
Times.AtLeastOnce);
Times.AtLeastOnce);
_entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce);
_entityServiceMock.Verify(
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()),
Times.AtLeastOnce);
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()),
Times.AtLeastOnce);
}
[Fact]
public async Task InitializeAsync_WhenCreatingEntitiesFails_ShouldRethrow()
{
var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = false });
_entityServiceMock
.Setup(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException("create failed"));
.Setup(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException("create failed"));
var act = sut.InitializeAsync;
await act.Should().ThrowAsync<InvalidOperationException>().WithMessage("create failed");
_entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.Never);
_entityServiceMock.Verify(
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()), Times.Never);
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()), Times.Never);
}
}
@@ -1,4 +1,6 @@
using System.Globalization;
#region
using System.Globalization;
using System.Text.Json;
using AutoMapper;
using FluentAssertions;
@@ -8,6 +10,8 @@ using NordPool.Models;
using NordPool.Models.Dtos;
using NordPoolManager;
#endregion
namespace NordPool.Manager.Tests;
public class NordPoolPriceServiceTests
@@ -110,12 +114,15 @@ public class NordPoolPriceServiceTests
{
// Arrange & Act — iterate over a full UTC day; CET conversion produces 96 unique quarter indices
var indices = new HashSet<int>();
for (var hour = 0; hour < 24; hour++)
for (var minute = 0; minute < 60; minute += 15)
{
var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc);
var index = NordPoolPriceService.GetTimeQuarterIndex(date);
indices.Add(index);
for (var minute = 0; minute < 60; minute += 15)
{
var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc);
var index = NordPoolPriceService.GetTimeQuarterIndex(date);
indices.Add(index);
}
}
// Assert
@@ -127,8 +134,12 @@ public class NordPoolPriceServiceTests
[Theory]
[InlineData(2026, 1, 15, 8, 0, 36)] // CET winter (UTC+1): UTC 08:00 = CET 09:00 -> index 36
[InlineData(2026, 7, 15, 8, 0, 40)] // CEST summer (UTC+2): UTC 08:00 = CEST 10:00 -> index 40
public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year, int month, int day, int hour,
int minute, int expectedIndex)
public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year,
int month,
int day,
int hour,
int minute,
int expectedIndex)
{
// Arrange
var testDate = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Utc);
@@ -245,7 +256,7 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new()
new NordPoolDayPrice
{
Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture),
End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0
@@ -254,7 +265,7 @@ public class NordPoolPriceServiceTests
};
_mapperMock.Setup(m => m.Map<NordPoolPriceResultDto, NordPoolPrice>(It.IsAny<NordPoolPriceResultDto>()))
.Returns(expectedPrice);
.Returns(expectedPrice);
// Act
var result = _sut.ParseNordPoolResult(jsonElement);
@@ -285,7 +296,7 @@ public class NordPoolPriceServiceTests
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonString);
_mapperMock.Setup(m => m.Map<NordPoolPriceResultDto, NordPoolPrice>(It.IsAny<NordPoolPriceResultDto>()))
.Returns((NordPoolPrice)null!);
.Returns((NordPoolPrice)null!);
// Act
var result = _sut.ParseNordPoolResult(jsonElement);
@@ -301,7 +312,7 @@ public class NordPoolPriceServiceTests
var jsonElement = JsonSerializer.Deserialize<JsonElement>("{}");
_mapperMock.Setup(m => m.Map<NordPoolPriceResultDto, NordPoolPrice>(It.IsAny<NordPoolPriceResultDto>()))
.Returns(new NordPoolPrice());
.Returns(new NordPoolPrice());
// Act
var result = _sut.ParseNordPoolResult(jsonElement);
@@ -322,9 +333,9 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 },
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 },
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
}
};
@@ -347,9 +358,9 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null },
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null },
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
}
};
@@ -388,7 +399,7 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = startTime, End = endTime, Price = 81.0 }
new NordPoolDayPrice { Start = startTime, End = endTime, Price = 81.0 }
}
};
@@ -424,8 +435,8 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = null },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = null },
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }
}
};
@@ -445,7 +456,7 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }
}
};
@@ -469,12 +480,14 @@ public class NordPoolPriceServiceTests
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice
{
Start = now.AddMinutes(i * 15),
End = now.AddMinutes((i + 1) * 15),
Price = 5.0 + i * 0.22
});
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
@@ -532,8 +545,11 @@ public class NordPoolPriceServiceTests
var expectedIndex = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice { Price = 4.0 + i * 0.23 });
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.DayQuartersIndex = expectedIndex;
@@ -552,8 +568,11 @@ public class NordPoolPriceServiceTests
{
// Arrange
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice { Price = null });
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.CurrentPrice = 17.91;
@@ -572,8 +591,11 @@ public class NordPoolPriceServiceTests
{
// Arrange
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice { Price = 5.0 + i * 0.22 });
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.DayQuartersIndex = -1;
@@ -595,9 +617,10 @@ public class NordPoolPriceServiceTests
{
// Arrange — negative and zero spot prices are valid NordPool scenarios
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = NordPoolTestData.CreateIntervals(
NordPoolConsts.MaxDailyIntervals,
i => i == index ? expectedPrice : 10.0);
NordPoolConsts.MaxDailyIntervals,
i => i == index ? expectedPrice : 10.0);
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.CurrentPrice = 17.91;
@@ -616,9 +639,10 @@ public class NordPoolPriceServiceTests
{
// Arrange — fewer prices than the current quarter index (e.g. partial day payload)
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = Enumerable.Range(0, index)
.Select(i => new NordPoolDayPrice { Price = 10.0 + i })
.ToList();
.Select(i => new NordPoolDayPrice { Price = 10.0 + i })
.ToList();
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.CurrentPrice = 17.91;
@@ -637,9 +661,10 @@ public class NordPoolPriceServiceTests
{
// Arrange
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
.Select(_ => new NordPoolDayPrice { Price = 99.0 })
.ToList();
.Select(_ => new NordPoolDayPrice { Price = 99.0 })
.ToList();
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.DayQuartersIndex = index;
@@ -658,9 +683,10 @@ public class NordPoolPriceServiceTests
{
// Arrange
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
.Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 })
.ToList();
.Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 })
.ToList();
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.CurrentPrice = 17.91;
@@ -687,6 +713,7 @@ public class NordPoolPriceServiceTests
Task<NordPoolPrice> Fetch(DateOnly date)
{
requestedDates.Add(date);
return Task.FromResult(CreatePrices(1.5));
}
@@ -718,10 +745,11 @@ public class NordPoolPriceServiceTests
// Act
await _sut.FetchPricesAsync(_ =>
{
delegateCalled = true;
return Task.FromResult(CreatePrices(3.0));
});
{
delegateCalled = true;
return Task.FromResult(CreatePrices(3.0));
});
// Assert
delegateCalled.Should().BeFalse();
@@ -761,7 +789,7 @@ public class NordPoolPriceServiceTests
("today prices are empty", today, new NordPoolPrice { Prices = [] }, CreatePrices(18.71), true),
("today and tomorrow prices present", today, CreatePrices(12.50), CreatePrices(18.71), false),
("price values are null but entries exist", today, CreatePrices((double?)null),
CreatePrices((double?)null), false),
CreatePrices((double?)null), false),
("all price payloads are null", today, null, null, true)
];
@@ -786,10 +814,12 @@ public class NordPoolPriceServiceTests
// Arrange — tomorrow's prices are not published before 13:00, so cached data is acceptable until then
var today = DateOnly.FromDateTime(DateTime.Now);
_sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = null };
// Act
@@ -805,10 +835,12 @@ public class NordPoolPriceServiceTests
// Arrange
var today = DateOnly.FromDateTime(DateTime.Now);
_sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() };
// Act
@@ -828,13 +860,14 @@ public class NordPoolPriceServiceTests
// Arrange
var tomorrow = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
};
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = tomorrow;
_sut.DayQuartersIndex = 48;
var today = new DateOnly(2026, 4, 1);
@@ -855,7 +888,7 @@ public class NordPoolPriceServiceTests
[Fact]
public void RollOverPrices_WithoutUsableTomorrowPrices_ShouldResetTodayToEmptyPrice()
{
NordPoolPrice?[] unusablePrices = [null, new() { Prices = null }, new() { Prices = [] }];
NordPoolPrice?[] unusablePrices = [null, new NordPoolPrice { Prices = null }, new NordPoolPrice { Prices = [] }];
foreach (var tomorrow in unusablePrices)
{
@@ -900,11 +933,12 @@ public class NordPoolPriceServiceTests
// Arrange
var previousToday = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
};
var tomorrow = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
};
_sut.TodayNordPoolPrice = previousToday;
+14 -10
View File
@@ -1,5 +1,9 @@
#region
using NordPool.Models;
#endregion
namespace NordPool.Manager.Tests;
/// <summary>
@@ -8,7 +12,7 @@ namespace NordPool.Manager.Tests;
/// </summary>
internal static class NordPoolTestData
{
public static readonly DateTime DayStart = new(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
public static readonly DateTime DayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Builds a contiguous set of 15-minute intervals starting at <paramref name="dayStart" />.
@@ -23,12 +27,12 @@ internal static class NordPoolTestData
return
[
.. Enumerable.Range(0, count)
.Select(i => new NordPoolDayPrice
{
Start = start.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = start.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = priceFactory(i)
})
.Select(i => new NordPoolDayPrice
{
Start = start.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = start.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = priceFactory(i)
})
];
}
@@ -41,8 +45,8 @@ internal static class NordPoolTestData
var start = dayStart ?? DayStart;
return CreateIntervals(
NordPoolConsts.MaxDailyIntervals,
i => Math.Round(15.0 * Math.Sin(i / 6.0) + i % 8 - 2.0, 2),
start);
NordPoolConsts.MaxDailyIntervals,
i => Math.Round(15.0 * Math.Sin(i / 6.0) + i % 8 - 2.0, 2),
start);
}
}