5777e641f6
- 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
272 lines
11 KiB
C#
272 lines
11 KiB
C#
using System.Text.Json;
|
|
using BoilerMonitor.Models;
|
|
using BoilerMonitorManager.Models;
|
|
using Microsoft.Extensions.Time.Testing;
|
|
using Moq;
|
|
using NetDaemon.HassModel;
|
|
using NetDaemon.HassModel.Entities;
|
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
|
|
|
namespace BoilerMonitor.Manager.Tests;
|
|
|
|
/// <summary>
|
|
/// Shared, deterministic fixtures used by the BoilerMonitor tests: config/options builders,
|
|
/// entity-state sets, parse samples and a fixed clock. Keeping them here avoids copy-pasted
|
|
/// setup and makes every timestamp/DST assertion independent of the real clock.
|
|
/// </summary>
|
|
internal static class BoilerMonitorTestData
|
|
{
|
|
public const string PowerEntityId = "sensor.sonoff_1002230e32_power";
|
|
public const string SwitchEntityId = "switch.sonoff_1002230e32";
|
|
|
|
/// <summary>Fixed "now" (UTC) used by every time based test.</summary>
|
|
public static readonly DateTimeOffset BaseTime = new(2026, 3, 31, 12, 0, 0, TimeSpan.Zero);
|
|
|
|
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null) =>
|
|
new(utcNow ?? BaseTime);
|
|
|
|
public static BoilerMonitorConfig CreateConfig(
|
|
string? boilerPowerEntityId = PowerEntityId,
|
|
string? boilerSwitchEntityId = SwitchEntityId,
|
|
int? pollIntervalSeconds = DefaultPollIntervalSeconds,
|
|
double? heatingPowerThresholdWatts = DefaultHeatingPowerThresholdWatts) =>
|
|
new()
|
|
{
|
|
BoilerPowerEntityId = boilerPowerEntityId,
|
|
BoilerSwitchEntityId = boilerSwitchEntityId,
|
|
PollIntervalSeconds = pollIntervalSeconds,
|
|
HeatingPowerThresholdWatts = heatingPowerThresholdWatts
|
|
};
|
|
|
|
public static BoilerMonitorOptions CreateOptions(
|
|
bool enabled = true,
|
|
bool cleanupEntitiesOnStartup = true) =>
|
|
new()
|
|
{
|
|
Enabled = enabled,
|
|
CleanupEntitiesOnStartup = cleanupEntitiesOnStartup
|
|
};
|
|
|
|
public static PersistedBoilerState CreatePersistedState(
|
|
TimeSpan? accumulatedRunTime = null,
|
|
int sessionCount = 3,
|
|
string? skipPriceCapState = "ON",
|
|
string? budgetOverrideState = "OFF") =>
|
|
new()
|
|
{
|
|
AccumulatedRunTime = accumulatedRunTime ?? TimeSpan.FromHours(2),
|
|
SessionCount = sessionCount,
|
|
SkipPriceCapState = skipPriceCapState,
|
|
BudgetOverrideState = budgetOverrideState
|
|
};
|
|
|
|
public static BoilerMonitorUpdateContext CreateUpdateContext(
|
|
TimeSpan? todayRunTime = null,
|
|
TimeSpan? remainingTime = null,
|
|
double budgetPercentage = 50.0,
|
|
bool budgetExhausted = false,
|
|
int sessionCount = 1,
|
|
double budgetHours = 2.0,
|
|
bool waterReady = false,
|
|
string? boilerSwitchState = "on",
|
|
double? boilerPowerWatts = 0.0,
|
|
DateTimeOffset? cooldownSince = null,
|
|
bool isNowCheap = true) =>
|
|
new()
|
|
{
|
|
TodayRunTime = todayRunTime ?? TimeSpan.FromHours(1),
|
|
RemainingTime = remainingTime ?? TimeSpan.FromHours(1),
|
|
BudgetPercentage = budgetPercentage,
|
|
BudgetExhausted = budgetExhausted,
|
|
SessionCount = sessionCount,
|
|
BudgetHours = budgetHours,
|
|
IsCurrentlyHeating = false,
|
|
WaterReady = waterReady,
|
|
BoilerSwitchState = boilerSwitchState,
|
|
BoilerPowerWatts = boilerPowerWatts,
|
|
CooldownSince = cooldownSince,
|
|
IsNowCheap = isNowCheap,
|
|
NextCheapIntervalStart = null
|
|
};
|
|
|
|
/// <summary>
|
|
/// The four entity states <c>ReadPersistedState</c> reads, with valid defaults.
|
|
/// A null value means the entity does not exist in Home Assistant.
|
|
/// </summary>
|
|
public static Dictionary<string, string?> CreatePersistedEntityStates(
|
|
string? todayRuntime = "7200",
|
|
string? sessionCount = "3",
|
|
string? skipPriceCap = "OFF",
|
|
string? budgetOverride = "OFF") =>
|
|
new()
|
|
{
|
|
[TodayRuntimeEntityId] = todayRuntime,
|
|
[SessionCountEntityId] = sessionCount,
|
|
[SkipPriceCapEntityId] = skipPriceCap,
|
|
[BudgetOverrideEntityId] = budgetOverride
|
|
};
|
|
|
|
public static EntityState CreateEntityState(string state) => new() { State = state };
|
|
|
|
public static EntityState CreateEntityStateWithAttributes(IReadOnlyDictionary<string, object?> attributes) =>
|
|
new() { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) };
|
|
|
|
public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince) =>
|
|
CreateEntityStateWithAttributes(new Dictionary<string, object?> { ["cooldown_since"] = cooldownSince });
|
|
|
|
public static void SetupEntityStates(
|
|
this Mock<IHaContext> haContextMock,
|
|
IReadOnlyDictionary<string, string?> states)
|
|
{
|
|
foreach (var (entityId, state) in states)
|
|
{
|
|
var entityState = state is null ? null : CreateEntityState(state);
|
|
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
|
}
|
|
}
|
|
|
|
public static void SetupEntityState(
|
|
this Mock<IHaContext> haContextMock,
|
|
string entityId,
|
|
EntityState? entityState) =>
|
|
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
|
|
|
/// <summary>
|
|
/// Entity-state samples for the today-runtime sensor: valid values with the expected
|
|
/// <see cref="TimeSpan"/>, plus unavailable/negative/overflow values that must be rejected.
|
|
/// </summary>
|
|
public static IEnumerable<object?[]> RuntimeStateSamples()
|
|
{
|
|
yield return ["7200", TimeSpan.FromHours(2)];
|
|
yield return ["0", TimeSpan.Zero];
|
|
yield return ["134.66", TimeSpan.FromSeconds(134.66)];
|
|
yield return ["1E3", TimeSpan.FromSeconds(1000)];
|
|
yield return ["0.001", TimeSpan.FromSeconds(0.001)];
|
|
yield return [" 60 ", TimeSpan.FromSeconds(60)];
|
|
yield return ["86400", TimeSpan.FromDays(1)];
|
|
yield return ["1e9", TimeSpan.FromSeconds(1e9)];
|
|
|
|
yield return [(string?)null, (TimeSpan?)null];
|
|
yield return ["", (TimeSpan?)null];
|
|
yield return [" ", (TimeSpan?)null];
|
|
yield return ["\t", (TimeSpan?)null];
|
|
yield return ["unavailable", (TimeSpan?)null];
|
|
yield return ["unknown", (TimeSpan?)null];
|
|
yield return ["Unavailable", (TimeSpan?)null];
|
|
yield return ["not_a_number", (TimeSpan?)null];
|
|
yield return ["NaN", (TimeSpan?)null];
|
|
yield return ["Infinity", (TimeSpan?)null];
|
|
yield return ["1e308", (TimeSpan?)null];
|
|
yield return ["-1", (TimeSpan?)null];
|
|
yield return ["-0.001", (TimeSpan?)null];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Entity-state samples for the session-count sensor, including the int boundaries.
|
|
/// </summary>
|
|
public static IEnumerable<object?[]> SessionCountStateSamples()
|
|
{
|
|
yield return ["0", 0];
|
|
yield return ["3", 3];
|
|
yield return [" 2 ", 2];
|
|
yield return ["+4", 4];
|
|
yield return ["2147483647", int.MaxValue];
|
|
|
|
yield return [(string?)null, (int?)null];
|
|
yield return ["", (int?)null];
|
|
yield return [" ", (int?)null];
|
|
yield return ["\t", (int?)null];
|
|
yield return ["unavailable", (int?)null];
|
|
yield return ["unknown", (int?)null];
|
|
yield return ["abc", (int?)null];
|
|
yield return ["1.5", (int?)null];
|
|
yield return ["-1", (int?)null];
|
|
yield return ["2147483648", (int?)null];
|
|
yield return ["1e3", (int?)null];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Water-ready detection samples around the heating threshold, including negative,
|
|
/// zero, exact-boundary, huge and NaN readings.
|
|
/// </summary>
|
|
public static IEnumerable<object?[]> PowerReadingSamples()
|
|
{
|
|
yield return ["negative sensor glitch", -1_000.0, true];
|
|
yield return ["just below zero", -0.001, true];
|
|
yield return ["zero", 0.0, true];
|
|
yield return ["just below threshold", 4.999, true];
|
|
yield return ["exactly at threshold", 5.0, false];
|
|
yield return ["just above threshold", 5.001, false];
|
|
yield return ["actively heating", 2_150.0, false];
|
|
yield return ["maximum", double.MaxValue, false];
|
|
yield return ["not-a-number", double.NaN, true];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Elapsed-time sweep showing that the water-ready cooldown never expires on its own.
|
|
/// </summary>
|
|
public static IEnumerable<object?[]> GeneratedElapsedTimes()
|
|
{
|
|
foreach (var hours in new[] { 1, 2, 6, 12, 23, 24, 25, 48, 168 })
|
|
{
|
|
yield return [TimeSpan.FromHours(hours)];
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end
|
|
/// timestamps carrying non-zero offsets.
|
|
/// </summary>
|
|
public static IEnumerable<object?[]> CooldownRestoreSamples()
|
|
{
|
|
yield return ["30 minutes ago", BaseTime, BaseTime - TimeSpan.FromMinutes(30), true];
|
|
yield return ["5 hours ago", BaseTime, BaseTime - TimeSpan.FromHours(5), true];
|
|
yield return ["exactly at today's UTC midnight", BaseTime, TodayMidnight(), true];
|
|
yield return ["one tick after today's UTC midnight", BaseTime, TodayMidnight().AddTicks(1), true];
|
|
yield return ["one tick before today's UTC midnight", BaseTime, TodayMidnight().AddTicks(-1), false];
|
|
yield return ["one second before today's UTC midnight", BaseTime, TodayMidnight().AddSeconds(-1), false];
|
|
yield return ["yesterday same time", BaseTime, BaseTime.AddDays(-1), false];
|
|
yield return ["two days ago", BaseTime, BaseTime.AddDays(-2), false];
|
|
yield return ["future timestamp", BaseTime, BaseTime.AddHours(1), true];
|
|
yield return ["maximum timestamp", BaseTime, DateTimeOffset.MaxValue, true];
|
|
|
|
// Europe DST starts 2026-03-29 02:00 CET → 03:00 CEST.
|
|
// now = 03:30+02:00 = 01:30Z, so UTC midnight is 2026-03-29T00:00Z.
|
|
yield return
|
|
[
|
|
"DST spring-forward, same UTC day",
|
|
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
|
|
new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)),
|
|
true
|
|
];
|
|
yield return
|
|
[
|
|
"DST spring-forward, previous UTC day",
|
|
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
|
|
new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)),
|
|
false
|
|
];
|
|
|
|
// Europe DST ends 2026-10-25 03:00 CEST → 02:00 CET. The 02:30 wall-clock hour occurs twice.
|
|
// now = 03:30+01:00 = 02:30Z, timestamp 02:30+02:00 = 00:30Z is still "today" in UTC.
|
|
yield return
|
|
[
|
|
"DST fall-back, ambiguous local hour",
|
|
new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)),
|
|
new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)),
|
|
true
|
|
];
|
|
|
|
yield return
|
|
[
|
|
"crossing midnight between restore and now",
|
|
new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero),
|
|
new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero),
|
|
false
|
|
];
|
|
}
|
|
|
|
private static DateTimeOffset TodayMidnight() =>
|
|
new(BaseTime.Date, TimeSpan.Zero);
|
|
}
|