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
This commit is contained in:
2026-11-30 11:52:06 +02:00
parent cf8c9434c8
commit 24729ee267
165 changed files with 2513 additions and 2470 deletions
@@ -1,34 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<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.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<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.11.0" />
<PackageReference Include="Moq" Version="4.21.0" />
</ItemGroup>
<ItemGroup>
<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.12.0"/>
<PackageReference Include="xunit" Version="2.9.3"/>
<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.11.0"/>
<PackageReference Include="Moq" Version="4.21.0"/>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj" />
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj"/>
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj"/>
</ItemGroup>
</Project>
@@ -8,150 +8,17 @@ using NetDaemon.HassModel.Entities;
namespace BatteryMonitor.Manager.Tests;
/// <summary>
/// Shared, deterministic builders and datasets used by the BatteryMonitor tests.
/// Keeping entity/state construction and generated inputs here means the test
/// classes only describe the scenario under test.
/// Shared, deterministic builders and datasets used by the BatteryMonitor tests.
/// Keeping entity/state construction and generated inputs here means the test
/// classes only describe the scenario under test.
/// </summary>
internal static class BatteryMonitorTestData
{
private const string DefaultFriendlyName = "Battery Device";
/// <summary>
/// Describes one entity exposed through <see cref="IHaContext.GetAllEntities"/>.
/// </summary>
public sealed record EntitySpec
{
public required string EntityId { get; init; }
public string? State { get; init; } = "50";
public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass;
public string? FriendlyName { get; init; } = DefaultFriendlyName;
/// <summary>When false the context returns no <see cref="EntityState"/> for the entity.</summary>
public bool HasState { get; init; } = true;
}
/// <summary>A battery device-class sensor.</summary>
public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName)
{
return new EntitySpec
{
EntityId = entityId,
State = state,
FriendlyName = friendlyName
};
}
/// <summary>A sensor with an arbitrary (or missing) device class.</summary>
public static EntitySpec Sensor(string entityId, string? deviceClass, string? state, string? friendlyName = DefaultFriendlyName)
{
return new EntitySpec
{
EntityId = entityId,
DeviceClass = deviceClass,
State = state,
FriendlyName = friendlyName
};
}
public static EntityState CreateEntityState(EntitySpec spec)
{
var attributes = new Dictionary<string, object?>(StringComparer.Ordinal);
if (spec.DeviceClass is not null)
{
attributes["device_class"] = spec.DeviceClass;
}
if (spec.FriendlyName is not null)
{
attributes["friendly_name"] = spec.FriendlyName;
}
return new EntityState
{
State = spec.State,
AttributesJson = JsonSerializer.SerializeToElement(attributes)
};
}
/// <summary>
/// Wires <see cref="IHaContext.GetState"/> and <see cref="IHaContext.GetAllEntities"/>
/// on the mock, exposing the entities in declaration order.
/// </summary>
public static void ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities)
{
var entityList = new List<Entity>(entities.Length);
foreach (var spec in entities)
{
if (spec.HasState)
{
haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
}
entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
}
haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
}
public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
{
return new BatterySensorInfo
{
EntityId = entityId,
FriendlyName = friendlyName ?? entityId,
BatteryLevel = batteryLevel
};
}
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
{
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
}
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
{
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
}
/// <summary>
/// Generates battery sensors with every integer level in <c>0..count-1</c>.
/// </summary>
public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
{
return
[
.. Enumerable.Range(0, count)
.Select(i => Battery(
$"sensor.generated_battery_{i:D3}",
i.ToString(CultureInfo.InvariantCulture),
$"Generated Battery {i:D3}"))
];
}
/// <summary>
/// Generates notification devices with deterministic, non-monotonic levels so
/// ordering behaviour is exercised over more than a handful of rows.
/// </summary>
public static IReadOnlyList<BatterySensorInfo> CreateGeneratedSensorInfos(int count)
{
return
[
.. Enumerable.Range(0, count)
.Select(i => CreateSensorInfo(
$"sensor.generated_{i:D3}",
i * 37 % 101,
$"Generated Device {i:D3}"))
];
}
/// <summary>
/// (threshold, state, expected) rows straddling the strict <c>level &lt; threshold</c>
/// boundary, including zero/negative thresholds and int min/max thresholds.
/// (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()
{
@@ -183,8 +50,8 @@ internal static class BatteryMonitorTestData
};
/// <summary>
/// States that must never produce a <see cref="BatterySensorInfo"/>, including
/// whitespace/malformed strings and a null state.
/// States that must never produce a <see cref="BatterySensorInfo" />, including
/// whitespace/malformed strings and a null state.
/// </summary>
public static TheoryData<string?> UnusableStateRows { get; } =
[
@@ -203,9 +70,121 @@ internal static class BatteryMonitorTestData
null
];
/// <summary>Device counts used to exercise notification payload generation.</summary>
public static TheoryData<int> NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
/// <summary>A battery device-class sensor.</summary>
public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName)
{
return new EntitySpec
{
EntityId = entityId,
State = state,
FriendlyName = friendlyName
};
}
/// <summary>A sensor with an arbitrary (or missing) device class.</summary>
public static EntitySpec Sensor(string entityId, string? deviceClass, string? state,
string? friendlyName = DefaultFriendlyName)
{
return new EntitySpec
{
EntityId = entityId,
DeviceClass = deviceClass,
State = state,
FriendlyName = friendlyName
};
}
public static EntityState CreateEntityState(EntitySpec spec)
{
var attributes = new Dictionary<string, object?>(StringComparer.Ordinal);
if (spec.DeviceClass is not null) attributes["device_class"] = spec.DeviceClass;
if (spec.FriendlyName is not null) attributes["friendly_name"] = spec.FriendlyName;
return new EntityState
{
State = spec.State,
AttributesJson = JsonSerializer.SerializeToElement(attributes)
};
}
/// <summary>
/// Cross-product of every excluded keyword (lower and upper case) plus
/// non-excluded look-alikes that must not be filtered.
/// Wires <see cref="IHaContext.GetState" /> and <see cref="IHaContext.GetAllEntities" />
/// on the mock, exposing the entities in declaration order.
/// </summary>
public static void ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities)
{
var entityList = new List<Entity>(entities.Length);
foreach (var spec in entities)
{
if (spec.HasState) haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
}
haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
}
public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
{
return new BatterySensorInfo
{
EntityId = entityId,
FriendlyName = friendlyName ?? entityId,
BatteryLevel = batteryLevel
};
}
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
{
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
}
public static List<BatterySensorInfo> CreateSensorInfos(
params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
{
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
}
/// <summary>
/// Generates battery sensors with every integer level in <c>0..count-1</c>.
/// </summary>
public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
{
return
[
.. Enumerable.Range(0, count)
.Select(i => Battery(
$"sensor.generated_battery_{i:D3}",
i.ToString(CultureInfo.InvariantCulture),
$"Generated Battery {i:D3}"))
];
}
/// <summary>
/// Generates notification devices with deterministic, non-monotonic levels so
/// ordering behaviour is exercised over more than a handful of rows.
/// </summary>
public static IReadOnlyList<BatterySensorInfo> CreateGeneratedSensorInfos(int count)
{
return
[
.. Enumerable.Range(0, count)
.Select(i => CreateSensorInfo(
$"sensor.generated_{i:D3}",
i * 37 % 101,
$"Generated Device {i:D3}"))
];
}
/// <summary>
/// Cross-product of every excluded keyword (lower and upper case) plus
/// non-excluded look-alikes that must not be filtered.
/// </summary>
public static TheoryData<string, bool> ExcludedEntityIdRows()
{
@@ -229,6 +208,20 @@ internal static class BatteryMonitorTestData
return data;
}
/// <summary>Device counts used to exercise notification payload generation.</summary>
public static TheoryData<int> NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
}
/// <summary>
/// Describes one entity exposed through <see cref="IHaContext.GetAllEntities" />.
/// </summary>
public sealed record EntitySpec
{
public required string EntityId { get; init; }
public string? State { get; init; } = "50";
public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass;
public string? FriendlyName { get; init; } = DefaultFriendlyName;
/// <summary>When false the context returns no <see cref="EntityState" /> for the entity.</summary>
public bool HasState { get; init; } = true;
}
}
@@ -1,11 +1,11 @@
using System.Text.Json;
using BatteryMonitor.Models;
using BatteryMonitorManager;
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;
@@ -36,10 +36,10 @@ public class BatteryNotificationServiceTests
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)))
]);
[
.. Enumerable.Range(0, deviceCount)
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
]);
var sut = CreateSut();
sut.NotifyLowBattery(devices);
@@ -139,10 +139,7 @@ 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());
@@ -222,7 +219,8 @@ 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));
@@ -279,4 +277,4 @@ public class BatteryNotificationServiceTests
}
#endregion
}
}
@@ -1,11 +1,11 @@
using System.Globalization;
using BatteryMonitor.Models;
using BatteryMonitorManager;
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;
@@ -25,6 +25,17 @@ public class BatterySensorDiscoveryServiceTests
ConfigureHaContext(_haContextMock, entities);
}
#region IsExcludedDevice
[Theory]
[MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))]
public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
{
BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
}
#endregion
#region Discovery
[Fact]
@@ -77,7 +88,8 @@ public class BatterySensorDiscoveryServiceTests
[InlineData("sensor.no_device_class", null)]
[InlineData("sensorx.bathroom_battery", "battery")]
[InlineData("switch.bathroom_battery", "battery")]
public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId, string? deviceClass)
public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId,
string? deviceClass)
{
SetupEntities(
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
@@ -111,7 +123,8 @@ public class BatterySensorDiscoveryServiceTests
public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor()
{
SetupEntities(
new EntitySpec { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
new EntitySpec
{ EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
);
@@ -124,7 +137,8 @@ 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"));
@@ -133,10 +147,7 @@ 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));
@@ -239,7 +250,8 @@ 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
@@ -279,15 +291,4 @@ public class BatterySensorDiscoveryServiceTests
}
#endregion
#region IsExcludedDevice
[Theory]
[MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))]
public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
{
BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
}
#endregion
}
}