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 CalculationCases => new() { { "two devices", 341.97, [8.55, 36.93], 296.49, "ok" }, { "no devices", 341.97, Array.Empty(), 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, Array.Empty(), 0.0, "ok" }, { "negative total, no devices", -120.0, Array.Empty(), 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(smoothingWindowSize: 1); var devices = deviceWatts .Select((watts, index) => (entityId: $"sensor.device{index}_power", watts: 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(smoothingWindowSize: 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(smoothingWindowSize: 1); var devices = new Dictionary { ["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(smoothingWindowSize: 10); // Act var result = sut.Calculate(341.97, new Dictionary()); // Assert result.SmoothedOtherPowerWatts.Should().Be(341.97); } [Fact] public void Calculate_WithSmoothing_ShouldApplyExponentialMovingAverage() { // Arrange var sut = CreateSut(smoothingWindowSize: 4); // Act var result1 = sut.Calculate(341.97, new Dictionary()); var result2 = sut.Calculate(115.0, new Dictionary()); // 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(smoothingWindowSize: 1); // Act sut.Calculate(500.0, new Dictionary()); var result = sut.Calculate(25.0, new Dictionary()); // Assert result.SmoothedOtherPowerWatts.Should().Be(25.0); } [Fact] public void Calculate_ShouldDampenSingleSpike() { // Arrange var sut = CreateSut(smoothingWindowSize: 10); sut.Calculate(100.0, new Dictionary()); // Act var result = sut.Calculate(10_000.0, new Dictionary()); // 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()); } // Assert result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1); } [Fact] public void Calculate_WithGeneratedSeries_ShouldNeverOvershootTheInputRange() { // Arrange var sut = CreateSut(smoothingWindowSize: 5); var samples = PowerMonitorTestData.CreatePowerSampleSeries(50); // Act var results = samples.Select(sample => sut.Calculate(sample, new Dictionary())).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(smoothingWindowSize: 10); sut.Calculate(341.97, new Dictionary()); sut.Calculate(341.97, new Dictionary()); // Act sut.Reset(); var result = sut.Calculate(115.0, new Dictionary()); // Assert result.SmoothedOtherPowerWatts.Should().BeApproximately(115.0, 0.1); } [Fact] public void Reset_WhenCalledBeforeAnyCalculation_ShouldKeepFirstSampleRaw() { // Arrange var sut = CreateSut(smoothingWindowSize: 10); // Act sut.Reset(); var result = sut.Calculate(42.5, new Dictionary()); // Assert result.SmoothedOtherPowerWatts.Should().Be(42.5); } #endregion }