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
@@ -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
}