Add shared test data builders and Qodana configuration

- Extract per-monitor *TestData helper classes and rework tests to use them
- Add boiler run-time tracker abstraction (implementation pending)
- Drop unused NordPool init/update-result types and stale PLAN.md
- Add qodana.yaml with the inspection set to keep the analysis focused
This commit is contained in:
2026-11-29 21:30:13 +02:00
parent 1152462765
commit 5777e641f6
79 changed files with 7162 additions and 3196 deletions
@@ -8,65 +8,93 @@ namespace NordPool.Manager.Tests;
public class CheapestIntervalsFinderTests
{
private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock;
private static readonly DateTime DayStart = NordPoolTestData.DayStart;
private static readonly DateTime DeadlineEndOfDay = DayStart.AddDays(1);
public CheapestIntervalsFinderTests()
{
_loggerMock = new Mock<ILogger<CheapestIntervalsFinder>>();
}
private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock = new();
private CheapestIntervalsFinder CreateSut()
{
return new CheapestIntervalsFinder(_loggerMock.Object);
}
private CheapestIntervalsFinder CreateSut() => new(_loggerMock.Object);
private static NordPoolPrice CreatePricesForDay(DateTime dayStart, int intervalCount = 96)
private static NordPoolPrice CreatePricesForDay(DateTime dayStart, int intervalCount = NordPoolConsts.MaxDailyIntervals)
{
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < intervalCount; i++)
return new NordPoolPrice
{
var start = dayStart.AddMinutes(i * 15);
prices.Add(new NordPoolDayPrice
{
Start = start,
End = start.AddMinutes(15),
Price = 4.93 + i * 0.22
});
}
return new NordPoolPrice { Prices = prices };
Prices = NordPoolTestData.CreateIntervals(intervalCount, i => 4.93 + i * 0.22, dayStart)
};
}
private static NordPoolPrice CreatePricesWithValues(DateTime dayStart, params double[] priceValues)
{
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < priceValues.Length; i++)
return new NordPoolPrice
{
var start = dayStart.AddMinutes(i * 15);
prices.Add(new NordPoolDayPrice
{
Start = start,
End = start.AddMinutes(15),
Price = priceValues[i]
});
}
return new NordPoolPrice { Prices = prices };
Prices = NordPoolTestData.CreateIntervals(priceValues.Length, i => priceValues[i], dayStart)
};
}
private static CheapestIntervalResult Interval(int startSeconds, int endSeconds, double price = 5.0, int rank = 1)
{
return new CheapestIntervalResult
{
Start = DayStart.AddSeconds(startSeconds),
End = DayStart.AddSeconds(endSeconds),
Price = price,
Rank = rank
};
}
private const int Hour = 3_600;
private const int Quarter = 15 * 60;
#region FindCheapestIntervals
public static IEnumerable<object[]> FilteringCases =>
[
["deadline includes interval ending exactly at it", new[] { 4.93, 5.63, 6.20 }, 10, double.MaxValue, 1_800.0, 2],
["deadline excludes interval ending one second late", new[] { 4.93, 5.63, 6.20 }, 10, double.MaxValue, 1_799.0, 1],
["deadline before first interval", new[] { 4.93, 5.63, 6.20 }, 10, double.MaxValue, -1.0, 0],
["price cap is inclusive", new[] { 12.50, 12.51 }, 10, 12.50, 86_400.0, 1],
["zero price cap keeps non-positive prices", new[] { -1.50, 0.0, 0.01, 2.0 }, 10, 0.0, 86_400.0, 2],
["all prices above cap", new[] { 17.91, 24.92, 22.44 }, 4, 10.0, 86_400.0, 0],
["fewer available than requested", new[] { 6.20, 8.96 }, 10, double.MaxValue, 86_400.0, 2],
["zero intervals requested", new[] { 17.91, 6.20 }, 0, double.MaxValue, 86_400.0, 0],
["negative intervals requested", new[] { 17.91, 6.20 }, -1, double.MaxValue, 86_400.0, 0],
["deadline and price cap combined", new[] { 17.91, 6.20, 12.50, 4.93, 8.96, 2.50 }, 2, 10.0, 4_500.0, 2],
["all prices equal", new[] { 12.50, 12.50, 12.50, 12.50, 12.50 }, 3, double.MaxValue, 86_400.0, 3]
];
[Theory]
[MemberData(nameof(FilteringCases))]
public void FindCheapestIntervals_ShouldApplyFiltersAndReturnExpectedCount(
string scenario,
double[] priceValues,
int requestedIntervals,
double priceCap,
double deadlineSeconds,
int expectedCount)
{
// Arrange
var sut = CreateSut();
var prices = CreatePricesWithValues(DayStart, priceValues);
var deadline = DayStart.AddSeconds(deadlineSeconds);
// Act
var result = sut.FindCheapestIntervals(prices, requestedIntervals, priceCap, deadline);
// Assert
result.Should().HaveCount(expectedCount, $"scenario: {scenario}");
result.Should().OnlyContain(r => r.End <= deadline && r.Price <= priceCap);
result.Select(r => r.Rank).Should().OnlyHaveUniqueItems();
}
[Fact]
public void FindCheapestIntervals_WithValidPrices_ShouldReturnRequestedCount()
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesForDay(dayStart);
var deadline = dayStart.AddDays(1);
var prices = CreatePricesForDay(DayStart);
// Act
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline);
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay);
// Assert
result.Should().HaveCount(4);
@@ -77,12 +105,10 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92, 5.63, 13.26);
var deadline = dayStart.AddDays(1);
var prices = CreatePricesWithValues(DayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92, 5.63, 13.26);
// Act
var result = sut.FindCheapestIntervals(prices, 3, double.MaxValue, deadline);
var result = sut.FindCheapestIntervals(prices, 3, double.MaxValue, DeadlineEndOfDay);
// Assert
result.Should().HaveCount(3);
@@ -97,18 +123,14 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 8.96, 4.93, 13.26);
var deadline = dayStart.AddDays(1);
var prices = CreatePricesWithValues(DayStart, 17.91, 8.96, 4.93, 13.26);
// Act
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline);
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay);
// Assert
var cheapest = result.Single(r => r.Price == 4.93);
cheapest.Rank.Should().Be(1);
var secondCheapest = result.Single(r => r.Price == 8.96);
secondCheapest.Rank.Should().Be(2);
result.Single(r => r.Price == 4.93).Rank.Should().Be(1);
result.Single(r => r.Price == 8.96).Rank.Should().Be(2);
}
[Fact]
@@ -116,83 +138,28 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96);
var deadline = dayStart.AddDays(1);
var prices = CreatePricesWithValues(DayStart, 17.91, 6.20, 12.50, 4.93, 8.96);
// Act
var result = sut.FindCheapestIntervals(prices, 3, double.MaxValue, deadline);
var result = sut.FindCheapestIntervals(prices, 3, double.MaxValue, DeadlineEndOfDay);
// Assert
result.Should().BeInAscendingOrder(r => r.Start);
}
[Fact]
public void FindCheapestIntervals_WithDeadline_ShouldExcludeIntervalsEndingAfterDeadline()
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 2.50, 1.80, 3.20);
var deadline = dayStart.AddMinutes(75); // 1h15m = covers intervals 0-4 (end of interval 4 = 75min)
// Act
var result = sut.FindCheapestIntervals(prices, 8, double.MaxValue, deadline);
// Assert
result.Should().HaveCount(5);
result.Should().OnlyContain(r => r.End <= deadline);
}
[Fact]
public void FindCheapestIntervals_WithPriceCap_ShouldExcludeExpensiveIntervals()
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92);
var deadline = dayStart.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 10, 10.0, deadline);
// Assert
result.Should().HaveCount(3);
result.Should().OnlyContain(r => r.Price <= 10.0);
}
[Fact]
public void FindCheapestIntervals_WithMaxPriceCap_ShouldIncludeAllIntervalsBeforeDeadline()
{
// Arrange: realistic ct/kWh samples — with double.MaxValue all six intervals qualify
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92);
var deadline = dayStart.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline);
// Assert: all 6 intervals are eligible, we take 4 cheapest by price
result.Should().HaveCount(4);
result.Select(r => r.Price).OrderBy(p => p).Should().ContainInOrder(4.93, 6.20, 8.96, 12.50);
}
[Fact]
public void FindCheapestIntervals_WithDeadlineAndPriceCap_ShouldApplyBothFilters()
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 2.50);
var deadline = dayStart.AddMinutes(75);
var prices = CreatePricesWithValues(DayStart, 17.91, 6.20, 12.50, 4.93, 8.96, 24.92);
// Act
var result = sut.FindCheapestIntervals(prices, 2, 10.0, deadline);
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay);
// Assert
result.Should().HaveCount(2);
result.Should().OnlyContain(r => r.End <= deadline && r.Price <= 10.0);
// Assert — all six intervals are eligible, the four cheapest are taken
result.Should().HaveCount(4);
result.Select(r => r.Price).OrderBy(p => p).Should().ContainInOrder(4.93, 6.20, 8.96, 12.50);
}
[Fact]
@@ -201,10 +168,9 @@ public class CheapestIntervalsFinderTests
// Arrange
var sut = CreateSut();
var prices = new NordPoolPrice { Prices = null };
var deadline = DateTime.Today.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline);
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay);
// Assert
result.Should().BeEmpty();
@@ -216,110 +182,67 @@ public class CheapestIntervalsFinderTests
// Arrange
var sut = CreateSut();
var prices = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() };
var deadline = DateTime.Today.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline);
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay);
// Assert
result.Should().BeEmpty();
}
[Fact]
public void FindCheapestIntervals_WithZeroIntervals_ShouldReturnEmpty()
public void FindCheapestIntervals_WithEqualPrices_ShouldPreferEarliestStart()
{
// Arrange
// Arrange — four equally priced intervals, only two are requested
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesForDay(dayStart);
var deadline = dayStart.AddDays(1);
var prices = CreatePricesWithValues(DayStart, 5.0, 5.0, 5.0, 5.0);
// Act
var result = sut.FindCheapestIntervals(prices, 0, double.MaxValue, deadline);
var result = sut.FindCheapestIntervals(prices, 2, double.MaxValue, DeadlineEndOfDay);
// Assert
result.Should().BeEmpty();
// Assert — tie-break is by Start ascending
result.Should().HaveCount(2);
result.Select(r => r.Start).Should().ContainInOrder(DayStart, DayStart.AddMinutes(15));
result.Select(r => r.Rank).Should().ContainInOrder(1, 2);
}
[Fact]
public void FindCheapestIntervals_WithNegativeIntervals_ShouldReturnEmpty()
public void FindCheapestIntervals_WithNegativePrices_ShouldRankCheapestFirst()
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesForDay(dayStart);
var deadline = dayStart.AddDays(1);
var prices = CreatePricesWithValues(DayStart, -2.10, 0.50, -7.40, 3.30);
// Act
var result = sut.FindCheapestIntervals(prices, -1, double.MaxValue, deadline);
var result = sut.FindCheapestIntervals(prices, 2, double.MaxValue, DeadlineEndOfDay);
// Assert
result.Should().BeEmpty();
// Assert — results are chronological, ranks still follow price order
result.Should().HaveCount(2);
result.Select(r => r.Price).Should().ContainInOrder(-2.10, -7.40);
result.Single(r => r.Price == -7.40).Rank.Should().Be(1);
result.Single(r => r.Price == -2.10).Rank.Should().Be(2);
}
[Fact]
public void FindCheapestIntervals_WhenFewerAvailableThanRequested_ShouldReturnAllAvailable()
public void FindCheapestIntervals_WithDuplicateIntervals_ShouldKeepBoth()
{
// Arrange
// Arrange — duplicate payload entries are not deduplicated
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 6.20, 8.96);
var deadline = dayStart.AddDays(1);
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 }
}
};
// Act
var result = sut.FindCheapestIntervals(prices, 10, double.MaxValue, deadline);
var result = sut.FindCheapestIntervals(prices, 2, double.MaxValue, DeadlineEndOfDay);
// Assert
result.Should().HaveCount(2);
}
[Fact]
public void FindCheapestIntervals_AllPricesAboveCap_ShouldReturnEmpty()
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 17.91, 24.92, 22.44);
var deadline = dayStart.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 4, 10.0, deadline);
// Assert
result.Should().BeEmpty();
}
[Fact]
public void FindCheapestIntervals_AllIntervalsAfterDeadline_ShouldReturnEmpty()
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 12, 0, 0);
var prices = CreatePricesWithValues(dayStart, 4.93, 5.63, 6.20);
var deadline = new DateTime(2026, 3, 31, 10, 0, 0);
// Act
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline);
// Assert
result.Should().BeEmpty();
}
[Fact]
public void FindCheapestIntervals_AllSamePrice_ShouldReturnRequestedCount()
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 12.50, 12.50, 12.50, 12.50, 12.50);
var deadline = dayStart.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 3, double.MaxValue, deadline);
// Assert
result.Should().HaveCount(3);
result.Should().OnlyContain(r => r.Price == 12.50);
result.Select(r => r.Rank).Should().BeEquivalentTo([1, 2]);
}
[Fact]
@@ -327,117 +250,110 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0);
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() { 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 }
}
};
var deadline = dayStart.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 10, double.MaxValue, deadline);
var result = sut.FindCheapestIntervals(prices, 10, double.MaxValue, DeadlineEndOfDay);
// Assert
result.Should().HaveCount(2);
}
[Fact]
public void FindCheapestIntervals_WithGeneratedFullDay_ShouldSelectExactlyTheCheapestIntervals()
{
// Arrange — deterministic 96-interval dataset with negative, cheap and expensive prices
var sut = CreateSut();
var prices = new NordPoolPrice { Prices = NordPoolTestData.CreateGeneratedDay() };
const int requestedIntervals = 8;
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();
// Act
var result = sut.FindCheapestIntervals(prices, requestedIntervals, priceCap, DeadlineEndOfDay);
// Assert
expected.Should().HaveCount(requestedIntervals);
result.Should().HaveCount(requestedIntervals);
result.Select(r => r.Start).Should().ContainInOrder(expected.Select(p => p.Start!.Value));
result.Should().BeInAscendingOrder(r => r.Start);
result.Select(r => r.Rank).Should().BeEquivalentTo(Enumerable.Range(1, requestedIntervals));
result.Should().OnlyContain(r => r.Price <= priceCap);
}
#endregion
#region IsCurrentIntervalCheap
[Fact]
public void IsCurrentIntervalCheap_WhenWithinInterval_ShouldReturnTrue()
public static IEnumerable<object[]> CurrentIntervalCases =>
[
["inside interval", 10 * Hour + 7 * 60, new[] { Interval(10 * Hour, 10 * Hour + Quarter) }, true],
["exactly at start", 10 * Hour, new[] { Interval(10 * Hour, 10 * Hour + Quarter) }, true],
["exactly at end", 10 * Hour + Quarter, new[] { Interval(10 * Hour, 10 * Hour + Quarter) }, false],
["outside all intervals", 12 * Hour, new[] { Interval(10 * Hour, 10 * Hour + Quarter), Interval(14 * Hour, 14 * Hour + Quarter) }, false],
["boundary between adjacent intervals", 10 * Hour + Quarter, new[] { Interval(10 * Hour, 10 * Hour + Quarter, price: 8.96, rank: 1), Interval(10 * Hour + Quarter, 10 * Hour + 2 * Quarter, price: 6.20, rank: 2) }, true],
["unsorted intervals", 14 * Hour + 5 * 60, new[] { Interval(14 * Hour, 14 * Hour + Quarter, price: 4.93, rank: 2), Interval(10 * Hour, 10 * Hour + Quarter, price: 6.20, rank: 1) }, true],
["before first interval", 10 * Hour - 1, new[] { Interval(10 * Hour, 10 * Hour + Quarter) }, false],
["in gap between intervals", 10 * Hour + 2 * Quarter, new[] { Interval(10 * Hour, 10 * Hour + Quarter), Interval(11 * Hour, 11 * Hour + Quarter) }, false],
["middle of three consecutive intervals", 10 * Hour + Quarter + 5 * 60, new[] { 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, Array.Empty<CheapestIntervalResult>(), false]
];
[Theory]
[MemberData(nameof(CurrentIntervalCases))]
public void IsCurrentIntervalCheap_ShouldMatchIntervalBounds(
string scenario,
int nowSeconds,
CheapestIntervalResult[] intervals,
bool expected)
{
// Arrange
var sut = CreateSut();
var now = new DateTime(2026, 3, 31, 10, 7, 0);
var intervals = new List<CheapestIntervalResult>
{
new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 }
};
var now = DayStart.AddSeconds(nowSeconds);
// Act
var result = sut.IsCurrentIntervalCheap(intervals, now);
// Assert
result.Should().BeTrue();
result.Should().Be(expected, $"scenario: {scenario}");
}
[Fact]
public void IsCurrentIntervalCheap_WhenExactlyAtStart_ShouldReturnTrue()
public void IsCurrentIntervalCheap_WithGeneratedDay_ShouldBeTrueOnlyForSelectedQuarters()
{
// Arrange
// Arrange — pick the four cheapest intervals of a generated day and probe every quarter
var sut = CreateSut();
var now = new DateTime(2026, 3, 31, 10, 0, 0);
var intervals = new List<CheapestIntervalResult>
var prices = new NordPoolPrice { Prices = NordPoolTestData.CreateGeneratedDay() };
var cheapest = sut.FindCheapestIntervals(prices, 4, double.MaxValue, DeadlineEndOfDay);
for (var quarter = 0; quarter < NordPoolConsts.MaxDailyIntervals; quarter++)
{
new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 }
};
var now = DayStart.AddMinutes(quarter * NordPoolConsts.MinutesPerInterval);
var expected = cheapest.Any(i => now >= i.Start && now < i.End);
// Act
var result = sut.IsCurrentIntervalCheap(intervals, now);
// Act
var result = sut.IsCurrentIntervalCheap(cheapest, now);
// Assert
result.Should().BeTrue();
}
[Fact]
public void IsCurrentIntervalCheap_WhenExactlyAtEnd_ShouldReturnFalse()
{
// Arrange
var sut = CreateSut();
var now = new DateTime(2026, 3, 31, 10, 15, 0);
var intervals = new List<CheapestIntervalResult>
{
new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 }
};
// Act
var result = sut.IsCurrentIntervalCheap(intervals, now);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsCurrentIntervalCheap_WhenOutsideAllIntervals_ShouldReturnFalse()
{
// Arrange
var sut = CreateSut();
var now = new DateTime(2026, 3, 31, 12, 0, 0);
var intervals = new List<CheapestIntervalResult>
{
new() { Start = new DateTime(2026, 3, 31, 10, 0, 0), End = new DateTime(2026, 3, 31, 10, 15, 0), Price = 8.96, Rank = 1 },
new() { Start = new DateTime(2026, 3, 31, 14, 0, 0), End = new DateTime(2026, 3, 31, 14, 15, 0), Price = 6.20, Rank = 2 }
};
// Act
var result = sut.IsCurrentIntervalCheap(intervals, now);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsCurrentIntervalCheap_WithEmptyList_ShouldReturnFalse()
{
// Arrange
var sut = CreateSut();
var now = DateTime.UtcNow;
var intervals = new List<CheapestIntervalResult>();
// Act
var result = sut.IsCurrentIntervalCheap(intervals, now);
// Assert
result.Should().BeFalse();
// Assert
result.Should().Be(expected, $"quarter {quarter} at {now:O}");
}
}
#endregion
@@ -115,14 +115,20 @@ public class CompactNordPoolDayPriceTests
json.Should().Be($"[{TestStartEpoch},{TestEndEpoch},null]");
}
[Fact]
public void JsonDeserialization_ShouldRoundTrip()
[Theory]
[InlineData(17.91)]
[InlineData(-12.34)]
[InlineData(0.0)]
[InlineData(0.001)]
[InlineData(17.9159)]
[InlineData(null)]
public void JsonDeserialization_ShouldRoundTripPrice(double? price)
{
var original = new CompactNordPoolDayPrice
{
Start = TestStartEpoch,
End = TestEndEpoch,
Price = 17.91
Price = price
};
var json = JsonSerializer.Serialize(original);
@@ -155,28 +161,33 @@ public class CompactNordPoolDayPriceTests
act.Should().Throw<ArgumentNullException>();
}
[Fact]
public void JsonDeserialization_EmptyArray_ShouldThrowJsonException()
{
var act = () => JsonSerializer.Deserialize<CompactNordPoolDayPrice>("[]");
public static IEnumerable<object[]> InvalidJsonPayloads =>
[
["empty array", "[]"],
["too few elements", "[1,2]"],
["extra elements", "[1,2,3,4]"],
["missing end of array", "[1,2,3"],
["non-numeric start", "[\"abc\",2,3]"],
["non-numeric end", "[1,\"abc\",3]"],
["non-numeric price", "[1,2,\"abc\"]"],
["object instead of array", "{\"start\":1}"]
];
act.Should().Throw<JsonException>();
[Theory]
[MemberData(nameof(InvalidJsonPayloads))]
public void JsonDeserialization_WithInvalidPayload_ShouldThrowJsonException(string scenario, string json)
{
var act = () => JsonSerializer.Deserialize<CompactNordPoolDayPrice>(json);
act.Should().Throw<JsonException>($"scenario: {scenario}");
}
[Fact]
public void JsonDeserialization_TooFewElements_ShouldThrowJsonException()
public void JsonSerialization_EmptyList_ShouldProduceEmptyArray()
{
var act = () => JsonSerializer.Deserialize<CompactNordPoolDayPrice>("[1,2]");
var json = JsonSerializer.Serialize(new List<CompactNordPoolDayPrice>());
act.Should().Throw<JsonException>();
}
[Fact]
public void JsonDeserialization_InvalidTokenType_ShouldThrowJsonException()
{
var act = () => JsonSerializer.Deserialize<CompactNordPoolDayPrice>("[\"abc\",2,3]");
act.Should().Throw<JsonException>();
json.Should().Be("[]");
}
[Fact]
@@ -216,23 +227,53 @@ public class CompactNordPoolDayPriceTests
result.Should().BeEmpty();
}
[Fact]
public void ToCompact_WithGeneratedDay_ShouldPreserveOrderAndCount()
{
var prices = NordPoolTestData.CreateIntervals(96, i => 4.93 + i * 0.22);
var result = prices.ToCompact();
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());
}
[Fact]
public void JsonSerialization_WithGeneratedDay_ShouldRoundTripAllEntries()
{
var compact = NordPoolTestData.CreateGeneratedDay().ToCompact();
var json = JsonSerializer.Serialize(compact);
var roundTripped = JsonSerializer.Deserialize<List<CompactNordPoolDayPrice>>(json);
roundTripped.Should().NotBeNull();
roundTripped!.Should().HaveCount(compact.Count);
roundTripped.Should().BeEquivalentTo(compact);
}
[Fact]
public void ToCompact_ShouldPreserveNullPriceAndNullTimestamps()
{
var prices = new List<NordPoolDayPrice>
{
new() { Start = null, End = null, Price = null }
};
var result = prices.ToCompact();
result.Should().ContainSingle();
result[0].Start.Should().Be(0L);
result[0].End.Should().Be(0L);
result[0].Price.Should().BeNull();
}
[Fact]
public void SerializedSize_WithMaxEntries_ShouldBeUnderHaAttributeLimit()
{
const int haAttributeByteLimitBytes = 16_384;
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < MaxExpectedPriceEntries; i++)
{
var start = dayStart.AddMinutes(i * MinutesPerInterval);
prices.Add(new NordPoolDayPrice
{
Start = start,
End = start.AddMinutes(MinutesPerInterval),
Price = 4.93 + i * 0.22
});
}
var prices = NordPoolTestData.CreateIntervals(MaxExpectedPriceEntries, i => 4.93 + i * 0.22);
var compactPrices = prices.ToCompact();
var attributePayload = new
@@ -8,19 +8,19 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="8.0.0">
<PackageReference Include="coverlet.collector" Version="10.1.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="AutoMapper" Version="17.0.0" />
<PackageReference Include="FluentAssertions" Version="8.11.0" />
<PackageReference Include="Moq" Version="4.21.0" />
</ItemGroup>
<ItemGroup>
@@ -130,6 +130,20 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(7));
}
[Fact]
public async Task CreateEntitiesAsync_WithNullUnitOfMeasurement_ShouldStillCreateAllEntities()
{
// Arrange
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
.Returns(Task.CompletedTask);
// Act
await _sut.CreateEntitiesAsync(null);
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(7));
}
#endregion
#region CleanupEntitiesAsync
@@ -421,106 +435,85 @@ public class NordPoolEntityServiceTests
Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WithTodayAndTomorrowPrices_ShouldUpdateCombinedSensor()
public static IEnumerable<object?[]> MergedPriceScenarios()
{
// 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);
yield return
[
"today and tomorrow with null-start entry filtered",
new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
new NordPoolDayPrice { Start = null, End = todayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
]
},
new NordPoolPrice
{
Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }]
},
2
];
// Act
await _sut.UpdateEntitiesAsync(context);
yield return
[
"only today",
new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 }] },
new NordPoolPrice { Prices = [] },
1
];
// 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);
yield return
[
"only tomorrow",
new NordPoolPrice { Prices = [] },
new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] },
1
];
// 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);
yield return ["empty lists", new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] }, 0];
yield return ["null lists", new NordPoolPrice { Prices = null }, new NordPoolPrice { Prices = null }, 0];
yield return ["null price objects", (NordPoolPrice?)null, (NordPoolPrice?)null, 0];
}
[Fact]
public async Task UpdateEntitiesAsync_WithOnlyTodayPrices_ShouldUpdateCombinedSensor()
[Theory]
[MemberData(nameof(MergedPriceScenarios))]
public async Task UpdateEntitiesAsync_WithMergedPriceScenarios_ShouldPublishSortedFilteredPrices(
string scenario,
NordPoolPrice? todayPrice,
NordPoolPrice? tomorrowPrice,
int expectedMergedCount)
{
// 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 = [] });
object? capturedAttributes = 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>()))
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext() with
{
TodayNordPoolPrice = todayPrice,
TomorrowNordPoolPrice = tomorrowPrice
};
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_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);
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
var prices = (List<CompactNordPoolDayPrice>)type.GetProperty("prices")!.GetValue(attributes)!;
prices.Should().HaveCount(expectedMergedCount, $"scenario: {scenario}");
prices.Select(p => p.Start).Should().BeInAscendingOrder();
type.GetProperty("prices_count")!.GetValue(attributes).Should().Be(expectedMergedCount);
}
[Fact]
@@ -600,5 +593,272 @@ public class NordPoolEntityServiceTests
$"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
}
[Theory]
[InlineData(17.91, "17.91")]
[InlineData(0.0, "0.00")]
[InlineData(-5.25, "-5.25")]
[InlineData(1234.5, "1234.50")]
[InlineData(17.916, "17.92")]
public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price, string expected)
{
// Arrange
var context = CreateDefaultContext(currentPrice: price);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", expected), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_CurrentPriceAttributes_ShouldReflectContext()
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext() with
{
UnitOfMeasurement = "EUR/MWh",
DayQuartersIndex = 42,
LastApiUpdateDate = null,
UsingCachedData = true
};
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
type.GetProperty("unit_of_measurement")!.GetValue(attributes).Should().Be("EUR/MWh");
type.GetProperty("device_class")!.GetValue(attributes).Should().Be("monetary");
type.GetProperty("state_class")!.GetValue(attributes).Should().Be("measurement");
type.GetProperty("last_api_fetch")!.GetValue(attributes).Should().BeNull();
type.GetProperty("using_cached_data")!.GetValue(attributes).Should().Be(true);
type.GetProperty("current_quarter_index")!.GetValue(attributes).Should().Be(42);
type.GetProperty("last_updated")!.GetValue(attributes).Should().NotBeNull();
}
[Fact]
public async Task UpdateEntitiesAsync_CheapestIntervalsAttributes_ShouldSummarizeSchedule()
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var first = new CheapestIntervalResult
{
Start = new DateTime(2026, 3, 31, 22, 0, 0, DateTimeKind.Utc),
End = new DateTime(2026, 3, 31, 22, 15, 0, DateTimeKind.Utc),
Price = 4.93,
Rank = 1
};
var second = new CheapestIntervalResult
{
Start = new DateTime(2026, 3, 31, 23, 0, 0, DateTimeKind.Utc),
End = new DateTime(2026, 3, 31, 23, 15, 0, DateTimeKind.Utc),
Price = 5.63,
Rank = 2
};
var context = CreateDefaultContext() with
{
CheapestIntervals = [first, second],
ConfiguredHours = 0.5,
ConfiguredIntervalCount = 2,
ConfiguredPriceCap = 25.0,
SkipPriceCap = true,
ConfiguredReadyBy = "06:30",
IsNowCheap = true,
NextCheapIntervalStart = first.Start
};
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "2"), Times.Once);
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should().HaveCount(2);
type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(30);
type.GetProperty("is_now_cheap")!.GetValue(attributes).Should().Be(true);
type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().Be(first.Start.ToString("O"));
type.GetProperty("skip_price_cap")!.GetValue(attributes).Should().Be(true);
type.GetProperty("configured_hours")!.GetValue(attributes).Should().Be(0.5);
type.GetProperty("configured_interval_count")!.GetValue(attributes).Should().Be(2);
type.GetProperty("configured_price_cap")!.GetValue(attributes).Should().Be(25.0);
type.GetProperty("configured_ready_by")!.GetValue(attributes).Should().Be("06:30");
}
[Fact]
public async Task UpdateEntitiesAsync_WhenCheapestIntervalsAreNull_ShouldPublishEmptyIntervals()
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext() with { CheapestIntervals = null };
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once);
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should().BeEmpty();
type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(0);
type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().BeNull();
}
[Fact]
public async Task UpdateEntitiesAsync_MergedPrices_ShouldDropEntriesWithoutStartAndSortByStart()
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var todayPrice = new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = dayStart.AddHours(2), End = dayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
]
};
var tomorrowPrice = new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 }
]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
var prices = (List<CompactNordPoolDayPrice>)type.GetProperty("prices")!.GetValue(attributes)!;
prices.Should().HaveCount(2);
prices.Select(p => p.Start).Should().BeInAscendingOrder();
type.GetProperty("prices_count")!.GetValue(attributes).Should().Be(2);
}
[Fact]
public async Task UpdateEntitiesAsync_WhenMergedPricesExceedExpectedMaximum_ShouldLogWarning()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
var todayPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice
{
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 10.0
}).ToList();
var tomorrowPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice
{
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 10.0
}).ToList();
var context = CreateDefaultContext(
todayPrice: new NordPoolPrice { Prices = todayPrices },
tomorrowPrice: new NordPoolPrice { Prices = tomorrowPrices });
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_loggerMock.Verify(
l => l.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((state, _) => state != null && state.ToString()!.Contains("exceeds expected maximum")),
It.IsAny<Exception?>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
Times.Once);
}
#endregion
#region Cancellation
public static IEnumerable<object[]> CancelledOperations()
{
var cancelled = new CancellationToken(canceled: true);
var context = CreateDefaultContext();
yield return ["create entities", (Func<NordPoolEntityService, Task>)(sut => sut.CreateEntitiesAsync("EUR/kWh", cancelled))];
yield return ["reset entities", (Func<NordPoolEntityService, Task>)(sut => sut.ResetEntitiesAsync(cancelled))];
yield return ["update entities", (Func<NordPoolEntityService, Task>)(sut => sut.UpdateEntitiesAsync(context, cancelled))];
yield return ["cleanup entities", (Func<NordPoolEntityService, Task>)(sut => sut.CleanupEntitiesAsync(cancelled))];
}
[Theory]
[MemberData(nameof(CancelledOperations))]
public async Task Operation_WithCancelledToken_ShouldThrowAndNotWriteAnything(
string scenario,
Func<NordPoolEntityService, Task> operation)
{
// Act
var act = () => operation(_sut);
// Assert
await act.Should().ThrowAsync<OperationCanceledException>($"scenario: {scenario}");
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Never);
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Never);
}
#endregion
}
+21 -23
View File
@@ -41,7 +41,7 @@ public class NordPoolInitTests
_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);
_priceServiceMock.Setup(p => p.UpdateCurrentPrice()).Returns(0.0);
_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);
_priceServiceMock.SetupGet(p => p.TodayNordPoolPrice).Returns((NordPoolPrice?)null);
@@ -88,38 +88,36 @@ public class NordPoolInitTests
sut.Should().NotBeNull();
}
[Fact]
public async Task CleanupEntitiesAsync_ShouldDelegateToEntityService()
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task InitializeAsync_ShouldRespectCleanupOnStartupSetting(bool cleanupEntitiesOnStartup)
{
// Arrange
var sut = CreateSut();
_entityServiceMock.Setup(es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
// Act
await sut.CleanupEntitiesAsync();
// Assert
_entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task InitializeAsync_WhenCleanupEntitiesOnStartupIsTrue_ShouldCallEntityCleanup()
{
var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = true });
var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = cleanupEntitiesOnStartup });
await sut.InitializeAsync();
_entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce);
// 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());
_entityServiceMock.Verify(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()), 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);
}
[Fact]
public async Task InitializeAsync_WhenCleanupEntitiesOnStartupIsFalse_ShouldNotCallEntityCleanup()
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"));
await sut.InitializeAsync();
var act = () => sut.InitializeAsync();
_entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()), Times.Never);
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);
}
}
@@ -154,6 +154,14 @@ public class NordPoolPriceServiceTests
[InlineData(200.0, 24.2)]
[InlineData(0.0, 0.0)]
[InlineData(123.456, 14.94)]
[InlineData(1.0, 0.12)]
[InlineData(10.0, 1.21)]
[InlineData(250.0, 30.25)]
[InlineData(500.0, 60.5)]
[InlineData(1000.0, 121.0)]
[InlineData(-1000.0, -121.0)]
[InlineData(1234.5, 149.37)]
[InlineData(0.01, 0.0)]
public void PriceCorrection_ShouldCalculateCorrectPrice(double mwPrice, double expectedCentsPrice)
{
// Act
@@ -459,7 +467,8 @@ public class NordPoolPriceServiceTests
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
// Act
var result = _sut.UpdateCurrentPrice();
_sut.UpdateCurrentPrice();
var result = _sut.GetCurrentPrice();
// Assert
result.Should().BeGreaterThan(0);
@@ -469,7 +478,8 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenNordPoolPriceIsNull_ShouldReturnZero()
{
// Act
var result = _sut.UpdateCurrentPrice();
_sut.UpdateCurrentPrice();
var result = _sut.GetCurrentPrice();
// Assert
result.Should().Be(0);
@@ -482,7 +492,8 @@ public class NordPoolPriceServiceTests
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() };
// Act
var result = _sut.UpdateCurrentPrice();
_sut.UpdateCurrentPrice();
var result = _sut.GetCurrentPrice();
// Assert
result.Should().Be(0);
@@ -495,7 +506,8 @@ public class NordPoolPriceServiceTests
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = null };
// Act
var result = _sut.UpdateCurrentPrice();
_sut.UpdateCurrentPrice();
var result = _sut.GetCurrentPrice();
// Assert
result.Should().Be(0);
@@ -516,7 +528,8 @@ public class NordPoolPriceServiceTests
_sut.CurrentPrice = 17.91;
// Act
var result = _sut.UpdateCurrentPrice();
_sut.UpdateCurrentPrice();
var result = _sut.GetCurrentPrice();
// Assert
result.Should().Be(17.91);
@@ -535,7 +548,8 @@ public class NordPoolPriceServiceTests
_sut.DayQuartersIndex = -1;
// Act
var result = _sut.UpdateCurrentPrice();
_sut.UpdateCurrentPrice();
var result = _sut.GetCurrentPrice();
// Assert
result.Should().Be(17.91);
@@ -559,78 +573,164 @@ public class NordPoolPriceServiceTests
_sut.DayQuartersIndex.Should().BeGreaterThanOrEqualTo(0);
}
[Theory]
[InlineData(-3.25)]
[InlineData(0.0)]
[InlineData(0.01)]
[InlineData(123.45)]
[InlineData(999.99)]
public void UpdateCurrentPrice_WhenCurrentQuarterHasPrice_ShouldStoreThatPrice(double expectedPrice)
{
// 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);
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.CurrentPrice = 17.91;
_sut.DayQuartersIndex = -1;
// Act
_sut.UpdateCurrentPrice();
// Assert
_sut.CurrentPrice.Should().Be(expectedPrice);
_sut.DayQuartersIndex.Should().Be(index);
}
[Fact]
public void UpdateCurrentPrice_WhenCurrentIndexIsOutsidePricesRange_ShouldKeepPreviousPriceButAdvanceIndex()
{
// 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();
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.CurrentPrice = 17.91;
_sut.DayQuartersIndex = -1;
// Act
_sut.UpdateCurrentPrice();
// Assert
_sut.CurrentPrice.Should().Be(17.91);
_sut.DayQuartersIndex.Should().Be(index);
}
[Fact]
public void UpdateCurrentPrice_WhenQuarterIndexUnchangedButPricesChanged_ShouldKeepCachedPrice()
{
// Arrange
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
.Select(i => new NordPoolDayPrice { Price = 99.0 })
.ToList();
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.DayQuartersIndex = index;
_sut.CurrentPrice = 17.91;
// Act
_sut.UpdateCurrentPrice();
// Assert — same quarter means no recompute, cached value survives
_sut.CurrentPrice.Should().Be(17.91);
_sut.DayQuartersIndex.Should().Be(index);
}
[Fact]
public void UpdateCurrentPrice_WhenOnlyCurrentQuarterPriceIsNull_ShouldKeepPreviousPriceAndAdvanceIndex()
{
// 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();
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.CurrentPrice = 17.91;
_sut.DayQuartersIndex = (index + 1) % NordPoolConsts.MaxDailyIntervals;
// Act
_sut.UpdateCurrentPrice();
// Assert
_sut.CurrentPrice.Should().Be(17.91);
_sut.DayQuartersIndex.Should().Be(index);
}
#endregion
#region ShouldFetchNewPrices
[Fact]
public void ShouldFetchNewPrices_WhenNoLastFetchedDate_ShouldReturnTrue()
/// <summary>
/// Scenarios that do not depend on the time of day (tomorrow's prices are published after 13:00,
/// so the "tomorrow missing" cases are covered separately below).
/// </summary>
public static IEnumerable<object?[]> ShouldFetchScenarios()
{
var today = DateOnly.FromDateTime(DateTime.Now);
static NordPoolPrice Prices(params double?[] values) => new()
{
Prices = values.Select(price => new NordPoolDayPrice { Price = price }).ToList()
};
yield return ["no fetch date yet", (DateOnly?)null, Prices(12.50), Prices(18.71), true];
yield return ["last fetch was yesterday", today.AddDays(-1), Prices(12.50), Prices(18.71), true];
yield return ["last fetch date is in the future", today.AddDays(1), Prices(12.50), Prices(18.71), false];
yield return ["today prices are null", today, new NordPoolPrice { Prices = null }, Prices(18.71), true];
yield return ["today prices are empty", today, new NordPoolPrice { Prices = [] }, Prices(18.71), true];
yield return ["today and tomorrow prices present", today, Prices(12.50), Prices(18.71), false];
yield return ["price values are null but entries exist", today, Prices((double?)null), Prices((double?)null), false];
yield return ["all price payloads are null", today, (NordPoolPrice?)null, (NordPoolPrice?)null, true];
}
[Theory]
[MemberData(nameof(ShouldFetchScenarios))]
public void ShouldFetchNewPrices_ShouldMatchScenario(
string scenario,
DateOnly? lastFetchedDate,
NordPoolPrice? todayPrice,
NordPoolPrice? tomorrowPrice,
bool expected)
{
// Arrange
_sut.LastFetchedDate = lastFetchedDate;
_sut.TodayNordPoolPrice = todayPrice;
_sut.TomorrowNordPoolPrice = tomorrowPrice;
// Act
var result = _sut.ShouldFetchNewPrices(DateOnly.FromDateTime(DateTime.Now));
// Assert
result.Should().BeTrue();
result.Should().Be(expected, $"scenario: {scenario}");
}
[Fact]
public void ShouldFetchNewPrices_WhenLastFetchedDateIsYesterday_ShouldReturnTrue()
public void ShouldFetchNewPrices_WhenTomorrowPricesAreNull_ShouldDependOnHourOfDay()
{
// Arrange
// 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.AddDays(-1);
_sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = null };
// Act
var result = _sut.ShouldFetchNewPrices(today);
// Assert
result.Should().BeTrue();
result.Should().Be(DateTime.Now.Hour >= 13);
}
[Fact]
public void ShouldFetchNewPrices_WhenTodayPricesAreNull_ShouldReturnTrue()
{
// Arrange
var today = DateOnly.FromDateTime(DateTime.Now);
_sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = null };
_sut.TomorrowNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
// Act
var result = _sut.ShouldFetchNewPrices(today);
// Assert
result.Should().BeTrue();
}
[Fact]
public void ShouldFetchNewPrices_WhenTodayPricesAreEmpty_ShouldReturnTrue()
{
// Arrange
var today = DateOnly.FromDateTime(DateTime.Now);
_sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() };
_sut.TomorrowNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
// Act
var result = _sut.ShouldFetchNewPrices(today);
// Assert
result.Should().BeTrue();
}
[Fact]
public void ShouldFetchNewPrices_WhenAllPricesAvailable_ShouldReturnFalse()
public void ShouldFetchNewPrices_WhenTomorrowPricesAreEmpty_ShouldDependOnHourOfDay()
{
// Arrange
var today = DateOnly.FromDateTime(DateTime.Now);
@@ -639,30 +739,117 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = new NordPoolPrice
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() };
// Act
var result = _sut.ShouldFetchNewPrices(today);
// Assert
result.Should().Be(DateTime.Now.Hour >= 13);
}
#endregion
#region RollOverPrices
[Fact]
public void RollOverPrices_WithTomorrowPrices_ShouldPromoteTomorrowToToday()
{
// Arrange
var tomorrow = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
};
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = tomorrow;
_sut.DayQuartersIndex = 48;
var today = new DateOnly(2026, 4, 1);
// Act
var result = _sut.ShouldFetchNewPrices(today);
_sut.RollOverPrices(today);
// Assert
result.Should().BeFalse();
_sut.TodayNordPoolPrice.Should().BeSameAs(tomorrow);
_sut.TomorrowNordPoolPrice.Should().BeNull();
_sut.DayQuartersIndex.Should().Be(-1);
_sut.LastFetchedDate.Should().Be(today);
}
public static IEnumerable<object?[]> UnusableTomorrowPrices =>
[
[null],
[new NordPoolPrice { Prices = null }],
[new NordPoolPrice { Prices = [] }]
];
[Theory]
[MemberData(nameof(UnusableTomorrowPrices))]
public void RollOverPrices_WithoutUsableTomorrowPrices_ShouldResetTodayToEmptyPrice(NordPoolPrice? tomorrow)
{
// Arrange
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = tomorrow;
_sut.DayQuartersIndex = 42;
var today = new DateOnly(2026, 4, 1);
// Act
_sut.RollOverPrices(today);
// Assert — nothing usable to promote, so today becomes an empty payload
_sut.TodayNordPoolPrice.Should().NotBeNull();
_sut.TodayNordPoolPrice!.Prices.Should().BeNull();
_sut.TomorrowNordPoolPrice.Should().BeNull();
_sut.DayQuartersIndex.Should().Be(-1);
_sut.LastFetchedDate.Should().Be(today);
}
[Fact]
public void ShouldFetchNewPrices_WhenNordPoolPriceIsNull_ShouldReturnTrue()
public void RollOverPrices_WhenBothPricesAreNull_ShouldNotThrow()
{
// Arrange
var today = DateOnly.FromDateTime(DateTime.Now);
_sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = null;
_sut.TomorrowNordPoolPrice = null;
var today = new DateOnly(2026, 4, 1);
// Act
var result = _sut.ShouldFetchNewPrices(today);
var act = () => _sut.RollOverPrices(today);
// Assert
result.Should().BeTrue();
act.Should().NotThrow();
_sut.TodayNordPoolPrice.Should().NotBeNull();
_sut.TodayNordPoolPrice!.Prices.Should().BeNull();
}
[Fact]
public void RollOverPrices_ShouldDiscardPreviousTodayPrices()
{
// Arrange
var previousToday = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
var tomorrow = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
};
_sut.TodayNordPoolPrice = previousToday;
_sut.TomorrowNordPoolPrice = tomorrow;
// Act
_sut.RollOverPrices(new DateOnly(2026, 4, 1));
// Assert — the old today payload is replaced, not mutated
_sut.TodayNordPoolPrice.Should().BeSameAs(tomorrow);
previousToday.Prices.Should().HaveCount(1);
previousToday.Prices![0].Price.Should().Be(12.50);
}
#endregion
@@ -0,0 +1,48 @@
using NordPool.Models;
namespace NordPool.Manager.Tests;
/// <summary>
/// Shared, deterministic datasets used by the NordPool tests.
/// Keeping the generators here avoids copy-pasted price loops across test classes.
/// </summary>
internal static class NordPoolTestData
{
public static readonly DateTime DayStart = new(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
public static readonly DateTime TomorrowStart = DayStart.AddDays(1);
/// <summary>
/// Builds a contiguous set of 15-minute intervals starting at <paramref name="dayStart"/>.
/// </summary>
public static List<NordPoolDayPrice> CreateIntervals(
int count,
Func<int, double?> priceFactory,
DateTime? dayStart = null)
{
var start = dayStart ?? DayStart;
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)
})
.ToList();
}
/// <summary>
/// A full 96-interval day with a deterministic sawtooth price curve covering
/// negative, zero, cheap and expensive prices.
/// </summary>
public static List<NordPoolDayPrice> CreateGeneratedDay(DateTime? dayStart = null)
{
var start = dayStart ?? DayStart;
return CreateIntervals(
NordPoolConsts.MaxDailyIntervals,
i => Math.Round(15.0 * Math.Sin(i / 6.0) + (i % 8) - 2.0, 2),
start);
}
}