Files
HomeAssistant/LeakMonitor.Manager.Tests/LeakMonitorTestData.cs
T
gitea_admin 24729ee267 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
2026-11-30 11:52:06 +02:00

272 lines
8.9 KiB
C#

using System.Text.Json;
using LeakMonitor.Models;
using LeakMonitorManager.Models;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
namespace LeakMonitor.Manager.Tests;
/// <summary>
/// Shared, deterministic builders and datasets used by the LeakMonitor tests.
/// Keeping entity/state construction, notification payload capture and generated
/// input rows here means the test classes only describe the scenario under test.
/// </summary>
internal static class LeakMonitorTestData
{
public const string AquariumSensorId = "binary_sensor.aquarium_leak_sensor";
public const string BoilerSensorId = "binary_sensor.boiler_moisture";
public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId];
private static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
/// <summary>
/// Every casing of the "water detected" state, across both configured sensors.
/// </summary>
public static TheoryData<string, string?> WaterDetectedCases { get; } = new()
{
{ AquariumSensorId, LeakMonitorConsts.WaterDetectedState },
{ AquariumSensorId, "ON" },
{ AquariumSensorId, "On" },
{ AquariumSensorId, "oN" },
{ BoilerSensorId, LeakMonitorConsts.WaterDetectedState }
};
/// <summary>
/// Every casing of the "water cleared" state, across both configured sensors.
/// </summary>
public static TheoryData<string, string?> WaterClearedCases { get; } = new()
{
{ AquariumSensorId, LeakMonitorConsts.WaterClearedState },
{ AquariumSensorId, "OFF" },
{ AquariumSensorId, "Off" },
{ BoilerSensorId, "oFf" }
};
/// <summary>
/// States that must never send or dismiss a leak notification. Covers unavailable,
/// unknown, blank, null and near-miss strings (the comparison is exact apart from casing).
/// </summary>
public static TheoryData<string?> NonActionableStateCases { get; } =
[
"unavailable",
"UNAVAILABLE",
"unknown",
"UNKNOWN",
string.Empty,
" ",
"\t",
"open",
"idle",
"detected",
"ON ",
" off",
"1",
"true",
null
];
/// <summary>
/// Blank but non-null sensor ids. Production does not validate ids, so these are
/// subscribed and forwarded verbatim.
/// </summary>
public static TheoryData<string> BlankSensorIds { get; } =
[
string.Empty,
" ",
"\t"
];
/// <summary>
/// (sensor id, expected notification id) rows for the id sanitising rules:
/// dots become underscores, other characters and blanks are preserved.
/// </summary>
public static TheoryData<string, string> NotificationIdCases { get; } = new()
{
{ AquariumSensorId, "leak_monitor_binary_sensor_aquarium_leak_sensor" },
{ BoilerSensorId, "leak_monitor_binary_sensor_boiler_moisture" },
{ "sensor.a.b.c", "leak_monitor_sensor_a_b_c" },
{ "no_dots", "leak_monitor_no_dots" },
{ "binary_sensor.already_snake_case", "leak_monitor_binary_sensor_already_snake_case" },
{ "binary_sensor.dash-and-dot.", "leak_monitor_binary_sensor_dash-and-dot_" },
{ string.Empty, "leak_monitor_" },
{ " ", "leak_monitor_ " }
};
/// <summary>
/// (cooldown minutes, elapsed seconds before the second alert, expected notification count)
/// rows straddling the strict <c>elapsed &lt; cooldown</c> boundary, plus zero, negative
/// and int-max cooldowns.
/// </summary>
public static TheoryData<int, int, int> CooldownBoundaryCases { get; } = new()
{
{ 5, 0, 1 },
{ 5, 299, 1 },
{ 5, 300, 2 },
{ 5, 301, 2 },
{ 10, 599, 1 },
{ 10, 600, 2 },
{ 1, 59, 1 },
{ 1, 60, 2 },
{ 0, 0, 2 },
{ -5, 0, 2 },
{ int.MaxValue, 600, 1 }
};
/// <summary>
/// Repetition counts used to exercise duplicate suppression and zero-cooldown behaviour.
/// </summary>
public static TheoryData<int> RepeatedNotificationCounts { get; } =
[
2,
3,
5,
10
];
/// <summary>
/// A deterministic detection/recovery sequence. The repeated "on" transition is filtered
/// out downstream, so the expected totals are two alerts and two dismissals.
/// </summary>
public static (string? OldState, string? NewState)[] DetectionSequence { get; } =
[
("off", "on"),
("on", "on"),
("on", "off"),
("off", "unavailable"),
("unavailable", "on"),
("on", "off")
];
/// <summary>
/// Builds leak monitor options with production-compatible defaults.
/// Pass <c>[]</c> for no sensors; omit the argument for the shared sensor set.
/// </summary>
public static LeakMonitorOptions CreateOptions(
IEnumerable<string>? sensorEntityIds = null,
int notificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes,
bool enabled = true)
{
return new LeakMonitorOptions
{
Enabled = enabled,
SensorEntityIds = sensorEntityIds?.ToArray() ?? [.. DefaultSensorIds],
NotificationCooldownMinutes = notificationCooldownMinutes
};
}
/// <summary>
/// Builds an <see cref="EntityState" />, or <c>null</c> when the entity has no state at all.
/// </summary>
private static EntityState? CreateOptionalState(string? state)
{
return state is null ? null : new EntityState { State = state };
}
public static StateChange CreateStateChange(
IHaContext haContext,
string entityId,
string? oldState,
string? newState)
{
return new StateChange(new Entity(haContext, entityId), CreateOptionalState(oldState),
CreateOptionalState(newState));
}
public static IReadOnlyList<StateChange> CreateStateChangeSequence(
IHaContext haContext,
string entityId,
params (string? OldState, string? NewState)[] transitions)
{
return
[
.. transitions.Select(transition =>
CreateStateChange(haContext, entityId, transition.OldState, transition.NewState))
];
}
/// <summary>
/// Wires <see cref="IHaContext.CallService" /> on the mock and returns the captured calls
/// in invocation order.
/// </summary>
public static List<ServiceCall> CaptureServiceCalls(Mock<IHaContext> haContextMock)
{
var calls = new List<ServiceCall>();
haContextMock
.Setup(h => h.CallService(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()))
.Callback<string, string, ServiceTarget?, object?>((domain, service, target, data) =>
calls.Add(new ServiceCall(domain, service, target, data)));
return calls;
}
/// <summary>Serialises a captured service-call payload so tests can assert on it.</summary>
public static JsonElement SerializePayload(object? data)
{
return JsonSerializer.SerializeToElement(data);
}
/// <summary>One captured <c>IHaContext.CallService</c> invocation.</summary>
public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data);
/// <summary>
/// Deterministic clock so cooldown boundaries can be crossed without real waiting.
/// </summary>
public sealed class ManualTimeProvider(DateTimeOffset? start = null) : TimeProvider
{
private DateTimeOffset _utcNow = start ?? DefaultStart;
public override DateTimeOffset GetUtcNow()
{
return _utcNow;
}
public void Advance(TimeSpan duration)
{
_utcNow += duration;
}
public void AdvanceSeconds(int seconds)
{
Advance(TimeSpan.FromSeconds(seconds));
}
}
/// <summary>
/// Observable that records subscriptions and lets tests push state changes through the
/// same pipeline the NetDaemon runtime uses.
/// </summary>
public sealed class TrackingObservable<T> : IObservable<T>
{
private readonly List<IObserver<T>> _observers = [];
public int SubscriptionCount => _observers.Count;
public IDisposable Subscribe(IObserver<T> observer)
{
_observers.Add(observer);
return new Subscription(_observers, observer);
}
public void Publish(T value)
{
foreach (var observer in _observers.ToArray()) observer.OnNext(value);
}
private sealed class Subscription(List<IObserver<T>> observers, IObserver<T> observer) : IDisposable
{
public void Dispose()
{
observers.Remove(observer);
}
}
}
}