Apply code formatting cleanup across monitor projects

- Reindent appsettings.json and the MSBuild project files
- Collapse single-statement guard blocks and tidy using and member order
- Normalize XML doc indentation and file endings
- Reorder BatteryMonitor test-data helpers and move the exclusion tests into
  their own region
- Carry the same formatting through the boiler config, control, entity and
  test files
This commit is contained in:
2026-11-30 11:52:06 +02:00
parent cf8c9434c8
commit 24729ee267
165 changed files with 2513 additions and 2470 deletions
@@ -8,16 +8,25 @@ namespace NordPool.Manager.Tests;
public class CheapestIntervalsFinderTests
{
private const int Hour = 3_600;
private const int Quarter = 15 * 60;
private static readonly DateTime DayStart = NordPoolTestData.DayStart;
private static readonly DateTime DeadlineEndOfDay = DayStart.AddDays(1);
private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock = new();
private CheapestIntervalsFinder CreateSut() => new(_loggerMock.Object);
private CheapestIntervalsFinder CreateSut()
{
return new CheapestIntervalsFinder(_loggerMock.Object);
}
private static bool IsPrice(double actual, double expected) => Math.Abs(actual - expected) < 0.000_001;
private static bool IsPrice(double actual, double expected)
{
return Math.Abs(actual - expected) < 0.000_001;
}
private static NordPoolPrice CreatePricesForDay(DateTime dayStart, int intervalCount = NordPoolConsts.MaxDailyIntervals)
private static NordPoolPrice CreatePricesForDay(DateTime dayStart,
int intervalCount = NordPoolConsts.MaxDailyIntervals)
{
return new NordPoolPrice
{
@@ -44,9 +53,6 @@ public class CheapestIntervalsFinderTests
};
}
private const int Hour = 3_600;
private const int Quarter = 15 * 60;
#region FindCheapestIntervals
public static TheoryData<string, double[], int, double, double, int> FilteringCases => new()
@@ -314,12 +320,25 @@ public class CheapestIntervalsFinderTests
("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),
("boundary between adjacent intervals", 10 * Hour + Quarter, [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, [Interval(14 * Hour, 14 * Hour + Quarter, price: 4.93, rank: 2), Interval(10 * Hour, 10 * Hour + Quarter, price: 6.20, rank: 1)], true),
("outside all intervals", 12 * Hour,
[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),
("unsorted intervals", 14 * Hour + 5 * 60,
[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),
("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),
("in gap between intervals", 10 * Hour + 2 * Quarter,
[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),
("empty interval list", 12 * Hour, [], false)
];
@@ -357,4 +376,4 @@ public class CheapestIntervalsFinderTests
}
#endregion
}
}
@@ -1,3 +1,4 @@
using System.Text;
using System.Text.Json;
using FluentAssertions;
using NordPool.Models;
@@ -14,6 +15,18 @@ public class CompactNordPoolDayPriceTests
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()
{
{ "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}" }
};
[Fact]
public void FromDayPrice_ShouldConvertDateTimesToUnixEpochSeconds()
{
@@ -150,7 +163,9 @@ public class CompactNordPoolDayPriceTests
var json = JsonSerializer.Serialize(prices);
json.Should().Be($"[[{TestStartEpoch},{TestEndEpoch},12.5],[{TestEndEpoch},{TestEndEpoch + IntervalDurationSeconds},13.26]]");
json.Should()
.Be(
$"[[{TestStartEpoch},{TestEndEpoch},12.5],[{TestEndEpoch},{TestEndEpoch + IntervalDurationSeconds},13.26]]");
}
[Fact]
@@ -161,18 +176,6 @@ public class CompactNordPoolDayPriceTests
act.Should().Throw<ArgumentNullException>();
}
public static TheoryData<string, string> InvalidJsonPayloads => new()
{
{ "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}" }
};
[Theory]
[MemberData(nameof(InvalidJsonPayloads))]
public void JsonDeserialization_WithInvalidPayload_ShouldThrowJsonException(string scenario, string json)
@@ -237,7 +240,8 @@ 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]
@@ -284,9 +288,9 @@ public class CompactNordPoolDayPriceTests
last_updated = DateTime.UtcNow.ToString("O")
};
var json = JsonSerializer.Serialize(attributePayload);
var byteCount = System.Text.Encoding.UTF8.GetByteCount(json);
var byteCount = Encoding.UTF8.GetByteCount(json);
byteCount.Should().BeLessThan(haAttributeByteLimitBytes,
$"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
}
}
}
@@ -1,36 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<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.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<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="17.0.0" />
<PackageReference Include="FluentAssertions" Version="8.11.0" />
<PackageReference Include="Moq" Version="4.21.0" />
</ItemGroup>
<ItemGroup>
<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.12.0"/>
<PackageReference Include="xunit" Version="2.9.3"/>
<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="17.0.0"/>
<PackageReference Include="FluentAssertions" Version="8.11.0"/>
<PackageReference Include="Moq" Version="4.21.0"/>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj"/>
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj"/>
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj"/>
</ItemGroup>
</Project>
@@ -1,3 +1,5 @@
using System.Text;
using System.Text.Json;
using FluentAssertions;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
@@ -266,7 +268,8 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", ""), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("button.nordpool_fetch_prices", "unknown"), Times.Once);
}
@@ -284,13 +287,20 @@ public class NordPoolEntityServiceTests
await _sut.ResetEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny<object>()),
Times.Once);
}
[Fact]
@@ -299,7 +309,8 @@ public class NordPoolEntityServiceTests
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState("sensor.nordpool_current_price", It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("State update failed"));
_entityManagerMock.Setup(em => em.SetEntityState(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<string>()))
_entityManagerMock.Setup(em =>
em.SetEntityState(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
@@ -325,7 +336,8 @@ public class NordPoolEntityServiceTests
// 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));
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
Times.Exactly(7));
}
#endregion
@@ -378,12 +390,16 @@ public class NordPoolEntityServiceTests
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny<string>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "17.91"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "1"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "1"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices",
It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()),
Times.Once);
}
[Fact]
@@ -401,10 +417,14 @@ public class NordPoolEntityServiceTests
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
}
[Fact]
@@ -448,26 +468,46 @@ public class NordPoolEntityServiceTests
{
Prices =
[
new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
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 }]
Prices =
[
new NordPoolDayPrice
{ Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }
]
},
2
),
(
"only today",
new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 }] },
new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 17.91 }
]
},
new NordPoolPrice { Prices = [] },
1
),
(
"only tomorrow",
new NordPoolPrice { Prices = [] },
new NordPoolPrice { Prices = [new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }] },
new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice
{ Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 18.71 }
]
},
1
),
("empty lists", new NordPoolPrice { Prices = [] }, new NordPoolPrice { Prices = [] }, 0),
@@ -481,10 +521,13 @@ public class NordPoolEntityServiceTests
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>()))
_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>()))
_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
@@ -513,12 +556,15 @@ public class NordPoolEntityServiceTests
// Arrange
var todayPrice = new NordPoolPrice
{
Prices = [new NordPoolDayPrice
{
Start = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc),
End = new DateTime(2026, 3, 31, 10, 15, 0, DateTimeKind.Utc),
Price = 17.91
}]
Prices =
[
new NordPoolDayPrice
{
Start = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc),
End = new DateTime(2026, 3, 31, 10, 15, 0, DateTimeKind.Utc),
Price = 17.91
}
]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
@@ -563,10 +609,13 @@ public class NordPoolEntityServiceTests
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>()))
_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>()))
_entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext(
@@ -578,8 +627,8 @@ public class NordPoolEntityServiceTests
// Assert
capturedAttributes.Should().NotBeNull();
var json = System.Text.Json.JsonSerializer.Serialize(capturedAttributes);
var byteCount = System.Text.Encoding.UTF8.GetByteCount(json);
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");
}
@@ -590,10 +639,11 @@ public class NordPoolEntityServiceTests
[InlineData(-5.25, "-5.25")]
[InlineData(1234.5, "1234.50")]
[InlineData(17.916, "17.92")]
public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price, string expected)
public async Task UpdateEntitiesAsync_ShouldFormatCurrentPriceWithTwoDecimalsAndInvariantCulture(double price,
string expected)
{
// Arrange
var context = CreateDefaultContext(currentPrice: price);
var context = CreateDefaultContext(price);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
@@ -617,7 +667,8 @@ public class NordPoolEntityServiceTests
_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>()))
_entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext() with
@@ -654,7 +705,9 @@ public class NordPoolEntityServiceTests
_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>()))
_entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
It.IsAny<object>()))
.Returns(Task.CompletedTask);
var first = new CheapestIntervalResult
@@ -693,7 +746,8 @@ public class NordPoolEntityServiceTests
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should().HaveCount(2);
((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"));
@@ -714,7 +768,9 @@ public class NordPoolEntityServiceTests
_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>()))
_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 };
@@ -740,10 +796,13 @@ public class NordPoolEntityServiceTests
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>()))
_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>()))
_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);
@@ -751,7 +810,8 @@ public class NordPoolEntityServiceTests
{
Prices =
[
new NordPoolDayPrice { Start = dayStart.AddHours(2), End = dayStart.AddHours(2).AddMinutes(15), Price = 17.91 },
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 }
]
};
@@ -759,7 +819,8 @@ public class NordPoolEntityServiceTests
{
Prices =
[
new NordPoolDayPrice { Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 }
new NordPoolDayPrice
{ Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 }
]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
@@ -813,7 +874,8 @@ public class NordPoolEntityServiceTests
l => l.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((state, _) => state != null && state.ToString()!.Contains("exceeds expected maximum")),
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);
@@ -826,7 +888,7 @@ public class NordPoolEntityServiceTests
public static TheoryData<string, Func<NordPoolEntityService, Task>> CancelledOperations()
{
var data = new TheoryData<string, Func<NordPoolEntityService, Task>>();
var cancelled = new CancellationToken(canceled: true);
var cancelled = new CancellationToken(true);
var context = CreateDefaultContext();
data.Add("create entities", sut => sut.CreateEntitiesAsync("EUR/kWh", cancelled));
@@ -854,4 +916,4 @@ public class NordPoolEntityServiceTests
}
#endregion
}
}
+19 -12
View File
@@ -15,14 +15,14 @@ namespace NordPool.Manager.Tests;
public class NordPoolInitTests
{
private readonly Mock<INordPoolBoilerConfigProvider> _boilerConfigProviderMock;
private readonly Mock<ICheapestIntervalsFinder> _cheapestIntervalsFinderMock;
private readonly Entities _entities;
private readonly Mock<INordPoolEntityService> _entityServiceMock;
private readonly Mock<IHaContext> _haContextMock;
private readonly Mock<ILogger<NordPoolInit>> _loggerMock;
private readonly Mock<INordPoolPriceService> _priceServiceMock;
private readonly Mock<INordPoolEntityService> _entityServiceMock;
private readonly Mock<IScheduler> _schedulerMock;
private readonly Mock<ICheapestIntervalsFinder> _cheapestIntervalsFinderMock;
private readonly Mock<INordPoolBoilerConfigProvider> _boilerConfigProviderMock;
private readonly Mock<IHaContext> _haContextMock;
private readonly Entities _entities;
public NordPoolInitTests()
{
@@ -37,10 +37,12 @@ public class NordPoolInitTests
_entities = new Entities(_haContextMock.Object);
_priceServiceMock.Setup(p => p.FetchPricesAsync()).Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny<CancellationToken>())).Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny<CancellationToken>()))
.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);
_entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>()))
.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);
@@ -49,7 +51,8 @@ public class NordPoolInitTests
_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>()))
.Setup(c => c.IsCurrentIntervalCheap(It.IsAny<IReadOnlyList<CheapestIntervalResult>>(),
It.IsAny<DateTime>()))
.Returns(false);
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()).Returns(new BoilerConfig
{
@@ -101,9 +104,12 @@ public class NordPoolInitTests
_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.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);
_entityServiceMock.Verify(
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()),
Times.AtLeastOnce);
}
[Fact]
@@ -118,6 +124,7 @@ public class NordPoolInitTests
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);
_entityServiceMock.Verify(
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()), Times.Never);
}
}
}
@@ -30,14 +30,14 @@ public class NordPoolPriceServiceTests
#region GetTimeQuarterIndex
[Theory]
[InlineData(0, 0, 8)] // UTC 00:00 = CEST 02:00
[InlineData(1, 0, 12)] // UTC 01:00 = CEST 03:00
[InlineData(6, 0, 32)] // UTC 06:00 = CEST 08:00
[InlineData(12, 0, 56)] // UTC 12:00 = CEST 14:00
[InlineData(22, 0, 0)] // UTC 22:00 = CEST 00:00 (next day start)
[InlineData(22, 15, 1)] // UTC 22:15 = CEST 00:15
[InlineData(22, 30, 2)] // UTC 22:30 = CEST 00:30
[InlineData(22, 45, 3)] // UTC 22:45 = CEST 00:45
[InlineData(0, 0, 8)] // UTC 00:00 = CEST 02:00
[InlineData(1, 0, 12)] // UTC 01:00 = CEST 03:00
[InlineData(6, 0, 32)] // UTC 06:00 = CEST 08:00
[InlineData(12, 0, 56)] // UTC 12:00 = CEST 14:00
[InlineData(22, 0, 0)] // UTC 22:00 = CEST 00:00 (next day start)
[InlineData(22, 15, 1)] // UTC 22:15 = CEST 00:15
[InlineData(22, 30, 2)] // UTC 22:30 = CEST 00:30
[InlineData(22, 45, 3)] // UTC 22:45 = CEST 00:45
public void GetTimeQuarterIndex_ShouldReturnCorrectIndex(int hour, int minute, int expectedIndex)
{
// Arrange — 2026-03-31 is in CEST (UTC+2)
@@ -51,11 +51,11 @@ public class NordPoolPriceServiceTests
}
[Theory]
[InlineData(0, 15, 9)] // UTC 00:15 = CEST 02:15
[InlineData(1, 30, 14)] // UTC 01:30 = CEST 03:30
[InlineData(12, 0, 56)] // UTC 12:00 = CEST 14:00
[InlineData(22, 0, 0)] // UTC 22:00 = CEST 00:00
[InlineData(22, 59, 3)] // UTC 22:59 = CEST 00:59
[InlineData(0, 15, 9)] // UTC 00:15 = CEST 02:15
[InlineData(1, 30, 14)] // UTC 01:30 = CEST 03:30
[InlineData(12, 0, 56)] // UTC 12:00 = CEST 14:00
[InlineData(22, 0, 0)] // UTC 22:00 = CEST 00:00
[InlineData(22, 59, 3)] // UTC 22:59 = CEST 00:59
public void GetTimeQuarterIndex_ShouldHandleAllHoursCorrectly(int hour, int minute, int expectedIndex)
{
// Arrange — 2026-03-31 is in CEST (UTC+2)
@@ -115,13 +115,11 @@ 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)
{
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);
}
var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc);
var index = NordPoolPriceService.GetTimeQuarterIndex(date);
indices.Add(index);
}
// Assert
@@ -131,9 +129,10 @@ 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)
[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)
{
// Arrange
var testDate = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Utc);
@@ -233,7 +232,14 @@ public class NordPoolPriceServiceTests
// Arrange
var dto = new NordPoolPriceResultDto
{
Prices = [new NordPoolDayPriceDto { Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), Price = 100.0 }]
Prices =
[
new NordPoolDayPriceDto
{
Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"),
Price = 100.0
}
]
};
var jsonString = JsonSerializer.Serialize(dto);
@@ -243,7 +249,11 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture), End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0 }
new()
{
Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture),
End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0
}
}
};
@@ -265,7 +275,14 @@ public class NordPoolPriceServiceTests
// Arrange
var dto = new NordPoolPriceResultDto
{
Prices = [new NordPoolDayPriceDto { Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), Price = 100.0 }]
Prices =
[
new NordPoolDayPriceDto
{
Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"),
Price = 100.0
}
]
};
var jsonString = JsonSerializer.Serialize(dto);
@@ -456,14 +473,12 @@ 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 };
@@ -667,32 +682,37 @@ public class NordPoolPriceServiceTests
#region ShouldFetchNewPrices
private static NordPoolPrice CreatePrices(params double?[] values) => new()
private static NordPoolPrice CreatePrices(params double?[] values)
{
Prices = [.. values.Select(price => new NordPoolDayPrice { Price = price })]
};
return new NordPoolPrice
{
Prices = [.. values.Select(price => new NordPoolDayPrice { Price = price })]
};
}
/// <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). xUnit cannot serialize
/// <see cref="NordPoolPrice"/> rows, so the matrix runs inside a single test.
/// 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). xUnit cannot serialize
/// <see cref="NordPoolPrice" /> rows, so the matrix runs inside a single test.
/// </summary>
[Fact]
public void ShouldFetchNewPrices_ShouldMatchScenario()
{
var today = DateOnly.FromDateTime(DateTime.Now);
(string Scenario, DateOnly? LastFetchedDate, NordPoolPrice? TodayPrice, NordPoolPrice? TomorrowPrice, bool Expected)[] cases =
[
("no fetch date yet", null, CreatePrices(12.50), CreatePrices(18.71), true),
("last fetch was yesterday", today.AddDays(-1), CreatePrices(12.50), CreatePrices(18.71), true),
("last fetch date is in the future", today.AddDays(1), CreatePrices(12.50), CreatePrices(18.71), false),
("today prices are null", today, new NordPoolPrice { Prices = null }, CreatePrices(18.71), true),
("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),
("all price payloads are null", today, null, null, true)
];
(string Scenario, DateOnly? LastFetchedDate, NordPoolPrice? TodayPrice, NordPoolPrice? TomorrowPrice, bool
Expected)[] cases =
[
("no fetch date yet", null, CreatePrices(12.50), CreatePrices(18.71), true),
("last fetch was yesterday", today.AddDays(-1), CreatePrices(12.50), CreatePrices(18.71), true),
("last fetch date is in the future", today.AddDays(1), CreatePrices(12.50), CreatePrices(18.71), false),
("today prices are null", today, new NordPoolPrice { Prices = null }, CreatePrices(18.71), true),
("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),
("all price payloads are null", today, null, null, true)
];
foreach (var (scenario, lastFetchedDate, todayPrice, tomorrowPrice, expected) in cases)
{
@@ -779,7 +799,7 @@ public class NordPoolPriceServiceTests
}
/// <summary>
/// Rows are not serializable as theory data, so the three unusable payloads are exercised in one test.
/// Rows are not serializable as theory data, so the three unusable payloads are exercised in one test.
/// </summary>
[Fact]
public void RollOverPrices_WithoutUsableTomorrowPrices_ShouldResetTodayToEmptyPrice()
@@ -789,7 +809,7 @@ public class NordPoolPriceServiceTests
foreach (var tomorrow in unusablePrices)
{
// Arrange
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = [new() { Price = 12.50 }] };
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = [new NordPoolDayPrice { Price = 12.50 }] };
_sut.TomorrowNordPoolPrice = tomorrow;
_sut.DayQuartersIndex = 42;
var today = new DateOnly(2026, 4, 1);
@@ -849,4 +869,4 @@ public class NordPoolPriceServiceTests
}
#endregion
}
}
+6 -6
View File
@@ -3,15 +3,15 @@ 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.
/// 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);
/// <summary>
/// Builds a contiguous set of 15-minute intervals starting at <paramref name="dayStart"/>.
/// Builds a contiguous set of 15-minute intervals starting at <paramref name="dayStart" />.
/// </summary>
public static List<NordPoolDayPrice> CreateIntervals(
int count,
@@ -33,8 +33,8 @@ internal static class NordPoolTestData
}
/// <summary>
/// A full 96-interval day with a deterministic sawtooth price curve covering
/// negative, zero, cheap and expensive prices.
/// 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)
{
@@ -45,4 +45,4 @@ internal static class NordPoolTestData
i => Math.Round(15.0 * Math.Sin(i / 6.0) + i % 8 - 2.0, 2),
start);
}
}
}