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
This commit is contained in:
2026-12-01 12:33:31 +02:00
parent 77458383d1
commit f919d6b25b
115 changed files with 3115 additions and 1959 deletions
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using System.Text.Json;
using BatteryMonitor.Models;
@@ -5,6 +7,8 @@ using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace BatteryMonitor.Manager.Tests;
/// <summary>
@@ -20,7 +24,7 @@ internal static class BatteryMonitorTestData
/// (threshold, state, expected) rows straddling the strict <c>level &lt; threshold</c>
/// boundary, including zero/negative thresholds and int min/max thresholds.
/// </summary>
public static TheoryData<int, string, bool> ThresholdBoundaryRows { get; } = new()
public static TheoryData<int, string, bool> ThresholdBoundaryRows { get; } = new TheoryData<int, string, bool>
{
{ 5, "4", true },
{ 5, "5", false },
@@ -59,7 +63,7 @@ internal static class BatteryMonitorTestData
"unknown",
"UNAVAILABLE",
"UNKNOWN",
"",
string.Empty,
" ",
"\t",
"not_a_number",
@@ -85,8 +89,10 @@ internal static class BatteryMonitorTestData
}
/// <summary>A sensor with an arbitrary (or missing) device class.</summary>
public static EntitySpec Sensor(string entityId, string? deviceClass, string? state,
string? friendlyName = DefaultFriendlyName)
public static EntitySpec Sensor(string entityId,
string? deviceClass,
string? state,
string? friendlyName = DefaultFriendlyName)
{
return new EntitySpec
{
@@ -101,9 +107,15 @@ internal static class BatteryMonitorTestData
{
var attributes = new Dictionary<string, object?>(StringComparer.Ordinal);
if (spec.DeviceClass is not null) attributes["device_class"] = spec.DeviceClass;
if (spec.DeviceClass is not null)
{
attributes["device_class"] = spec.DeviceClass;
}
if (spec.FriendlyName is not null) attributes["friendly_name"] = spec.FriendlyName;
if (spec.FriendlyName is not null)
{
attributes["friendly_name"] = spec.FriendlyName;
}
return new EntityState
{
@@ -122,7 +134,10 @@ internal static class BatteryMonitorTestData
foreach (var spec in entities)
{
if (spec.HasState) haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
if (spec.HasState)
{
haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
}
entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
}
@@ -159,10 +174,10 @@ internal static class BatteryMonitorTestData
return
[
.. Enumerable.Range(0, count)
.Select(i => Battery(
$"sensor.generated_battery_{i:D3}",
i.ToString(CultureInfo.InvariantCulture),
$"Generated Battery {i:D3}"))
.Select(i => Battery(
$"sensor.generated_battery_{i:D3}",
i.ToString(CultureInfo.InvariantCulture),
$"Generated Battery {i:D3}"))
];
}
@@ -175,10 +190,10 @@ internal static class BatteryMonitorTestData
return
[
.. Enumerable.Range(0, count)
.Select(i => CreateSensorInfo(
$"sensor.generated_{i:D3}",
i * 37 % 101,
$"Generated Device {i:D3}"))
.Select(i => CreateSensorInfo(
$"sensor.generated_{i:D3}",
i * 37 % 101,
$"Generated Device {i:D3}"))
];
}
@@ -202,7 +217,7 @@ internal static class BatteryMonitorTestData
data.Add("sensor.boiler_temp_battery", false);
data.Add("sensor.aquarium_leak_sensor_battery", false);
data.Add("sensor.temperature", false);
data.Add("", false);
data.Add(string.Empty, false);
data.Add(" ", false);
return data;
@@ -1,3 +1,5 @@
#region
using System.Text.Json;
using BatteryMonitor.Models;
using BatteryMonitorManager;
@@ -8,12 +10,14 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
#endregion
namespace BatteryMonitor.Manager.Tests;
public class BatteryNotificationServiceTests
{
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new Mock<ILogger<BatteryNotificationService>>();
private BatteryNotificationService CreateSut()
{
@@ -23,10 +27,10 @@ public class BatteryNotificationServiceTests
private void VerifyCallService(string service, Times times)
{
_haContextMock.Verify(h => h.CallService(
BatteryMonitorConsts.PersistentNotificationDomain,
service,
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), times);
BatteryMonitorConsts.PersistentNotificationDomain,
service,
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), times);
}
#region NotifyLowBattery
@@ -38,7 +42,7 @@ public class BatteryNotificationServiceTests
var devices = CreateSensorInfos(
[
.. Enumerable.Range(0, deviceCount)
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
]);
var sut = CreateSut();
@@ -54,17 +58,18 @@ public class BatteryNotificationServiceTests
public void NotifyLowBattery_WithEmptyList_ShouldNotCallService(bool useArray)
{
IReadOnlyList<BatterySensorInfo> devices = useArray
? Array.Empty<BatterySensorInfo>()
: new List<BatterySensorInfo>();
? 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);
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Never);
_loggerMock.Invocations.Should().BeEmpty();
}
@@ -72,18 +77,20 @@ public class BatteryNotificationServiceTests
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);
.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)));
("sensor.a", "Device A", 4),
("sensor.b", "Device B", 1)));
payload.Should().NotBeNull();
@@ -101,16 +108,19 @@ public class BatteryNotificationServiceTests
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));
("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;
.Where(invocation => invocation.Method.Name == nameof(ILogger.Log))
.Should()
.ContainSingle()
.Subject;
logInvocation.Arguments[0].Should().Be(LogLevel.Information);
logInvocation.Arguments[2].Should().NotBeNull();
@@ -139,7 +149,10 @@ public class BatteryNotificationServiceTests
{
var sut = CreateSut();
for (var i = 0; i < calls; i++) sut.DismissNotification();
for (var i = 0; i < calls; i++)
{
sut.DismissNotification();
}
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls));
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
@@ -153,9 +166,9 @@ public class BatteryNotificationServiceTests
public void BuildNotificationMessage_ShouldOrderByBatteryLevel()
{
var devices = CreateSensorInfos(
("sensor.a", "Device A", 4),
("sensor.b", "Device B", 1),
("sensor.c", "Device C", 3));
("sensor.a", "Device A", 4),
("sensor.b", "Device B", 1),
("sensor.c", "Device C", 3));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
@@ -170,9 +183,9 @@ public class BatteryNotificationServiceTests
public void BuildNotificationMessage_ShouldKeepInsertionOrderForEqualLevels()
{
var devices = CreateSensorInfos(
("sensor.first", "First Device", 4),
("sensor.second", "Second Device", 4),
("sensor.third", "Third Device", 1));
("sensor.first", "First Device", 4),
("sensor.second", "Second Device", 4),
("sensor.third", "Third Device", 1));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
@@ -191,8 +204,8 @@ public class BatteryNotificationServiceTests
var message = BatteryNotificationService.BuildNotificationMessage(devices);
var expectedLines = devices
.OrderBy(d => d.BatteryLevel)
.Select(d => $"- **{d.FriendlyName}**: {d.BatteryLevel:F0}%");
.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);
@@ -219,8 +232,9 @@ public class BatteryNotificationServiceTests
[InlineData("Full Battery", 100, "- **Full Battery**: 100%")]
[InlineData("", 5, "- ****: 5%")]
[InlineData(" ", 4, "- ** **: 4%")]
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, double batteryLevel,
string expectedLine)
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName,
double batteryLevel,
string expectedLine)
{
var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel));
@@ -256,8 +270,8 @@ public class BatteryNotificationServiceTests
public void BuildNotificationMessage_WithDuplicateDevices_ShouldListEveryDevice()
{
var devices = CreateSensorInfos(
("sensor.duplicate_battery", "Duplicate Battery", 2),
("sensor.duplicate_battery", "Duplicate Battery", 2));
("sensor.duplicate_battery", "Duplicate Battery", 2),
("sensor.duplicate_battery", "Duplicate Battery", 2));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using BatteryMonitor.Models;
using BatteryMonitorManager;
@@ -8,12 +10,14 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
#endregion
namespace BatteryMonitor.Manager.Tests;
public class BatterySensorDiscoveryServiceTests
{
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
private BatterySensorDiscoveryService CreateSut()
{
@@ -42,10 +46,10 @@ public class BatterySensorDiscoveryServiceTests
public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices()
{
SetupEntities(
Battery("sensor.bathroom_battery", "3", "Bathroom Battery"),
Battery("sensor.bedroom_battery", "80", "Bedroom Battery"),
Battery("sensor.boiler_temp_battery", "2", "Boiler Temp Battery")
);
Battery("sensor.bathroom_battery", "3", "Bathroom Battery"),
Battery("sensor.bedroom_battery", "80", "Bedroom Battery"),
Battery("sensor.boiler_temp_battery", "2", "Boiler Temp Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
@@ -70,9 +74,9 @@ public class BatterySensorDiscoveryServiceTests
public void DiscoverLowBatterySensors_ShouldExcludePersonalDevices(string excludedEntityId, string friendlyName)
{
SetupEntities(
Battery("sensor.bathroom_battery", "2", "Bathroom Battery"),
Battery(excludedEntityId, "1", friendlyName)
);
Battery("sensor.bathroom_battery", "2", "Bathroom Battery"),
Battery(excludedEntityId, "1", friendlyName)
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
@@ -89,12 +93,12 @@ public class BatterySensorDiscoveryServiceTests
[InlineData("sensorx.bathroom_battery", "battery")]
[InlineData("switch.bathroom_battery", "battery")]
public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId,
string? deviceClass)
string? deviceClass)
{
SetupEntities(
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
);
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
@@ -108,9 +112,9 @@ public class BatterySensorDiscoveryServiceTests
public void DiscoverLowBatterySensors_ShouldSkipUnusableStates(string? state)
{
SetupEntities(
Battery("sensor.bathroom_battery", state, "Bathroom Battery"),
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
);
Battery("sensor.bathroom_battery", state, "Bathroom Battery"),
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
@@ -123,10 +127,10 @@ public class BatterySensorDiscoveryServiceTests
public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor()
{
SetupEntities(
new EntitySpec
{ EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
);
new EntitySpec
{ EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
@@ -137,8 +141,9 @@ public class BatterySensorDiscoveryServiceTests
[Theory]
[MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))]
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent, string state,
bool expectedIncluded)
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent,
string state,
bool expectedIncluded)
{
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
@@ -147,7 +152,10 @@ public class BatterySensorDiscoveryServiceTests
result.Should().HaveCount(expectedIncluded ? 1 : 0);
if (!expectedIncluded) return;
if (!expectedIncluded)
{
return;
}
result[0].EntityId.Should().Be("sensor.boundary_battery");
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
@@ -157,9 +165,9 @@ public class BatterySensorDiscoveryServiceTests
public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty()
{
SetupEntities(
Sensor("sensor.temperature", "temperature", "22", "Temperature"),
Sensor("switch.some_switch", null, "on", "Switch")
);
Sensor("sensor.temperature", "temperature", "22", "Temperature"),
Sensor("switch.some_switch", null, "on", "Switch")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
@@ -171,10 +179,10 @@ public class BatterySensorDiscoveryServiceTests
public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty()
{
SetupEntities(
Battery("sensor.bathroom_battery", "5", "Bathroom Battery"),
Battery("sensor.bedroom_battery", "50", "Bedroom Battery"),
Battery("sensor.boiler_temp_battery", "100", "Boiler Temp Battery")
);
Battery("sensor.bathroom_battery", "5", "Bathroom Battery"),
Battery("sensor.bedroom_battery", "50", "Bedroom Battery"),
Battery("sensor.boiler_temp_battery", "100", "Boiler Temp Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
@@ -198,9 +206,9 @@ public class BatterySensorDiscoveryServiceTests
public void DiscoverLowBatterySensors_WithDuplicateSensorIds_ShouldReportEachOccurrence()
{
SetupEntities(
Battery("sensor.duplicate_battery", "2", "Duplicate Battery"),
Battery("sensor.duplicate_battery", "2", "Duplicate Battery")
);
Battery("sensor.duplicate_battery", "2", "Duplicate Battery"),
Battery("sensor.duplicate_battery", "2", "Duplicate Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
@@ -250,8 +258,10 @@ public class BatterySensorDiscoveryServiceTests
result.Should().HaveCount(7);
result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i));
result.Select(s => s.FriendlyName).Should()
.OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
result.Select(s => s.FriendlyName)
.Should()
.OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
}
#endregion