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; /// /// 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. /// internal static class BoilerMonitorTestData { public const string PowerEntityId = "sensor.sonoff_1002230e32_power"; public const string SwitchEntityId = "switch.sonoff_1002230e32"; /// Fixed "now" (UTC) used by every time based test. 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, bool isNowCheap = true) => 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, }; /// /// The four entity states ReadPersistedState reads, with valid defaults. /// A null value means the entity does not exist in Home Assistant. /// public static Dictionary 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 attributes) => new() { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) }; public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince) => CreateEntityStateWithAttributes(new Dictionary { ["cooldown_since"] = cooldownSince }); extension(Mock haContextMock) { public void SetupEntityStates(IReadOnlyDictionary 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); } /// /// Entity-state samples for the today-runtime sensor: valid values with the expected /// , plus unavailable/negative/overflow values that must be rejected. /// public static TheoryData RuntimeStateSamples() { var data = new TheoryData(); 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; } /// /// Entity-state samples for the session-count sensor, including the int boundaries. /// public static TheoryData SessionCountStateSamples() { var data = new TheoryData(); 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; } /// /// Water-ready detection samples around the heating threshold, including negative, /// zero, exact-boundary, huge and NaN readings. /// public static TheoryData PowerReadingSamples() { var data = new TheoryData(); 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; } /// /// Elapsed-time sweep showing that the water-ready cooldown never expires on its own. /// public static TheoryData GeneratedElapsedTimes() { var data = new TheoryData(); 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; } /// /// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end /// timestamps carrying non-zero offsets. /// public static TheoryData CooldownRestoreSamples() { var data = new TheoryData(); 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); }