Files
gitea_admin f919d6b25b Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
2026-12-01 12:33:31 +02:00

365 lines
14 KiB
C#

#region
using FluentAssertions;
using LeakMonitor.Models;
using LeakMonitorManager;
using LeakMonitorManager.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace LeakMonitor.Manager.Tests;
public class LeakNotificationServiceTests
{
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<LeakNotificationService>> _loggerMock = new Mock<ILogger<LeakNotificationService>>();
private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new LeakMonitorTestData.ManualTimeProvider();
private LeakNotificationService CreateSut(LeakMonitorOptions? options = null)
{
return new LeakNotificationService(
_haContextMock.Object,
_loggerMock.Object,
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
public static TheoryData<string, string> SendAlertServiceCalls { get; } = new TheoryData<string, string>
{
{ 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(LeakMonitorTestData.AquariumSensorId);
_haContextMock.Verify(
h => h.CallService(domain, service, It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Once());
}
[Fact]
public void SendLeakAlert_ShouldIncludeSensorDetailsInPayloads()
{
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
var sut = CreateSut();
const string sensorId = LeakMonitorTestData.AquariumSensorId;
const string expectedMessage = $"Water detected by {sensorId}! Check immediately.";
sut.SendLeakAlert(sensorId);
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_ShouldNotDismissNotification()
{
var sut = CreateSut();
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 is
{
Domain: LeakMonitorConsts.PersistentNotificationDomain,
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);
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]
public void SendLeakAlert_DifferentSensors_ShouldNotifyForEach()
{
var sut = CreateSut();
foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds)
{
sut.SendLeakAlert(sensorId);
}
VerifyMobilePush(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
VerifyPersistentCreate(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
}
[Fact]
public void SendLeakAlert_CooldownShouldBeTrackedPerSensor()
{
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
var sut = CreateSut();
sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId);
_timeProvider.AdvanceSeconds(60);
// 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
#region DismissLeakAlert
[Fact]
public void DismissLeakAlert_ShouldCallPersistentNotificationDismiss()
{
var sut = CreateSut();
sut.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId);
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
[Theory]
[MemberData(nameof(LeakMonitorTestData.NotificationIdCases), MemberType = typeof(LeakMonitorTestData))]
public void BuildNotificationId_ShouldSanitizeSensorId(string sensorEntityId, string expected)
{
var result = LeakNotificationService.BuildNotificationId(sensorEntityId);
result.Should().Be(expected);
result.Should().StartWith(LeakMonitorConsts.NotificationIdPrefix);
}
[Fact]
public void BuildNotificationId_WithNullSensorId_ShouldThrow()
{
// Production has no null guard; the string.Replace call fails before any prefix is built.
var act = () => LeakNotificationService.BuildNotificationId(null!);
act.Should().Throw<NullReferenceException>();
}
#endregion
}