Files
HomeAssistant/BatteryMonitor.Manager.Tests/BatteryNotificationServiceTests.cs
T
gitea_admin 17774b40b8 Convert test data sources to typed TheoryData
Replace untyped MemberData sources with TheoryData<...>, use collection
expressions for array and list literals, drop redundant casts and null
suppressions, and give log-assertion helpers an IsEnabled setup so guarded
log calls stay verifiable.
2026-11-29 21:42:41 +02:00

283 lines
10 KiB
C#

using System.Text.Json;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using BatteryMonitor.Models;
using BatteryMonitorManager;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
namespace BatteryMonitor.Manager.Tests;
public class BatteryNotificationServiceTests
{
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new();
private BatteryNotificationService CreateSut()
{
return new BatteryNotificationService(_haContextMock.Object, _loggerMock.Object);
}
private void VerifyCallService(string service, Times times)
{
_haContextMock.Verify(h => h.CallService(
BatteryMonitorConsts.PersistentNotificationDomain,
service,
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), times);
}
#region NotifyLowBattery
[Theory]
[MemberData(nameof(NotifyDeviceCounts), MemberType = typeof(BatteryMonitorTestData))]
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount)
{
var devices = CreateSensorInfos(
[
.. Enumerable.Range(0, deviceCount)
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
]);
var sut = CreateSut();
sut.NotifyLowBattery(devices);
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Once());
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Never());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void NotifyLowBattery_WithEmptyList_ShouldNotCallService(bool useArray)
{
IReadOnlyList<BatterySensorInfo> devices = useArray
? Array.Empty<BatterySensorInfo>()
: new List<BatterySensorInfo>();
var sut = CreateSut();
sut.NotifyLowBattery(devices);
_haContextMock.Verify(h => h.CallService(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Never);
_loggerMock.Invocations.Should().BeEmpty();
}
[Fact]
public void NotifyLowBattery_ShouldSendTitleNotificationIdAndDeviceSummary()
{
object? payload = null;
_haContextMock
.Setup(h => h.CallService(
BatteryMonitorConsts.PersistentNotificationDomain,
BatteryMonitorConsts.PersistentNotificationCreateService,
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()))
.Callback<string, string, ServiceTarget?, object?>((_, _, _, data) => payload = data);
var sut = CreateSut();
sut.NotifyLowBattery(CreateSensorInfos(
("sensor.a", "Device A", 4),
("sensor.b", "Device B", 1)));
payload.Should().NotBeNull();
using var document = JsonDocument.Parse(JsonSerializer.Serialize(payload));
var root = document.RootElement;
root.GetProperty("title").GetString().Should().Be(BatteryMonitorConsts.NotificationTitle);
root.GetProperty("notification_id").GetString().Should().Be(BatteryMonitorConsts.NotificationId);
var message = root.GetProperty("message").GetString();
message.Should().Contain("Device A").And.Contain("Device B");
message.Should().Contain("1%").And.Contain("4%");
}
[Fact]
public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount()
{
_loggerMock.Setup(l => l.IsEnabled(LogLevel.Information)).Returns(true);
var devices = CreateSensorInfos(
("sensor.a", "Device A", 2),
("sensor.b", "Device B", 3));
var sut = CreateSut();
sut.NotifyLowBattery(devices);
var logInvocation = _loggerMock.Invocations
.Where(invocation => invocation.Method.Name == nameof(ILogger.Log))
.Should().ContainSingle().Subject;
logInvocation.Arguments[0].Should().Be(LogLevel.Information);
logInvocation.Arguments[2].Should().NotBeNull();
logInvocation.Arguments[2]!.ToString().Should().Be("Sent low battery notification for 2 device(s)");
}
#endregion
#region DismissNotification
[Fact]
public void DismissNotification_ShouldCallPersistentNotificationDismiss()
{
var sut = CreateSut();
sut.DismissNotification();
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Once());
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(5)]
public void DismissNotification_WhenCalledRepeatedly_ShouldDismissEachTime(int calls)
{
var sut = CreateSut();
for (var i = 0; i < calls; i++)
{
sut.DismissNotification();
}
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls));
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
}
#endregion
#region BuildNotificationMessage
[Fact]
public void BuildNotificationMessage_ShouldOrderByBatteryLevel()
{
var devices = CreateSensorInfos(
("sensor.a", "Device A", 4),
("sensor.b", "Device B", 1),
("sensor.c", "Device C", 3));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
lines.Should().HaveCount(4);
lines[1].Should().Contain("Device B");
lines[2].Should().Contain("Device C");
lines[3].Should().Contain("Device A");
}
[Fact]
public void BuildNotificationMessage_ShouldKeepInsertionOrderForEqualLevels()
{
var devices = CreateSensorInfos(
("sensor.first", "First Device", 4),
("sensor.second", "Second Device", 4),
("sensor.third", "Third Device", 1));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
lines.Should().HaveCount(4);
lines[1].Should().Contain("Third Device");
lines[2].Should().Contain("First Device");
lines[3].Should().Contain("Second Device");
}
[Fact]
public void BuildNotificationMessage_WithGeneratedDevices_ShouldOrderByAscendingLevel()
{
var devices = CreateGeneratedSensorInfos(50);
var message = BatteryNotificationService.BuildNotificationMessage(devices);
var expectedLines = devices
.OrderBy(d => d.BatteryLevel)
.Select(d => $"- **{d.FriendlyName}**: {d.BatteryLevel:F0}%");
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
lines.Should().HaveCount(devices.Count + 1);
lines.Skip(1).Should().Equal(expectedLines);
}
[Fact]
public void BuildNotificationMessage_ShouldContainTitle()
{
var devices = CreateSensorInfos(("sensor.a", "Device A", 2));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
message.Should().Contain("low battery");
}
[Theory]
[InlineData("Bathroom Battery", 3, "- **Bathroom Battery**: 3%")]
[InlineData("Test Device", 1, "- **Test Device**: 1%")]
[InlineData("Empty Battery", 0, "- **Empty Battery**: 0%")]
[InlineData("Negative Battery", -7, "- **Negative Battery**: -7%")]
[InlineData("Rounded Down", 12.4, "- **Rounded Down**: 12%")]
[InlineData("Rounded Up", 12.6, "- **Rounded Up**: 13%")]
[InlineData("Full Battery", 100, "- **Full Battery**: 100%")]
[InlineData("", 5, "- ****: 5%")]
[InlineData(" ", 4, "- ** **: 4%")]
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, double batteryLevel, string expectedLine)
{
var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
lines.Should().HaveCount(2);
lines[1].Should().Be(expectedLine);
}
[Fact]
public void BuildNotificationMessage_ShouldContainDeviceNameAndLevel()
{
var devices = CreateSensorInfos(("sensor.a", "Bathroom Battery", 3));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
message.Should().Contain("Bathroom Battery");
message.Should().Contain("3%");
}
[Fact]
public void BuildNotificationMessage_WithSingleDevice_ShouldFormatCorrectly()
{
var devices = CreateSensorInfos(("sensor.a", "Test Device", 1));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
message.Should().Contain("- **Test Device**: 1%");
}
[Fact]
public void BuildNotificationMessage_WithDuplicateDevices_ShouldListEveryDevice()
{
var devices = CreateSensorInfos(
("sensor.duplicate_battery", "Duplicate Battery", 2),
("sensor.duplicate_battery", "Duplicate Battery", 2));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
lines.Should().HaveCount(3);
lines[1].Should().Be("- **Duplicate Battery**: 2%");
lines[2].Should().Be("- **Duplicate Battery**: 2%");
}
[Fact]
public void BuildNotificationMessage_WithNoDevices_ShouldContainOnlyHeader()
{
var message = BatteryNotificationService.BuildNotificationMessage([]);
message.Should().Be("The following devices have low battery:");
message.Should().NotContain("- **");
}
#endregion
}