Files
HomeAssistant/PowerMonitor.Manager.Tests/OtherPowerCalculationServiceTests.cs
T
gitea_admin 24729ee267 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
2026-11-30 11:52:06 +02:00

225 lines
7.3 KiB
C#

using FluentAssertions;
using Microsoft.Extensions.Options;
using PowerMonitorManager;
using PowerMonitorManager.Models;
namespace PowerMonitor.Manager.Tests;
public class OtherPowerCalculationServiceTests
{
private static OtherPowerCalculationService CreateSut(int smoothingWindowSize = 10)
{
var options = Options.Create(new PowerMonitorOptions
{
SmoothingWindowSize = smoothingWindowSize
});
return new OtherPowerCalculationService(options);
}
#region Basic calculation
public static TheoryData<string, double, double[], double, string> CalculationCases => new()
{
{ "two devices", 341.97, [8.55, 36.93], 296.49, "ok" },
{ "no devices", 341.97, [], 341.97, "ok" },
{ "devices exceed total", 341.97, [200.0, 180.0], 0.0, "device_sum_exceeds_total" },
{ "devices equal total", 100.0, [60.0, 40.0], 0.0, "ok" },
{ "zero power, no devices", 0.0, [], 0.0, "ok" },
{ "negative total, no devices", -120.0, [], 0.0, "device_sum_exceeds_total" },
{ "negative device reading", 100.0, [150.0, -40.0], 0.0, "device_sum_exceeds_total" },
{ "very large values", 1_000_000.0, [250_000.0, 250_000.0], 500_000.0, "ok" },
{ "very small values", 0.5, [0.25], 0.25, "ok" }
};
[Theory]
[MemberData(nameof(CalculationCases))]
public void Calculate_ShouldDeriveOtherPowerFromTotalAndDevices(
string scenario,
double totalPowerWatts,
double[] deviceWatts,
double expectedOtherWatts,
string expectedDataQuality)
{
// Arrange
var sut = CreateSut(1);
var devices = deviceWatts
.Select((watts, index) => (entityId: $"sensor.device{index}_power", watts))
.ToDictionary(entry => entry.entityId, entry => entry.watts);
// Act
var result = sut.Calculate(totalPowerWatts, devices);
// Assert
result.TotalPowerWatts.Should().Be(totalPowerWatts, $"scenario: {scenario}");
result.KnownDevicesSumWatts.Should().BeApproximately(deviceWatts.Sum(), 1e-6, $"scenario: {scenario}");
result.RawOtherPowerWatts.Should().BeApproximately(expectedOtherWatts, 1e-6, $"scenario: {scenario}");
result.SmoothedOtherPowerWatts.Should().BeApproximately(expectedOtherWatts, 1e-6, $"scenario: {scenario}");
result.DataQuality.Should().Be(expectedDataQuality, $"scenario: {scenario}");
result.DevicePowerReadings.Should().HaveCount(deviceWatts.Length, $"scenario: {scenario}");
}
[Fact]
public void Calculate_ShouldIncludeAllDeviceReadingsInResult()
{
// Arrange
var sut = CreateSut(1);
var devices = PowerMonitorTestData.CreateCostDeviceReadings();
// Act
var result = sut.Calculate(PowerMonitorTestData.DefaultTotalWatts, devices);
// Assert
result.DevicePowerReadings.Should().HaveCount(2);
result.DevicePowerReadings["sensor.sonoff_100215c534_power"].Should().Be(101.0);
result.DevicePowerReadings["sensor.sonoff_10018909cb_power"].Should().Be(109.93);
}
[Fact]
public void Calculate_ShouldCopyDeviceReadingsInsteadOfAliasingThem()
{
// Arrange
var sut = CreateSut(1);
var devices = new Dictionary<string, double> { ["sensor.tv_power"] = 100.0 };
// Act
var result = sut.Calculate(150.0, devices);
devices["sensor.tv_power"] = 900.0;
// Assert
result.DevicePowerReadings["sensor.tv_power"].Should().Be(100.0);
result.KnownDevicesSumWatts.Should().Be(100.0);
}
#endregion
#region EMA smoothing
[Fact]
public void Calculate_FirstSample_ShouldReturnRawValueWithoutSmoothing()
{
// Arrange
var sut = CreateSut();
// Act
var result = sut.Calculate(341.97, new Dictionary<string, double>());
// Assert
result.SmoothedOtherPowerWatts.Should().Be(341.97);
}
[Fact]
public void Calculate_WithSmoothing_ShouldApplyExponentialMovingAverage()
{
// Arrange
var sut = CreateSut(4);
// Act
var result1 = sut.Calculate(341.97, new Dictionary<string, double>());
var result2 = sut.Calculate(115.0, new Dictionary<string, double>());
// Assert
result1.SmoothedOtherPowerWatts.Should().BeApproximately(341.97, 0.1);
result2.SmoothedOtherPowerWatts.Should().BeLessThan(341.97);
result2.SmoothedOtherPowerWatts.Should().BeGreaterThan(115.0);
}
[Fact]
public void Calculate_WithSmoothingWindowOfOne_ShouldFollowRawValueExactly()
{
// Arrange - alpha becomes 1, so the previous value has no influence.
var sut = CreateSut(1);
// Act
sut.Calculate(500.0, new Dictionary<string, double>());
var result = sut.Calculate(25.0, new Dictionary<string, double>());
// Assert
result.SmoothedOtherPowerWatts.Should().Be(25.0);
}
[Fact]
public void Calculate_ShouldDampenSingleSpike()
{
// Arrange
var sut = CreateSut();
sut.Calculate(100.0, new Dictionary<string, double>());
// Act
var result = sut.Calculate(10_000.0, new Dictionary<string, double>());
// Assert
result.RawOtherPowerWatts.Should().Be(10_000.0);
result.SmoothedOtherPowerWatts.Should().BeLessThan(result.RawOtherPowerWatts * 0.25);
result.SmoothedOtherPowerWatts.Should().BeGreaterThan(100.0);
}
[Theory]
[InlineData(2)]
[InlineData(4)]
[InlineData(5)]
[InlineData(10)]
[InlineData(20)]
public void Calculate_MultipleCallsWithSameValue_ShouldConverge(int smoothingWindowSize)
{
// Arrange
var sut = CreateSut(smoothingWindowSize);
// Act
PowerCalculationResult? result = null;
for (var i = 0; i < 200; i++) result = sut.Calculate(200.0, new Dictionary<string, double>());
// Assert
result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1);
}
[Fact]
public void Calculate_WithGeneratedSeries_ShouldNeverOvershootTheInputRange()
{
// Arrange
var sut = CreateSut(5);
var samples = PowerMonitorTestData.CreatePowerSampleSeries(50);
// Act
var results = samples.Select(sample => sut.Calculate(sample, new Dictionary<string, double>())).ToList();
// Assert
results.Should().OnlyContain(r => r.SmoothedOtherPowerWatts >= samples.Min());
results.Should().OnlyContain(r => r.SmoothedOtherPowerWatts <= samples.Max());
}
#endregion
#region Reset
[Fact]
public void Reset_ShouldClearSmoothedState()
{
// Arrange
var sut = CreateSut();
sut.Calculate(341.97, new Dictionary<string, double>());
sut.Calculate(341.97, new Dictionary<string, double>());
// Act
sut.Reset();
var result = sut.Calculate(115.0, new Dictionary<string, double>());
// Assert
result.SmoothedOtherPowerWatts.Should().BeApproximately(115.0, 0.1);
}
[Fact]
public void Reset_WhenCalledBeforeAnyCalculation_ShouldKeepFirstSampleRaw()
{
// Arrange
var sut = CreateSut();
// Act
sut.Reset();
var result = sut.Calculate(42.5, new Dictionary<string, double>());
// Assert
result.SmoothedOtherPowerWatts.Should().Be(42.5);
}
#endregion
}