Files
HomeAssistant/BoilerMonitor.Manager.Tests/BoilerMonitorTestData.cs
T
gitea_admin cf8c9434c8 Clear the residual Qodana findings
- Drop the leftover unused using, parameter and date-time attribute reader
- Merge the remaining enum guard into its pattern
- Make the NordPool price DTO init-only
- Replace the four non-serializable theory matrices with single tests that
  iterate the same rows, so xUnit can still report them
- Replace Array.Empty with collection expressions and drop unused locals,
  redundant default arguments and duplicated tuple names
- Throw from the unreachable shower default instead of an empty section
- Cover the configurable PowerMonitor option overrides in a test so the
  init setters have a caller
2026-11-29 21:49:21 +02:00

268 lines
11 KiB
C#

using System.Text.Json;
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 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) =>
new()
{
TodayRunTime = todayRunTime ?? TimeSpan.FromHours(1),
RemainingTime = remainingTime ?? TimeSpan.FromHours(1),
BudgetPercentage = budgetPercentage,
BudgetExhausted = budgetExhausted,
SessionCount = sessionCount,
BudgetHours = budgetHours,
WaterReady = waterReady,
BoilerSwitchState = boilerSwitchState,
BoilerPowerWatts = boilerPowerWatts,
CooldownSince = cooldownSince,
};
/// <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 });
extension(Mock<IHaContext> haContextMock)
{
public void SetupEntityStates(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 void SetupEntityState(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 TheoryData<string?, TimeSpan?> RuntimeStateSamples()
{
var data = new TheoryData<string?, TimeSpan?>();
data.Add("7200", TimeSpan.FromHours(2));
data.Add("0", TimeSpan.Zero);
data.Add("134.66", TimeSpan.FromSeconds(134.66));
data.Add("1E3", TimeSpan.FromSeconds(1000));
data.Add("0.001", TimeSpan.FromSeconds(0.001));
data.Add(" 60 ", TimeSpan.FromSeconds(60));
data.Add("86400", TimeSpan.FromDays(1));
data.Add("1e9", TimeSpan.FromSeconds(1e9));
data.Add(null, null);
data.Add("", null);
data.Add(" ", null);
data.Add("\t", null);
data.Add("unavailable", null);
data.Add("unknown", null);
data.Add("Unavailable", null);
data.Add("not_a_number", null);
data.Add("NaN", null);
data.Add("Infinity", null);
data.Add("1e308", null);
data.Add("-1", null);
data.Add("-0.001", null);
return data;
}
/// <summary>
/// Entity-state samples for the session-count sensor, including the int boundaries.
/// </summary>
public static TheoryData<string?, int?> SessionCountStateSamples()
{
var data = new TheoryData<string?, int?>();
data.Add("0", 0);
data.Add("3", 3);
data.Add(" 2 ", 2);
data.Add("+4", 4);
data.Add("2147483647", int.MaxValue);
data.Add(null, null);
data.Add("", null);
data.Add(" ", null);
data.Add("\t", null);
data.Add("unavailable", null);
data.Add("unknown", null);
data.Add("abc", null);
data.Add("1.5", null);
data.Add("-1", null);
data.Add("2147483648", null);
data.Add("1e3", null);
return data;
}
/// <summary>
/// Water-ready detection samples around the heating threshold, including negative,
/// zero, exact-boundary, huge and NaN readings.
/// </summary>
public static TheoryData<string, double, bool> PowerReadingSamples()
{
var data = new TheoryData<string, double, bool>();
data.Add("negative sensor glitch", -1_000.0, true);
data.Add("just below zero", -0.001, true);
data.Add("zero", 0.0, true);
data.Add("just below threshold", 4.999, true);
data.Add("exactly at threshold", 5.0, false);
data.Add("just above threshold", 5.001, false);
data.Add("actively heating", 2_150.0, false);
data.Add("maximum", double.MaxValue, false);
data.Add("not-a-number", double.NaN, true);
return data;
}
/// <summary>
/// Elapsed-time sweep showing that the water-ready cooldown never expires on its own.
/// </summary>
public static TheoryData<TimeSpan> GeneratedElapsedTimes()
{
var data = new TheoryData<TimeSpan>();
data.Add(TimeSpan.FromHours(1));
data.Add(TimeSpan.FromHours(2));
data.Add(TimeSpan.FromHours(6));
data.Add(TimeSpan.FromHours(12));
data.Add(TimeSpan.FromHours(23));
data.Add(TimeSpan.FromHours(24));
data.Add(TimeSpan.FromHours(25));
data.Add(TimeSpan.FromHours(48));
data.Add(TimeSpan.FromHours(168));
return data;
}
/// <summary>
/// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end
/// timestamps carrying non-zero offsets.
/// </summary>
public static TheoryData<string, DateTimeOffset, DateTimeOffset, bool> CooldownRestoreSamples()
{
var data = new TheoryData<string, DateTimeOffset, DateTimeOffset, bool>();
data.Add("30 minutes ago", BaseTime, BaseTime - TimeSpan.FromMinutes(30), true);
data.Add("5 hours ago", BaseTime, BaseTime - TimeSpan.FromHours(5), true);
data.Add("exactly at today's UTC midnight", BaseTime, TodayMidnight(), true);
data.Add("one tick after today's UTC midnight", BaseTime, TodayMidnight().AddTicks(1), true);
data.Add("one tick before today's UTC midnight", BaseTime, TodayMidnight().AddTicks(-1), false);
data.Add("one second before today's UTC midnight", BaseTime, TodayMidnight().AddSeconds(-1), false);
data.Add("yesterday same time", BaseTime, BaseTime.AddDays(-1), false);
data.Add("two days ago", BaseTime, BaseTime.AddDays(-2), false);
data.Add("future timestamp", BaseTime, BaseTime.AddHours(1), true);
data.Add("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.
data.Add(
"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
);
data.Add(
"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.
data.Add(
"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
);
data.Add(
"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
);
return data;
}
private static DateTimeOffset TodayMidnight() =>
new(BaseTime.Date, TimeSpan.Zero);
}