Add shared test data builders and Qodana configuration
- 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
This commit is contained in:
@@ -8,18 +8,18 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="8.0.0">
|
||||
<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.3.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="FluentAssertions" Version="8.11.0" />
|
||||
<PackageReference Include="Moq" Version="4.21.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Moq;
|
||||
@@ -12,101 +13,344 @@ namespace LeakMonitor.Manager.Tests;
|
||||
|
||||
public class LeakMonitorInitTests
|
||||
{
|
||||
private readonly Mock<IHaContext> _haContextMock;
|
||||
private readonly Mock<ILeakNotificationService> _notificationServiceMock;
|
||||
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock;
|
||||
private readonly LeakMonitorOptions _options;
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILeakNotificationService> _notificationServiceMock = new();
|
||||
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock = new();
|
||||
private readonly LeakMonitorTestData.TrackingObservable<StateChange> _stateChanges = new();
|
||||
|
||||
public LeakMonitorInitTests()
|
||||
{
|
||||
_haContextMock = new Mock<IHaContext>();
|
||||
_notificationServiceMock = new Mock<ILeakNotificationService>();
|
||||
_loggerMock = new Mock<ILogger<LeakMonitorInit>>();
|
||||
_options = new LeakMonitorOptions
|
||||
{
|
||||
Enabled = true,
|
||||
SensorEntityIds = ["binary_sensor.aquarium_leak_sensor", "binary_sensor.boiler_moisture"]
|
||||
};
|
||||
_haContextMock.Setup(h => h.StateAllChanges()).Returns(_stateChanges);
|
||||
}
|
||||
|
||||
private LeakMonitorInit CreateSut()
|
||||
private LeakMonitorInit CreateSut(LeakMonitorOptions? options = null)
|
||||
{
|
||||
return new LeakMonitorInit(
|
||||
_haContextMock.Object,
|
||||
_notificationServiceMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(_options));
|
||||
Options.Create(options ?? LeakMonitorTestData.CreateOptions()));
|
||||
}
|
||||
|
||||
private void VerifyNotifications(Times expected)
|
||||
{
|
||||
_notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny<string>()), expected);
|
||||
_notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny<string>()), expected);
|
||||
}
|
||||
|
||||
private void VerifyLogged(LogLevel level, Times times)
|
||||
{
|
||||
_loggerMock.Verify(
|
||||
l => l.Log(
|
||||
level,
|
||||
It.IsAny<EventId>(),
|
||||
It.IsAny<It.IsAnyType>(),
|
||||
It.IsAny<Exception?>(),
|
||||
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
|
||||
times);
|
||||
}
|
||||
|
||||
#region HandleStateChange
|
||||
|
||||
[Fact]
|
||||
public void HandleStateChange_WaterDetected_ShouldSendLeakAlert()
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.WaterDetectedCases), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void HandleStateChange_WhenWaterDetected_ShouldSendLeakAlert(string sensorEntityId, string? newState)
|
||||
{
|
||||
var sut = CreateSut();
|
||||
var change = CreateStateChange("off", LeakMonitorConsts.WaterDetectedState);
|
||||
var change = LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
newState);
|
||||
|
||||
sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change);
|
||||
sut.HandleStateChange(sensorEntityId, change);
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert("binary_sensor.aquarium_leak_sensor"),
|
||||
Times.Once);
|
||||
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
|
||||
_notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny<string>()), Times.Never());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.WaterClearedCases), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void HandleStateChange_WhenWaterCleared_ShouldDismissLeakAlert(string sensorEntityId, string? newState)
|
||||
{
|
||||
var sut = CreateSut();
|
||||
var change = LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState);
|
||||
|
||||
sut.HandleStateChange(sensorEntityId, change);
|
||||
|
||||
_notificationServiceMock.Verify(n => n.DismissLeakAlert(sensorEntityId), Times.Once());
|
||||
_notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny<string>()), Times.Never());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.NonActionableStateCases), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void HandleStateChange_WhenStateIsNotActionable_ShouldNotNotify(string? newState)
|
||||
{
|
||||
var sut = CreateSut();
|
||||
var change = LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState);
|
||||
|
||||
sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change);
|
||||
|
||||
VerifyNotifications(Times.Never());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HandleStateChange_WaterCleared_ShouldDismissLeakAlert()
|
||||
public void HandleStateChange_WhenDetectionRepeats_ShouldForwardEveryDetection()
|
||||
{
|
||||
// Deduplication is the notification service's job (cooldown); the init handler
|
||||
// forwards each "on" event it receives.
|
||||
var sut = CreateSut();
|
||||
var change = CreateStateChange("on", LeakMonitorConsts.WaterClearedState);
|
||||
var change = LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
LeakMonitorConsts.WaterDetectedState);
|
||||
|
||||
sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change);
|
||||
sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change);
|
||||
sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change);
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.DismissLeakAlert("binary_sensor.aquarium_leak_sensor"),
|
||||
Times.Once);
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Exactly(2));
|
||||
_notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny<string>()), Times.Never());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HandleStateChange_UnknownState_ShouldNotNotify()
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void HandleStateChange_WithBlankSensorId_ShouldForwardTheIdVerbatim(string sensorEntityId)
|
||||
{
|
||||
var sut = CreateSut();
|
||||
var change = CreateStateChange("off", "unavailable");
|
||||
var change = LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState);
|
||||
|
||||
sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change);
|
||||
sut.HandleStateChange(sensorEntityId, change);
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert(It.IsAny<string>()),
|
||||
Times.Never);
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.DismissLeakAlert(It.IsAny<string>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HandleStateChange_CaseInsensitive_ShouldDetectWater()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
var change = CreateStateChange("off", "ON");
|
||||
|
||||
sut.HandleStateChange("binary_sensor.boiler_moisture", change);
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert("binary_sensor.boiler_moisture"),
|
||||
Times.Once);
|
||||
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private StateChange CreateStateChange(string? oldState, string? newState)
|
||||
{
|
||||
var entity = new Entity(_haContextMock.Object, "binary_sensor.test");
|
||||
var oldEntityState = oldState is not null
|
||||
? new EntityState { State = oldState }
|
||||
: null;
|
||||
var newEntityState = newState is not null
|
||||
? new EntityState { State = newState }
|
||||
: null;
|
||||
#region InitializeAsync
|
||||
|
||||
return new StateChange(entity, oldEntityState, newEntityState);
|
||||
[Fact]
|
||||
public void InitializeAsync_WhenNoSensorsConfigured_ShouldNotSubscribeAndLogWarning()
|
||||
{
|
||||
var sut = CreateSut(LeakMonitorTestData.CreateOptions(sensorEntityIds: []));
|
||||
|
||||
sut.Should().NotBeNull();
|
||||
_stateChanges.SubscriptionCount.Should().Be(0);
|
||||
_haContextMock.Verify(h => h.StateAllChanges(), Times.Never());
|
||||
VerifyNotifications(Times.Never());
|
||||
VerifyLogged(LogLevel.Warning, Times.Once());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeAsync_WhenSensorsConfigured_ShouldSubscribeToEachSensor()
|
||||
{
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.SubscriptionCount.Should().Be(LeakMonitorTestData.DefaultSensorIds.Length);
|
||||
_haContextMock.Verify(
|
||||
h => h.StateAllChanges(),
|
||||
Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void InitializeAsync_WithBlankSensorId_ShouldStillSubscribeAndForward(string sensorEntityId)
|
||||
{
|
||||
var sut = CreateSut(LeakMonitorTestData.CreateOptions(sensorEntityIds: [sensorEntityId]));
|
||||
|
||||
_stateChanges.SubscriptionCount.Should().Be(1);
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
|
||||
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeAsync_WithNullSensorEntry_ShouldStillSubscribeRemainingSensors()
|
||||
{
|
||||
CreateSut(LeakMonitorTestData.CreateOptions(
|
||||
sensorEntityIds: [null!, LeakMonitorTestData.BoilerSensorId]));
|
||||
|
||||
_stateChanges.SubscriptionCount.Should().Be(2);
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.BoilerSensorId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId),
|
||||
Times.Once());
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Never());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.WaterDetectedCases), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void InitializeAsync_WhenSubscribedSensorDetectsWater_ShouldSendLeakAlert(
|
||||
string sensorEntityId,
|
||||
string? newState)
|
||||
{
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
newState));
|
||||
|
||||
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert(It.Is<string>(id => id != sensorEntityId)),
|
||||
Times.Never());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.WaterClearedCases), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void InitializeAsync_WhenSubscribedSensorClearsWater_ShouldDismissLeakAlert(
|
||||
string sensorEntityId,
|
||||
string? newState)
|
||||
{
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
sensorEntityId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState));
|
||||
|
||||
_notificationServiceMock.Verify(n => n.DismissLeakAlert(sensorEntityId), Times.Once());
|
||||
_notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny<string>()), Times.Never());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.NonActionableStateCases), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void InitializeAsync_WhenSubscribedSensorReportsNonActionableState_ShouldNotNotify(string? newState)
|
||||
{
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
newState));
|
||||
|
||||
VerifyNotifications(Times.Never());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeAsync_WhenStateIsUnchanged_ShouldNotNotify()
|
||||
{
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
|
||||
VerifyNotifications(Times.Never());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeAsync_WhenUnrelatedEntityChanges_ShouldNotNotify()
|
||||
{
|
||||
CreateSut();
|
||||
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
"binary_sensor.unrelated_motion",
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
|
||||
VerifyNotifications(Times.Never());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeAsync_WhenDetectionSequenceArrives_ShouldNotifyPerTransition()
|
||||
{
|
||||
CreateSut();
|
||||
|
||||
foreach (var change in LeakMonitorTestData.CreateStateChangeSequence(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorTestData.DetectionSequence))
|
||||
{
|
||||
_stateChanges.Publish(change);
|
||||
}
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Exactly(2));
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeAsync_WhenNotificationServiceThrows_ShouldLogErrorAndKeepMonitoring()
|
||||
{
|
||||
_notificationServiceMock
|
||||
.Setup(n => n.SendLeakAlert(It.IsAny<string>()))
|
||||
.Throws(new InvalidOperationException("notification failed"));
|
||||
|
||||
CreateSut();
|
||||
|
||||
var act = () => _stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterClearedState,
|
||||
LeakMonitorConsts.WaterDetectedState));
|
||||
|
||||
act.Should().NotThrow();
|
||||
VerifyLogged(LogLevel.Error, Times.Once());
|
||||
|
||||
// The failed event must not tear down the subscription.
|
||||
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||
_haContextMock.Object,
|
||||
LeakMonitorTestData.AquariumSensorId,
|
||||
LeakMonitorConsts.WaterDetectedState,
|
||||
LeakMonitorConsts.WaterClearedState));
|
||||
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||
Times.Once());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitializeAsync_WhenSubscriptionFails_ShouldSwallowAndLogError()
|
||||
{
|
||||
_haContextMock
|
||||
.Setup(h => h.StateAllChanges())
|
||||
.Throws(new InvalidOperationException("home assistant offline"));
|
||||
|
||||
var act = () => CreateSut();
|
||||
|
||||
act.Should().NotThrow();
|
||||
_stateChanges.SubscriptionCount.Should().Be(0);
|
||||
VerifyNotifications(Times.Never());
|
||||
VerifyLogged(LogLevel.Error, Times.Once());
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
using System.Text.Json;
|
||||
using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using LeakMonitor.Models;
|
||||
using LeakMonitorManager.Models;
|
||||
|
||||
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];
|
||||
|
||||
public static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
/// <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) => new()
|
||||
{
|
||||
Enabled = enabled,
|
||||
SensorEntityIds = sensorEntityIds?.ToArray() ?? [.. DefaultSensorIds],
|
||||
NotificationCooldownMinutes = notificationCooldownMinutes
|
||||
};
|
||||
|
||||
/// <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; } = new()
|
||||
{
|
||||
"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; } = new()
|
||||
{
|
||||
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 < 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; } = new()
|
||||
{
|
||||
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 an <see cref="EntityState"/>, or <c>null</c> when the entity has no state at all.
|
||||
/// </summary>
|
||||
public static EntityState? CreateOptionalState(string? state) =>
|
||||
state is null ? null : new EntityState { State = state };
|
||||
|
||||
public static StateChange CreateStateChange(
|
||||
IHaContext haContext,
|
||||
string entityId,
|
||||
string? oldState,
|
||||
string? newState) =>
|
||||
new(new Entity(haContext, entityId), CreateOptionalState(oldState), CreateOptionalState(newState));
|
||||
|
||||
public static IReadOnlyList<StateChange> CreateStateChangeSequence(
|
||||
IHaContext haContext,
|
||||
string entityId,
|
||||
params (string? OldState, string? NewState)[] transitions) =>
|
||||
transitions
|
||||
.Select(transition => CreateStateChange(haContext, entityId, transition.OldState, transition.NewState))
|
||||
.ToList();
|
||||
|
||||
/// <summary>One captured <c>IHaContext.CallService</c> invocation.</summary>
|
||||
public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data);
|
||||
|
||||
/// <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) => JsonSerializer.SerializeToElement(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() => _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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,74 +12,204 @@ namespace LeakMonitor.Manager.Tests;
|
||||
|
||||
public class LeakNotificationServiceTests
|
||||
{
|
||||
private readonly Mock<IHaContext> _haContextMock;
|
||||
private readonly Mock<ILogger<LeakNotificationService>> _loggerMock;
|
||||
private readonly LeakMonitorOptions _options;
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<LeakNotificationService>> _loggerMock = new();
|
||||
private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new();
|
||||
|
||||
public LeakNotificationServiceTests()
|
||||
{
|
||||
_haContextMock = new Mock<IHaContext>();
|
||||
_loggerMock = new Mock<ILogger<LeakNotificationService>>();
|
||||
_options = new LeakMonitorOptions
|
||||
{
|
||||
Enabled = true,
|
||||
NotificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes
|
||||
};
|
||||
}
|
||||
|
||||
private LeakNotificationService CreateSut()
|
||||
private LeakNotificationService CreateSut(LeakMonitorOptions? options = null)
|
||||
{
|
||||
return new LeakNotificationService(
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(_options),
|
||||
TimeProvider.System);
|
||||
Options.Create(options ?? LeakMonitorTestData.CreateOptions()),
|
||||
_timeProvider);
|
||||
}
|
||||
|
||||
private void VerifyMobilePush(Times times)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
h => h.CallService(
|
||||
LeakMonitorConsts.NotifyDomain,
|
||||
LeakMonitorConsts.MobileAppService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()),
|
||||
times);
|
||||
}
|
||||
|
||||
private void VerifyPersistentCreate(Times times)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
h => h.CallService(
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationCreateService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()),
|
||||
times);
|
||||
}
|
||||
|
||||
private void VerifyPersistentDismiss(Times times)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
h => h.CallService(
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationDismissService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()),
|
||||
times);
|
||||
}
|
||||
|
||||
#region SendLeakAlert
|
||||
|
||||
[Fact]
|
||||
public void SendLeakAlert_ShouldCallMobileNotifyService()
|
||||
public static TheoryData<string, string> SendAlertServiceCalls { get; } = new()
|
||||
{
|
||||
{ LeakMonitorConsts.NotifyDomain, LeakMonitorConsts.MobileAppService },
|
||||
{ LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationCreateService }
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(SendAlertServiceCalls))]
|
||||
public void SendLeakAlert_ShouldCallExpectedService(string domain, string service)
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.SendLeakAlert("binary_sensor.aquarium_leak_sensor");
|
||||
sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||
|
||||
_haContextMock.Verify(h => h.CallService(
|
||||
LeakMonitorConsts.NotifyDomain,
|
||||
LeakMonitorConsts.MobileAppService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), Times.Once);
|
||||
_haContextMock.Verify(
|
||||
h => h.CallService(domain, service, It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Once());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SendLeakAlert_ShouldCallPersistentNotificationCreate()
|
||||
public void SendLeakAlert_ShouldIncludeSensorDetailsInPayloads()
|
||||
{
|
||||
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
|
||||
var sut = CreateSut();
|
||||
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||
var expectedMessage = $"Water detected by {sensorId}! Check immediately.";
|
||||
|
||||
sut.SendLeakAlert("binary_sensor.aquarium_leak_sensor");
|
||||
sut.SendLeakAlert(sensorId);
|
||||
|
||||
_haContextMock.Verify(h => h.CallService(
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationCreateService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), Times.Once);
|
||||
calls.Should().HaveCount(2);
|
||||
|
||||
var mobileCall = calls.Single(c => c.Service == LeakMonitorConsts.MobileAppService);
|
||||
mobileCall.Domain.Should().Be(LeakMonitorConsts.NotifyDomain);
|
||||
mobileCall.Target.Should().BeNull();
|
||||
|
||||
var mobilePayload = LeakMonitorTestData.SerializePayload(mobileCall.Data);
|
||||
mobilePayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle);
|
||||
mobilePayload.GetProperty("message").GetString().Should().Be(expectedMessage);
|
||||
|
||||
var sound = mobilePayload.GetProperty("data").GetProperty("push").GetProperty("sound");
|
||||
sound.GetProperty("critical").GetInt32().Should().Be(1);
|
||||
sound.GetProperty("volume").GetDouble().Should().Be(1.0);
|
||||
|
||||
var persistentCall = calls.Single(c => c.Service == LeakMonitorConsts.PersistentNotificationCreateService);
|
||||
persistentCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain);
|
||||
persistentCall.Target.Should().BeNull();
|
||||
|
||||
var persistentPayload = LeakMonitorTestData.SerializePayload(persistentCall.Data);
|
||||
persistentPayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle);
|
||||
persistentPayload.GetProperty("message").GetString().Should().Be(expectedMessage);
|
||||
persistentPayload.GetProperty("notification_id").GetString().Should()
|
||||
.Be(LeakNotificationService.BuildNotificationId(sensorId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SendLeakAlert_CalledTwiceWithinCooldown_ShouldOnlyNotifyOnce()
|
||||
public void SendLeakAlert_ShouldNotDismissNotification()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
const string sensorId = "binary_sensor.aquarium_leak_sensor";
|
||||
|
||||
sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||
|
||||
VerifyMobilePush(Times.Once());
|
||||
VerifyPersistentCreate(Times.Once());
|
||||
VerifyPersistentDismiss(Times.Never());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.NotificationIdCases), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void SendLeakAlert_ShouldUseExpectedNotificationId(string sensorId, string expectedNotificationId)
|
||||
{
|
||||
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.SendLeakAlert(sensorId);
|
||||
|
||||
var persistentCall = calls.Single(c =>
|
||||
c.Domain == LeakMonitorConsts.PersistentNotificationDomain &&
|
||||
c.Service == LeakMonitorConsts.PersistentNotificationCreateService);
|
||||
|
||||
LeakMonitorTestData.SerializePayload(persistentCall.Data)
|
||||
.GetProperty("notification_id")
|
||||
.GetString()
|
||||
.Should()
|
||||
.Be(expectedNotificationId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.RepeatedNotificationCounts), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void SendLeakAlert_RepeatedWithinCooldown_ShouldOnlyNotifyOnce(int repeats)
|
||||
{
|
||||
var sut = CreateSut();
|
||||
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||
|
||||
for (var i = 0; i < repeats; i++)
|
||||
{
|
||||
sut.SendLeakAlert(sensorId);
|
||||
}
|
||||
|
||||
VerifyMobilePush(Times.Once());
|
||||
VerifyPersistentCreate(Times.Once());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.RepeatedNotificationCounts), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void SendLeakAlert_RepeatedWithZeroCooldown_ShouldAlwaysNotify(int repeats)
|
||||
{
|
||||
var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: 0));
|
||||
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||
|
||||
for (var i = 0; i < repeats; i++)
|
||||
{
|
||||
sut.SendLeakAlert(sensorId);
|
||||
}
|
||||
|
||||
VerifyMobilePush(Times.Exactly(repeats));
|
||||
VerifyPersistentCreate(Times.Exactly(repeats));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.CooldownBoundaryCases), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void SendLeakAlert_ShouldRespectCooldownBoundaries(
|
||||
int cooldownMinutes,
|
||||
int elapsedSeconds,
|
||||
int expectedNotificationCount)
|
||||
{
|
||||
var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: cooldownMinutes));
|
||||
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||
|
||||
sut.SendLeakAlert(sensorId);
|
||||
_timeProvider.AdvanceSeconds(elapsedSeconds);
|
||||
sut.SendLeakAlert(sensorId);
|
||||
|
||||
_haContextMock.Verify(h => h.CallService(
|
||||
LeakMonitorConsts.NotifyDomain,
|
||||
LeakMonitorConsts.MobileAppService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), Times.Once);
|
||||
VerifyMobilePush(Times.Exactly(expectedNotificationCount));
|
||||
VerifyPersistentCreate(Times.Exactly(expectedNotificationCount));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SendLeakAlert_AfterEachCooldownExpires_ShouldNotifyEveryTime()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||
|
||||
sut.SendLeakAlert(sensorId);
|
||||
_timeProvider.Advance(TimeSpan.FromMinutes(LeakMonitorConsts.DefaultNotificationCooldownMinutes));
|
||||
sut.SendLeakAlert(sensorId);
|
||||
_timeProvider.Advance(TimeSpan.FromMinutes(LeakMonitorConsts.DefaultNotificationCooldownMinutes));
|
||||
sut.SendLeakAlert(sensorId);
|
||||
|
||||
VerifyMobilePush(Times.Exactly(3));
|
||||
VerifyPersistentCreate(Times.Exactly(3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -87,31 +217,50 @@ public class LeakNotificationServiceTests
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.SendLeakAlert("binary_sensor.aquarium_leak_sensor");
|
||||
sut.SendLeakAlert("binary_sensor.boiler_moisture");
|
||||
foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds)
|
||||
{
|
||||
sut.SendLeakAlert(sensorId);
|
||||
}
|
||||
|
||||
_haContextMock.Verify(h => h.CallService(
|
||||
LeakMonitorConsts.NotifyDomain,
|
||||
LeakMonitorConsts.MobileAppService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), Times.Exactly(2));
|
||||
VerifyMobilePush(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
|
||||
VerifyPersistentCreate(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SendLeakAlert_WithZeroCooldown_ShouldAlwaysNotify()
|
||||
public void SendLeakAlert_CooldownShouldBeTrackedPerSensor()
|
||||
{
|
||||
_options.NotificationCooldownMinutes = 0;
|
||||
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
|
||||
var sut = CreateSut();
|
||||
const string sensorId = "binary_sensor.aquarium_leak_sensor";
|
||||
|
||||
sut.SendLeakAlert(sensorId);
|
||||
sut.SendLeakAlert(sensorId);
|
||||
sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||
_timeProvider.AdvanceSeconds(60);
|
||||
|
||||
_haContextMock.Verify(h => h.CallService(
|
||||
LeakMonitorConsts.NotifyDomain,
|
||||
LeakMonitorConsts.MobileAppService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), Times.Exactly(2));
|
||||
// A first-ever alert for a different sensor is not suppressed by the first sensor's cooldown.
|
||||
sut.SendLeakAlert(LeakMonitorTestData.BoilerSensorId);
|
||||
sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||
|
||||
VerifyMobilePush(Times.Exactly(2));
|
||||
|
||||
var boilerNotifications = calls
|
||||
.Where(c => c.Domain == LeakMonitorConsts.NotifyDomain)
|
||||
.Where(c => LeakMonitorTestData.SerializePayload(c.Data)
|
||||
.GetProperty("message")
|
||||
.GetString()!
|
||||
.Contains(LeakMonitorTestData.BoilerSensorId, StringComparison.Ordinal));
|
||||
|
||||
boilerNotifications.Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SendLeakAlert_WithNullSensorId_ShouldThrowAndNotNotify()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
var act = () => sut.SendLeakAlert(null!);
|
||||
|
||||
act.Should().Throw<ArgumentNullException>();
|
||||
VerifyMobilePush(Times.Never());
|
||||
VerifyPersistentCreate(Times.Never());
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -123,33 +272,82 @@ public class LeakNotificationServiceTests
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.DismissLeakAlert("binary_sensor.aquarium_leak_sensor");
|
||||
sut.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||
|
||||
_haContextMock.Verify(h => h.CallService(
|
||||
LeakMonitorConsts.PersistentNotificationDomain,
|
||||
LeakMonitorConsts.PersistentNotificationDismissService,
|
||||
It.IsAny<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), Times.Once);
|
||||
VerifyPersistentDismiss(Times.Once());
|
||||
VerifyMobilePush(Times.Never());
|
||||
VerifyPersistentCreate(Times.Never());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.NotificationIdCases), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void DismissLeakAlert_ShouldUseExpectedNotificationId(string sensorId, string expectedNotificationId)
|
||||
{
|
||||
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.DismissLeakAlert(sensorId);
|
||||
|
||||
var dismissCall = calls.Should().ContainSingle().Which;
|
||||
dismissCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain);
|
||||
dismissCall.Service.Should().Be(LeakMonitorConsts.PersistentNotificationDismissService);
|
||||
dismissCall.Target.Should().BeNull();
|
||||
LeakMonitorTestData.SerializePayload(dismissCall.Data)
|
||||
.GetProperty("notification_id")
|
||||
.GetString()
|
||||
.Should()
|
||||
.Be(expectedNotificationId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DismissLeakAlert_CalledRepeatedly_ShouldDismissEachTime()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||
|
||||
sut.DismissLeakAlert(sensorId);
|
||||
sut.DismissLeakAlert(sensorId);
|
||||
|
||||
VerifyPersistentDismiss(Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DismissLeakAlert_ShouldNotResetCooldown()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||
|
||||
sut.SendLeakAlert(sensorId);
|
||||
sut.DismissLeakAlert(sensorId);
|
||||
_timeProvider.AdvanceSeconds(60);
|
||||
sut.SendLeakAlert(sensorId);
|
||||
|
||||
VerifyMobilePush(Times.Once());
|
||||
VerifyPersistentCreate(Times.Once());
|
||||
VerifyPersistentDismiss(Times.Once());
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region BuildNotificationId
|
||||
|
||||
[Fact]
|
||||
public void BuildNotificationId_ShouldReplaceDotsWithUnderscores()
|
||||
[Theory]
|
||||
[MemberData(nameof(LeakMonitorTestData.NotificationIdCases), MemberType = typeof(LeakMonitorTestData))]
|
||||
public void BuildNotificationId_ShouldSanitizeSensorId(string sensorEntityId, string expected)
|
||||
{
|
||||
var result = LeakNotificationService.BuildNotificationId("binary_sensor.aquarium_leak_sensor");
|
||||
var result = LeakNotificationService.BuildNotificationId(sensorEntityId);
|
||||
|
||||
result.Should().Be("leak_monitor_binary_sensor_aquarium_leak_sensor");
|
||||
result.Should().Be(expected);
|
||||
result.Should().StartWith(LeakMonitorConsts.NotificationIdPrefix);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildNotificationId_ShouldStartWithPrefix()
|
||||
public void BuildNotificationId_WithNullSensorId_ShouldThrow()
|
||||
{
|
||||
var result = LeakNotificationService.BuildNotificationId("binary_sensor.boiler_moisture");
|
||||
// Production has no null guard; the string.Replace call fails before any prefix is built.
|
||||
Action act = () => LeakNotificationService.BuildNotificationId(null!);
|
||||
|
||||
result.Should().StartWith(LeakMonitorConsts.NotificationIdPrefix);
|
||||
act.Should().Throw<NullReferenceException>();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
Reference in New Issue
Block a user