Add shared test data builders and Qodana configuration

- Extract per-monitor *TestData helper classes and rework tests to use them
- Add boiler run-time tracker abstraction (implementation pending)
- Drop unused NordPool init/update-result types and stale PLAN.md
- Add qodana.yaml with the inspection set to keep the analysis focused
This commit is contained in:
2026-11-29 21:30:13 +02:00
parent 1152462765
commit 5777e641f6
79 changed files with 7162 additions and 3196 deletions
@@ -5,164 +5,303 @@ namespace PowerMonitor.Manager.Tests;
public class CostAccumulatorTests
{
public enum CostWindow
{
FifteenMinutes,
Hour,
Day,
Month
}
#region AddCost and GetSnapshot
[Fact]
public void GetSnapshot_WhenNew_ShouldReturnZeroCosts()
{
var sut = new CostAccumulator(new DateTime(2026, 3, 17, 10, 0, 0));
// Arrange
var sut = new CostAccumulator(PowerMonitorTestData.FixedNow);
// Act
var snapshot = sut.GetSnapshot();
// Assert
snapshot.Cost15Min.Should().Be(0);
snapshot.Cost1Hour.Should().Be(0);
snapshot.CostDaily.Should().Be(0);
snapshot.CostMonthly.Should().Be(0);
snapshot.Previous15Min.Should().Be(0);
snapshot.Previous1Hour.Should().Be(0);
snapshot.PreviousDaily.Should().Be(0);
snapshot.PreviousMonthly.Should().Be(0);
snapshot.PartialWindow.Should().BeTrue();
}
[Fact]
public void AddCost_ShouldAccumulateInAllWindows()
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
// Arrange
var now = PowerMonitorTestData.FixedNow;
var sut = new CostAccumulator(now);
// Act
sut.AddCost(0.05, now.AddSeconds(15));
sut.AddCost(0.03, now.AddSeconds(30));
// Assert
var snapshot = sut.GetSnapshot();
snapshot.Cost15Min.Should().BeApproximately(0.08, 0.0001);
snapshot.Cost1Hour.Should().BeApproximately(0.08, 0.0001);
snapshot.CostDaily.Should().BeApproximately(0.08, 0.0001);
snapshot.CostMonthly.Should().BeApproximately(0.08, 0.0001);
snapshot.Cost15Min.Should().BeApproximately(0.08, 1e-9);
snapshot.Cost1Hour.Should().BeApproximately(0.08, 1e-9);
snapshot.CostDaily.Should().BeApproximately(0.08, 1e-9);
snapshot.CostMonthly.Should().BeApproximately(0.08, 1e-9);
snapshot.PartialWindow.Should().BeTrue();
}
#endregion
#region 15-minute window resets
[Fact]
public void AddCost_When15MinWindowCrosses_ShouldResetAndStorePrevious()
public void AddCost_WithGeneratedSeriesInSameWindow_ShouldSumEveryIncrement()
{
var now = new DateTime(2026, 3, 17, 10, 14, 0);
// Arrange
var now = PowerMonitorTestData.FixedNow;
var sut = new CostAccumulator(now);
sut.AddCost(0.10, now);
var increments = PowerMonitorTestData.CreatePowerSampleSeries(50)
.Select(watts => watts / 100_000.0)
.ToArray();
sut.AddCost(0.02, new DateTime(2026, 3, 17, 10, 15, 0));
// Act
foreach (var increment in increments)
{
sut.AddCost(increment, now.AddSeconds(1));
}
// Assert
var expected = increments.Sum();
var snapshot = sut.GetSnapshot();
snapshot.Cost15Min.Should().BeApproximately(0.02, 0.0001);
snapshot.Previous15Min.Should().BeApproximately(0.10, 0.0001);
snapshot.PartialWindow.Should().BeFalse();
snapshot.Cost15Min.Should().BeApproximately(expected, 1e-9);
snapshot.Cost1Hour.Should().BeApproximately(expected, 1e-9);
snapshot.CostDaily.Should().BeApproximately(expected, 1e-9);
snapshot.CostMonthly.Should().BeApproximately(expected, 1e-9);
snapshot.PartialWindow.Should().BeTrue();
}
#endregion
#region Hourly window resets
[Fact]
public void AddCost_WhenHourWindowCrosses_ShouldResetAndStorePrevious()
public void AddCost_WithNegativeIncrement_ShouldReduceEveryWindow()
{
var now = new DateTime(2026, 3, 17, 10, 59, 0);
// Arrange - a meter that corrects itself downwards must not be clamped by the accumulator.
var now = PowerMonitorTestData.FixedNow;
var sut = new CostAccumulator(now);
sut.AddCost(0.50, now);
sut.AddCost(0.01, new DateTime(2026, 3, 17, 11, 0, 0));
// Act
sut.AddCost(-0.20, now.AddSeconds(15));
// Assert
var snapshot = sut.GetSnapshot();
snapshot.Cost1Hour.Should().BeApproximately(0.01, 0.0001);
snapshot.Previous1Hour.Should().BeApproximately(0.50, 0.0001);
snapshot.Cost15Min.Should().BeApproximately(0.30, 1e-9);
snapshot.Cost1Hour.Should().BeApproximately(0.30, 1e-9);
snapshot.CostDaily.Should().BeApproximately(0.30, 1e-9);
snapshot.CostMonthly.Should().BeApproximately(0.30, 1e-9);
}
[Fact]
public void AddCost_WithVeryLargeIncrement_ShouldPreserveTheValue()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var sut = new CostAccumulator(now);
// Act
sut.AddCost(1_000_000.0, now);
// Assert
sut.GetSnapshot().CostMonthly.Should().Be(1_000_000.0);
}
[Fact]
public void AddCost_WithinSameWindows_ShouldNotPopulatePreviousValues()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var sut = new CostAccumulator(now);
// Act
sut.AddCost(0.01, now);
sut.AddCost(0.01, now.AddSeconds(15));
sut.AddCost(0.01, now.AddMinutes(14));
// Assert
var snapshot = sut.GetSnapshot();
snapshot.Previous15Min.Should().Be(0);
snapshot.Previous1Hour.Should().Be(0);
snapshot.PreviousDaily.Should().Be(0);
snapshot.PreviousMonthly.Should().Be(0);
snapshot.PartialWindow.Should().BeTrue();
}
#endregion
#region Daily window resets
#region Window rollovers
[Fact]
public void AddCost_WhenDayChanges_ShouldResetDailyAndStorePrevious()
public static IEnumerable<object[]> WindowRolloverCases =>
[
["15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0), new DateTime(2026, 3, 17, 10, 15, 0), 0.10, 0.02],
["15 minute slot ends across the hour", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 11, 0, 0), 0.10, 0.02],
["15 minute slot ends at midnight", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 23, 45, 0), new DateTime(2026, 3, 18, 0, 0, 0), 0.10, 0.02],
["15 minute slot ends on DST spring forward", CostWindow.FifteenMinutes, new DateTime(2026, 3, 29, 2, 45, 0), new DateTime(2026, 3, 29, 3, 0, 0), 0.10, 0.02],
["15 minute slot ends on DST fall back", CostWindow.FifteenMinutes, new DateTime(2026, 10, 25, 2, 45, 0), new DateTime(2026, 10, 25, 3, 0, 0), 0.10, 0.02],
["hour ends", CostWindow.Hour, new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 0, 0), 0.50, 0.01],
["hour ends at midnight", CostWindow.Hour, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), 0.50, 0.01],
["hour ends on DST spring forward", CostWindow.Hour, new DateTime(2026, 3, 29, 2, 59, 0), new DateTime(2026, 3, 29, 3, 0, 0), 0.50, 0.01],
["hour ends on DST fall back", CostWindow.Hour, new DateTime(2026, 10, 25, 2, 59, 0), new DateTime(2026, 10, 25, 3, 0, 0), 0.50, 0.01],
["day changes", CostWindow.Day, new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), 5.00, 0.01],
["day changes at month end", CostWindow.Day, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), 5.00, 0.01],
["day changes at year end", CostWindow.Day, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), 5.00, 0.01],
["month changes", CostWindow.Month, new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), 100.00, 0.01],
["year changes", CostWindow.Month, new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), 100.00, 0.01],
["month changes on leap day", CostWindow.Month, new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), 100.00, 0.01]
];
[Theory]
[MemberData(nameof(WindowRolloverCases))]
public void AddCost_WhenWindowRollsOver_ShouldResetCurrentAndKeepPrevious(
string scenario,
CostWindow window,
DateTime firstTimestamp,
DateTime rolloverTimestamp,
double beforeRolloverCost,
double afterRolloverCost)
{
var now = new DateTime(2026, 3, 17, 23, 59, 0);
var sut = new CostAccumulator(now);
sut.AddCost(5.00, now);
// Arrange
var sut = new CostAccumulator(firstTimestamp);
sut.AddCost(beforeRolloverCost, firstTimestamp);
sut.AddCost(0.01, new DateTime(2026, 3, 18, 0, 0, 0));
// Act
sut.AddCost(afterRolloverCost, rolloverTimestamp);
// Assert
var snapshot = sut.GetSnapshot();
snapshot.CostDaily.Should().BeApproximately(0.01, 0.0001);
snapshot.PreviousDaily.Should().BeApproximately(5.00, 0.0001);
GetCurrent(snapshot, window).Should().BeApproximately(afterRolloverCost, 1e-9, $"scenario: {scenario}");
GetPrevious(snapshot, window).Should().BeApproximately(beforeRolloverCost, 1e-9, $"scenario: {scenario}");
snapshot.PartialWindow.Should().BeFalse($"scenario: {scenario}");
}
#endregion
[Fact]
public void AddCost_WhenAllWindowBoundariesCoincide_ShouldResetEveryWindow()
{
// Arrange
var lastSampleTime = new DateTime(2026, 3, 31, 23, 59, 0);
var rolloverTime = new DateTime(2026, 4, 1, 0, 0, 0);
var sut = new CostAccumulator(lastSampleTime);
sut.AddCost(12.34, lastSampleTime);
#region Monthly window resets
// Act
sut.AddCost(0.56, rolloverTime);
// Assert
var snapshot = sut.GetSnapshot();
snapshot.Cost15Min.Should().BeApproximately(0.56, 1e-9);
snapshot.Cost1Hour.Should().BeApproximately(0.56, 1e-9);
snapshot.CostDaily.Should().BeApproximately(0.56, 1e-9);
snapshot.CostMonthly.Should().BeApproximately(0.56, 1e-9);
snapshot.Previous15Min.Should().BeApproximately(12.34, 1e-9);
snapshot.Previous1Hour.Should().BeApproximately(12.34, 1e-9);
snapshot.PreviousDaily.Should().BeApproximately(12.34, 1e-9);
snapshot.PreviousMonthly.Should().BeApproximately(12.34, 1e-9);
}
[Fact]
public void AddCost_WhenMonthChanges_ShouldResetMonthlyAndStorePrevious()
public void AddCost_AfterFirstRollover_ShouldKeepPartialWindowFalse()
{
var now = new DateTime(2026, 3, 31, 23, 59, 0);
// Arrange
var now = PowerMonitorTestData.FixedNow;
var sut = new CostAccumulator(now);
sut.AddCost(100.00, now);
sut.AddCost(0.10, now);
sut.AddCost(0.01, new DateTime(2026, 4, 1, 0, 0, 0));
// Act
sut.AddCost(0.10, now.AddMinutes(15));
sut.AddCost(0.10, now.AddMinutes(30));
var snapshot = sut.GetSnapshot();
snapshot.CostMonthly.Should().BeApproximately(0.01, 0.0001);
snapshot.PreviousMonthly.Should().BeApproximately(100.00, 0.0001);
// Assert
sut.GetSnapshot().PartialWindow.Should().BeFalse();
}
#endregion
#region Window boundary detection (static methods)
[Theory]
[InlineData(10, 0, 10, 14, false)]
[InlineData(10, 0, 10, 15, true)]
[InlineData(10, 14, 10, 15, true)]
[InlineData(10, 29, 10, 30, true)]
[InlineData(10, 44, 10, 45, true)]
[InlineData(10, 45, 10, 59, false)]
[InlineData(10, 45, 11, 0, true)]
public void IsNew15MinWindow_ShouldDetectBoundary(int lastHour, int lastMin, int nowHour, int nowMin, bool expected)
{
var lastReset = new DateTime(2026, 3, 17, lastHour, lastMin, 0);
var now = new DateTime(2026, 3, 17, nowHour, nowMin, 0);
public static IEnumerable<object[]> FifteenMinuteBoundaryCases =>
[
["same slot, first second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false],
["same slot, last second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 14, 59), false],
["slot boundary 14 -> 15", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 15, 0), true],
["slot boundary 29 -> 30", new DateTime(2026, 3, 17, 10, 29, 0), new DateTime(2026, 3, 17, 10, 30, 0), true],
["slot boundary 44 -> 45", new DateTime(2026, 3, 17, 10, 44, 0), new DateTime(2026, 3, 17, 10, 45, 0), true],
["same slot, late", new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 10, 59, 59), false],
["hour boundary", new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 11, 0, 0), true],
["midnight boundary", new DateTime(2026, 3, 17, 23, 45, 0), new DateTime(2026, 3, 18, 0, 0, 0), true],
["clock moved backwards", new DateTime(2026, 3, 17, 10, 45, 0), new DateTime(2026, 3, 17, 10, 44, 0), true],
["DST spring forward", new DateTime(2026, 3, 29, 2, 45, 0), new DateTime(2026, 3, 29, 3, 0, 0), true]
];
CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected);
[Theory]
[MemberData(nameof(FifteenMinuteBoundaryCases))]
public void IsNew15MinWindow_ShouldDetectBoundary(string scenario, DateTime lastReset, DateTime now, bool expected)
{
CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
}
[Theory]
[InlineData(10, 10, false)]
[InlineData(10, 11, true)]
[InlineData(23, 0, true)]
public void IsNewHourWindow_ShouldDetectBoundary(int lastHour, int nowHour, bool expected)
{
var lastReset = new DateTime(2026, 3, 17, lastHour, 0, 0);
var now = new DateTime(2026, 3, 17, nowHour, 0, 0);
public static IEnumerable<object[]> HourBoundaryCases =>
[
["same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false],
["same hour, later minute", new DateTime(2026, 3, 17, 10, 10, 0), new DateTime(2026, 3, 17, 10, 11, 0), false],
["same hour, last minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 59, 59), false],
["next hour", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 11, 0, 0), true],
["next hour, late minute", new DateTime(2026, 3, 17, 10, 59, 0), new DateTime(2026, 3, 17, 11, 59, 0), true],
["midnight boundary", new DateTime(2026, 3, 17, 23, 0, 0), new DateTime(2026, 3, 18, 0, 0, 0), true],
["clock moved backwards", new DateTime(2026, 3, 17, 11, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), true],
["DST spring forward", new DateTime(2026, 3, 29, 2, 0, 0), new DateTime(2026, 3, 29, 3, 0, 0), true],
["DST fall back", new DateTime(2026, 10, 25, 2, 0, 0), new DateTime(2026, 10, 25, 3, 0, 0), true]
];
CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected);
[Theory]
[MemberData(nameof(HourBoundaryCases))]
public void IsNewHourWindow_ShouldDetectBoundary(string scenario, DateTime lastReset, DateTime now, bool expected)
{
CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
}
[Theory]
[InlineData(17, 17, false)]
[InlineData(17, 18, true)]
public void IsNewDayWindow_ShouldDetectBoundary(int lastDay, int nowDay, bool expected)
{
var lastReset = new DateTime(2026, 3, lastDay, 0, 0, 0);
var now = new DateTime(2026, 3, nowDay, 0, 0, 0);
public static IEnumerable<object[]> DayBoundaryCases =>
[
["same timestamp", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 0, 0, 0), false],
["same day, last second", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 23, 59, 59), false],
["next day", new DateTime(2026, 3, 17, 23, 59, 0), new DateTime(2026, 3, 18, 0, 0, 0), true],
["month rollover", new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), true],
["year rollover", new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), true],
["leap day rollover", new DateTime(2028, 2, 28, 23, 59, 0), new DateTime(2028, 2, 29, 0, 0, 0), true],
["DST spring forward day", new DateTime(2026, 3, 28, 23, 59, 0), new DateTime(2026, 3, 29, 0, 0, 0), true],
["DST fall back day", new DateTime(2026, 10, 24, 23, 59, 0), new DateTime(2026, 10, 25, 0, 0, 0), true]
];
CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected);
[Theory]
[MemberData(nameof(DayBoundaryCases))]
public void IsNewDayWindow_ShouldDetectBoundary(string scenario, DateTime lastReset, DateTime now, bool expected)
{
CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
}
[Theory]
[InlineData(3, 3, false)]
[InlineData(3, 4, true)]
[InlineData(12, 1, true)]
public void IsNewMonthWindow_ShouldDetectBoundary(int lastMonth, int nowMonth, bool expected)
{
var lastReset = new DateTime(2026, lastMonth, 1, 0, 0, 0);
var now = new DateTime(2026, nowMonth, 1, 0, 0, 0);
public static IEnumerable<object[]> MonthBoundaryCases =>
[
["same month, first day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 1, 0, 0, 0), false],
["same month, last day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 59), false],
["next month", new DateTime(2026, 3, 31, 23, 59, 0), new DateTime(2026, 4, 1, 0, 0, 0), true],
["clock moved into previous month", new DateTime(2026, 4, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 0), true],
["year rollover", new DateTime(2026, 12, 31, 23, 59, 0), new DateTime(2027, 1, 1, 0, 0, 0), true],
["leap day rollover", new DateTime(2028, 2, 29, 23, 59, 0), new DateTime(2028, 3, 1, 0, 0, 0), true]
];
CostAccumulator.IsNewMonthWindow(now, lastReset).Should().Be(expected);
[Theory]
[MemberData(nameof(MonthBoundaryCases))]
public void IsNewMonthWindow_ShouldDetectBoundary(string scenario, DateTime lastReset, DateTime now, bool expected)
{
CostAccumulator.IsNewMonthWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
}
#endregion
@@ -172,12 +311,14 @@ public class CostAccumulatorTests
[Fact]
public async Task AddCost_ConcurrentAccess_ShouldNotLoseData()
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
// Arrange
var now = PowerMonitorTestData.FixedNow;
var sut = new CostAccumulator(now);
const double incrementPerCall = 0.001;
const int callsPerThread = 1000;
const int threadCount = 10;
// Act
var tasks = Enumerable.Range(0, threadCount)
.Select(_ => Task.Run(() =>
{
@@ -190,10 +331,29 @@ public class CostAccumulatorTests
await Task.WhenAll(tasks);
// Assert
var snapshot = sut.GetSnapshot();
var expected = incrementPerCall * callsPerThread * threadCount;
snapshot.CostMonthly.Should().BeApproximately(expected, 0.0001);
}
#endregion
private static double GetCurrent(CostSnapshot snapshot, CostWindow window) => window switch
{
CostWindow.FifteenMinutes => snapshot.Cost15Min,
CostWindow.Hour => snapshot.Cost1Hour,
CostWindow.Day => snapshot.CostDaily,
CostWindow.Month => snapshot.CostMonthly,
_ => throw new ArgumentOutOfRangeException(nameof(window))
};
private static double GetPrevious(CostSnapshot snapshot, CostWindow window) => window switch
{
CostWindow.FifteenMinutes => snapshot.Previous15Min,
CostWindow.Hour => snapshot.Previous1Hour,
CostWindow.Day => snapshot.PreviousDaily,
CostWindow.Month => snapshot.PreviousMonthly,
_ => throw new ArgumentOutOfRangeException(nameof(window))
};
}
@@ -18,103 +18,181 @@ public class OtherPowerCalculationServiceTests
#region Basic calculation
[Fact]
public void Calculate_ShouldReturnOtherAsTotalMinusDevices()
public static IEnumerable<object[]> CalculationCases =>
[
["two devices", 341.97, new[] { 8.55, 36.93 }, 296.49, "ok"],
["no devices", 341.97, System.Array.Empty<double>(), 341.97, "ok"],
["devices exceed total", 341.97, new[] { 200.0, 180.0 }, 0.0, "device_sum_exceeds_total"],
["devices equal total", 100.0, new[] { 60.0, 40.0 }, 0.0, "ok"],
["zero power, no devices", 0.0, System.Array.Empty<double>(), 0.0, "ok"],
["negative total, no devices", -120.0, System.Array.Empty<double>(), 0.0, "device_sum_exceeds_total"],
["negative device reading", 100.0, new[] { 150.0, -40.0 }, 0.0, "device_sum_exceeds_total"],
["very large values", 1_000_000.0, new[] { 250_000.0, 250_000.0 }, 500_000.0, "ok"],
["very small values", 0.5, new[] { 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 = new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 8.55,
["sensor.sonoff_10018909cb_power"] = 36.93
};
var devices = deviceWatts
.Select((watts, index) => ($"sensor.device{index}_power", watts))
.ToDictionary(entry => entry.Item1, entry => entry.Item2);
var result = sut.Calculate(341.97, devices);
// Act
var result = sut.Calculate(totalPowerWatts, devices);
result.TotalPowerWatts.Should().Be(341.97);
result.KnownDevicesSumWatts.Should().BeApproximately(45.48, 0.01);
result.RawOtherPowerWatts.Should().BeApproximately(296.49, 0.01);
result.DataQuality.Should().Be("ok");
}
[Fact]
public void Calculate_WhenDevicesSumExceedsTotal_ShouldClampToZero()
{
var sut = CreateSut(smoothingWindowSize: 1);
var devices = new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 200.0,
["sensor.sonoff_10018909cb_power"] = 180.0
};
var result = sut.Calculate(341.97, devices);
result.RawOtherPowerWatts.Should().Be(0);
result.SmoothedOtherPowerWatts.Should().Be(0);
result.DataQuality.Should().Be("device_sum_exceeds_total");
}
[Fact]
public void Calculate_WithNoDevices_ShouldReturnTotalAsOther()
{
var sut = CreateSut(smoothingWindowSize: 1);
var devices = new Dictionary<string, double>();
var result = sut.Calculate(341.97, devices);
result.RawOtherPowerWatts.Should().Be(341.97);
result.KnownDevicesSumWatts.Should().Be(0);
// 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 = new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 8.55,
["sensor.sonoff_10018909cb_power"] = 36.93
};
var devices = PowerMonitorTestData.CreateCostDeviceReadings();
var result = sut.Calculate(341.97, devices);
// Act
var result = sut.Calculate(PowerMonitorTestData.DefaultTotalWatts, devices);
// Assert
result.DevicePowerReadings.Should().HaveCount(2);
result.DevicePowerReadings["sensor.sonoff_100215c534_power"].Should().Be(8.55);
result.DevicePowerReadings["sensor.sonoff_10018909cb_power"].Should().Be(36.93);
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<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(smoothingWindowSize: 10);
// 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(smoothingWindowSize: 4);
var devices = new Dictionary<string, double>();
// Act
var result1 = sut.Calculate(341.97, devices);
result1.SmoothedOtherPowerWatts.Should().BeApproximately(341.97, 0.1);
var result2 = sut.Calculate(115.0, devices);
// 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_MultipleCallsWithSameValue_ShouldConverge()
public void Calculate_WithSmoothingWindowOfOne_ShouldFollowRawValueExactly()
{
var sut = CreateSut(smoothingWindowSize: 5);
// Arrange - alpha becomes 1, so the previous value has no influence.
var sut = CreateSut(smoothingWindowSize: 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(smoothingWindowSize: 10);
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);
var devices = new Dictionary<string, double>();
// Act
PowerCalculationResult? result = null;
for (var i = 0; i < 50; i++)
for (var i = 0; i < 200; i++)
{
result = sut.Calculate(200.0, devices);
}
// 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);
var devices = new Dictionary<string, double>();
// Act
var results = samples.Select(sample => sut.Calculate(sample, devices)).ToList();
// Assert
results.Should().OnlyContain(r => r.SmoothedOtherPowerWatts >= samples.Min());
results.Should().OnlyContain(r => r.SmoothedOtherPowerWatts <= samples.Max());
}
#endregion
#region Reset
@@ -122,16 +200,33 @@ public class OtherPowerCalculationServiceTests
[Fact]
public void Reset_ShouldClearSmoothedState()
{
// Arrange
var sut = CreateSut(smoothingWindowSize: 10);
var devices = new Dictionary<string, double>();
sut.Calculate(341.97, devices);
sut.Calculate(341.97, devices);
// Act
sut.Reset();
var result = sut.Calculate(115.0, devices);
// 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<string, double>());
// Assert
result.SmoothedOtherPowerWatts.Should().Be(42.5);
}
#endregion
}
@@ -7,62 +7,66 @@ namespace PowerMonitor.Manager.Tests;
public class PowerCostCalculationServiceTests
{
private readonly PowerCostCalculationService _sut = new();
private const double DefaultTotalWatts = 341.97;
private const double DefaultSmoothedOtherWatts = 131.04;
private const double DefaultPricePerKwh = 0.1791;
private static PowerCalculationResult CreateResult(
double totalWatts = DefaultTotalWatts,
double smoothedOtherWatts = DefaultSmoothedOtherWatts,
Dictionary<string, double>? deviceReadings = null)
public enum CostBucket
{
var readings = deviceReadings ?? new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 101.0,
["sensor.sonoff_10018909cb_power"] = 109.93
};
return new PowerCalculationResult
{
TotalPowerWatts = totalWatts,
KnownDevicesSumWatts = readings.Values.Sum(),
RawOtherPowerWatts = smoothedOtherWatts,
SmoothedOtherPowerWatts = smoothedOtherWatts,
DataQuality = "ok",
DevicePowerReadings = readings
};
Total,
Other
}
private readonly PowerCostCalculationService _sut = new();
#region CalculateCostIncrement
[Fact]
public void CalculateCostIncrement_ShouldComputeCorrectCost()
{
var cost = PowerCostCalculationService.CalculateCostIncrement(
powerWatts: 341.97,
pricePerKwh: 0.1791,
pollIntervalSeconds: PowerMonitorConsts.DefaultPollIntervalSeconds);
public static IEnumerable<object[]> CostIncrementCases =>
[
["default polling interval", 341.97, 0.1791, 15, 0.0002551951125],
["one kilowatt for one hour", 1000.0, 1.0, PowerMonitorConsts.SecondsPerHour, 1.0],
["limit load for one minute", 5500.0, 0.25, 60, 0.0229166666666667],
["very large load", 1_000_000.0, 0.5, 900, 125.0],
["negative power", -500.0, 0.2, PowerMonitorConsts.SecondsPerHour, -0.1],
["zero power", 0.0, 0.1791, 15, 0.0],
["zero price", 341.97, 0.0, 15, 0.0],
["zero interval", 1000.0, 0.2, 0, 0.0],
["tiny values", 0.001, 0.0001, 1, 2.77777777777778e-14]
];
var expected = (341.97 / PowerMonitorConsts.WattsPerKilowatt)
* 0.1791
* ((double)PowerMonitorConsts.DefaultPollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
cost.Should().BeApproximately(expected, 0.000001);
[Theory]
[MemberData(nameof(CostIncrementCases))]
public void CalculateCostIncrement_ShouldComputeExpectedCost(
string scenario,
double powerWatts,
double pricePerKwh,
int pollIntervalSeconds,
double expectedCost)
{
// Act
var cost = PowerCostCalculationService.CalculateCostIncrement(powerWatts, pricePerKwh, pollIntervalSeconds);
// Assert
var precision = expectedCost == 0 ? 1e-12 : Math.Abs(expectedCost) * 1e-9;
cost.Should().BeApproximately(expectedCost, precision, $"scenario: {scenario}");
}
[Fact]
public void CalculateCostIncrement_WithZeroPower_ShouldReturnZero()
public void CalculateCostIncrement_ForGeneratedPowerSeries_ShouldBeProportionalToPower()
{
var cost = PowerCostCalculationService.CalculateCostIncrement(0, DefaultPricePerKwh, 15);
cost.Should().Be(0);
}
// Arrange
const double pricePerKwh = 0.25;
const int pollIntervalSeconds = 15;
var samples = PowerMonitorTestData.CreatePowerSampleSeries(25);
var unitCost = PowerCostCalculationService.CalculateCostIncrement(1_000.0, pricePerKwh, pollIntervalSeconds);
[Fact]
public void CalculateCostIncrement_WithZeroPrice_ShouldReturnZero()
{
var cost = PowerCostCalculationService.CalculateCostIncrement(341.97, 0, 15);
cost.Should().Be(0);
// Act
var costs = samples
.Select(watts => PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds))
.ToArray();
// Assert
costs.Should().BeInAscendingOrder("every generated sample is larger than the previous one");
for (var i = 0; i < samples.Count; i++)
{
costs[i].Should().BeApproximately(samples[i] / 1_000.0 * unitCost, 1e-15);
}
}
#endregion
@@ -72,41 +76,53 @@ public class PowerCostCalculationServiceTests
[Fact]
public void RecordCosts_ShouldCreateTotalAndOtherSnapshots()
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult();
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now);
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
var totalSnapshot = _sut.GetTotalCostSnapshot();
totalSnapshot.CostDaily.Should().BeGreaterThan(0);
// Assert
var expectedTotal = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts, PowerMonitorTestData.DefaultPricePerKwh);
var otherSnapshot = _sut.GetOtherCostSnapshot();
otherSnapshot.CostDaily.Should().BeGreaterThan(0);
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expectedTotal, 1e-12);
_sut.GetOtherCostSnapshot().CostDaily.Should().BeApproximately(expectedOther, 1e-12);
_sut.GetTotalCostSnapshot().PartialWindow.Should().BeTrue();
}
[Fact]
public void RecordCosts_ShouldCreateDeviceSnapshots()
[Theory]
[InlineData("sensor.sonoff_100215c534_power")]
[InlineData("sensor.sonoff_10018909cb_power")]
public void RecordCosts_ShouldCreatePositiveDeviceSnapshotForEveryReading(string entityId)
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult();
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now);
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
var ac = _sut.GetDeviceCostSnapshot("sensor.sonoff_100215c534_power");
ac.CostDaily.Should().BeGreaterThan(0);
var induction = _sut.GetDeviceCostSnapshot("sensor.sonoff_10018909cb_power");
induction.CostDaily.Should().BeGreaterThan(0);
// Assert
var snapshot = _sut.GetDeviceCostSnapshot(entityId);
var expected = ExpectedCost(result.DevicePowerReadings[entityId], PowerMonitorTestData.DefaultPricePerKwh);
snapshot.CostDaily.Should().BeApproximately(expected, 1e-12);
snapshot.CostDaily.Should().BeGreaterThan(0);
snapshot.PartialWindow.Should().BeTrue();
}
[Fact]
public void RecordCosts_TotalCostShouldBeHigherThanOtherCost()
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult(totalWatts: DefaultTotalWatts, smoothedOtherWatts: DefaultSmoothedOtherWatts);
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now);
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
// Assert
var total = _sut.GetTotalCostSnapshot();
var other = _sut.GetOtherCostSnapshot();
total.CostDaily.Should().BeGreaterThan(other.CostDaily);
@@ -115,78 +131,334 @@ public class PowerCostCalculationServiceTests
[Fact]
public void RecordCosts_MultipleCalls_ShouldAccumulate()
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult();
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now);
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
var firstCost = _sut.GetTotalCostSnapshot().CostDaily;
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now.AddSeconds(15));
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15));
var secondCost = _sut.GetTotalCostSnapshot().CostDaily;
// Assert
secondCost.Should().BeApproximately(firstCost * 2, 0.000001);
}
[Fact]
public void RecordCosts_NewDeviceAppearing_ShouldCreateAccumulator()
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result1 = CreateResult(deviceReadings: new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 101.0
});
// Arrange
var now = PowerMonitorTestData.FixedNow;
var firstResult = PowerMonitorTestData.CreateCalculation(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
_sut.RecordCosts(result1, DefaultPricePerKwh, 15, now);
// Act
_sut.RecordCosts(firstResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(1);
var result2 = CreateResult(deviceReadings: new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 101.0,
["sensor.sonoff_10018909cb_power"] = 109.93
});
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15));
_sut.RecordCosts(result2, DefaultPricePerKwh, 15, now.AddSeconds(15));
// Assert
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
}
[Fact]
public void RecordCosts_WhenDeviceDisappears_ShouldKeepItsPreviousAccumulator()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15, now);
var beforeDisappearance = _sut.GetDeviceCostSnapshot("sensor.sonoff_10018909cb_power").CostDaily;
// Act
var singleDeviceResult = PowerMonitorTestData.CreateCalculation(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
_sut.RecordCosts(singleDeviceResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15));
// Assert
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
_sut.GetDeviceCostSnapshot("sensor.sonoff_10018909cb_power").CostDaily.Should().Be(beforeDisappearance);
}
[Fact]
public void RecordCosts_WithNoDeviceReadings_ShouldStillTrackTotals()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation(deviceReadings: new Dictionary<string, double>());
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
// Assert
_sut.GetAllDeviceCostSnapshots().Should().BeEmpty();
_sut.GetTotalCostSnapshot().CostDaily.Should().BeGreaterThan(0);
}
[Fact]
public void RecordCosts_WithZeroPower_ShouldCreateZeroCostSnapshots()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation(
totalWatts: 0,
smoothedOtherWatts: 0,
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0)));
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
// Assert
_sut.GetTotalCostSnapshot().CostDaily.Should().Be(0);
_sut.GetOtherCostSnapshot().CostDaily.Should().Be(0);
_sut.GetDeviceCostSnapshot("sensor.sonoff_100215c534_power").CostDaily.Should().Be(0);
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(1);
}
[Fact]
public void RecordCosts_WithNegativeDevicePower_ShouldProduceNegativeDeviceCost()
{
// Arrange - a sensor glitch must flow through the pure cost math unchanged.
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.glitch_power", -500.0)));
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
// Assert
var expected = ExpectedCost(-500.0, PowerMonitorTestData.DefaultPricePerKwh);
_sut.GetDeviceCostSnapshot("sensor.glitch_power").CostDaily.Should().BeApproximately(expected, 1e-12);
_sut.GetDeviceCostSnapshot("sensor.glitch_power").CostDaily.Should().BeNegative();
}
[Fact]
public void RecordCosts_WithZeroPollInterval_ShouldTrackDevicesWithoutCost()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
// Act
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 0, now);
// Assert
_sut.GetTotalCostSnapshot().CostDaily.Should().Be(0);
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
_sut.GetAllDeviceCostSnapshots().Values.Should().OnlyContain(snapshot => snapshot.CostMonthly == 0);
}
[Fact]
public void RecordCosts_When15MinWindowCrosses_ShouldResetAndStorePrevious()
{
// Arrange
var firstTimestamp = new DateTime(2026, 3, 17, 10, 14, 0);
var rolloverTimestamp = new DateTime(2026, 3, 17, 10, 15, 0);
var result = PowerMonitorTestData.CreateCalculation();
var expected = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, firstTimestamp);
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, rolloverTimestamp);
// Assert
var snapshot = _sut.GetTotalCostSnapshot();
snapshot.Cost15Min.Should().BeApproximately(expected, 1e-12);
snapshot.Previous15Min.Should().BeApproximately(expected, 1e-12);
snapshot.PartialWindow.Should().BeFalse();
}
[Fact]
public void RecordCosts_WhenDayChanges_ShouldResetDailyWindow()
{
// Arrange
var beforeMidnight = new DateTime(2026, 3, 17, 23, 50, 0);
var afterMidnight = new DateTime(2026, 3, 18, 0, 5, 0);
var result = PowerMonitorTestData.CreateCalculation();
var expected = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, beforeMidnight);
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, afterMidnight);
// Assert
var snapshot = _sut.GetTotalCostSnapshot();
snapshot.CostDaily.Should().BeApproximately(expected, 1e-12);
snapshot.PreviousDaily.Should().BeApproximately(expected, 1e-12);
}
[Fact]
public void RecordCosts_WhenMonthChanges_ShouldResetMonthlyWindow()
{
// Arrange
var beforeMonthEnd = new DateTime(2026, 3, 31, 23, 59, 0);
var afterMonthStart = new DateTime(2026, 4, 1, 0, 0, 0);
var result = PowerMonitorTestData.CreateCalculation();
var expected = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, beforeMonthEnd);
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, afterMonthStart);
// Assert
var snapshot = _sut.GetTotalCostSnapshot();
snapshot.CostMonthly.Should().BeApproximately(expected, 1e-12);
snapshot.PreviousMonthly.Should().BeApproximately(expected, 1e-12);
}
[Fact]
public void RecordCosts_ForGeneratedQuarterHourDay_ShouldResetEverySlot()
{
// Arrange
const double pricePerKwh = 0.2;
var timestamps = PowerMonitorTestData.CreateSampleTimestamps(PowerMonitorTestData.FixedDayStart, 96);
var wattSamples = PowerMonitorTestData.CreatePowerSampleSeries(96);
var expectedPerSlot = timestamps
.Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds))
.ToArray();
// Act
for (var slot = 0; slot < timestamps.Count; slot++)
{
var result = PowerMonitorTestData.CreateCalculation(
totalWatts: wattSamples[slot],
smoothedOtherWatts: wattSamples[slot] / 2,
deviceReadings: new Dictionary<string, double>());
_sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]);
}
// Assert
var snapshot = _sut.GetTotalCostSnapshot();
snapshot.Cost15Min.Should().BeApproximately(expectedPerSlot[^1], 1e-12);
snapshot.Previous15Min.Should().BeApproximately(expectedPerSlot[^2], 1e-12);
snapshot.CostDaily.Should().BeApproximately(expectedPerSlot.Sum(), 1e-9);
snapshot.PreviousDaily.Should().Be(0);
}
[Fact]
public void RecordCosts_ForGeneratedHourlyDay_ShouldAccumulateDailyAndMonthlyTotals()
{
// Arrange
const int pollIntervalSeconds = PowerMonitorConsts.SecondsPerHour;
var windows = PowerMonitorTestData.CreateHourlyTariffWindows(PowerMonitorTestData.FixedDayStart);
var expectedPerHour = new List<double>();
// Act
foreach (var (start, pricePerKwh) in windows)
{
var watts = 500.0 + (start.Hour * 125.0);
var result = PowerMonitorTestData.CreateCalculation(
totalWatts: watts,
smoothedOtherWatts: watts / 4,
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2)));
_sut.RecordCosts(result, pricePerKwh, pollIntervalSeconds, start);
expectedPerHour.Add(ExpectedCost(watts, pricePerKwh, pollIntervalSeconds));
}
// Assert
var snapshot = _sut.GetTotalCostSnapshot();
snapshot.CostDaily.Should().BeApproximately(expectedPerHour.Sum(), 1e-9);
snapshot.CostMonthly.Should().BeApproximately(expectedPerHour.Sum(), 1e-9);
snapshot.Cost1Hour.Should().BeApproximately(expectedPerHour[^1], 1e-12);
snapshot.Previous1Hour.Should().BeApproximately(expectedPerHour[^2], 1e-12);
}
#endregion
#region Price management
[Fact]
public void RecordCosts_WithValidPrice_ShouldUpdateLastKnownPrice()
public void InitialPrice_ShouldBeZeroAndLive()
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult();
_sut.RecordCosts(result, 0.2492, 15, now);
_sut.LastKnownPrice.Should().Be(0.2492);
_sut.LastKnownPrice.Should().Be(0);
_sut.PriceSource.Should().Be("live");
}
[Fact]
public void RecordCosts_WithZeroPrice_ShouldUseFallback()
[Theory]
[InlineData(0.0001)]
[InlineData(0.1791)]
[InlineData(0.2492)]
[InlineData(1.5)]
[InlineData(100.0)]
public void RecordCosts_WithPositivePrice_ShouldStoreLivePrice(double price)
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult();
// Act
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), price, 15, PowerMonitorTestData.FixedNow);
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now);
_sut.RecordCosts(result, 0, 15, now.AddSeconds(15));
_sut.LastKnownPrice.Should().Be(DefaultPricePerKwh);
// Assert
_sut.LastKnownPrice.Should().Be(price);
_sut.PriceSource.Should().Be("live");
}
[Fact]
public void SetPrice_ShouldUpdatePriceAndMarkAsStale()
[Theory]
[InlineData(0.0)]
[InlineData(-0.0001)]
[InlineData(-5.0)]
public void RecordCosts_WithNonPositivePrice_ShouldFallBackToLastKnownPrice(double invalidPrice)
{
_sut.SetPrice(0.1891);
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
_sut.LastKnownPrice.Should().Be(0.1891);
// Act
_sut.RecordCosts(result, invalidPrice, 15, now.AddSeconds(15));
// Assert
_sut.LastKnownPrice.Should().Be(PowerMonitorTestData.DefaultPricePerKwh);
_sut.PriceSource.Should().Be("live");
var expected = 2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12);
}
[Fact]
public void RecordCosts_WithZeroPriceAndNoPriorPrice_ShouldRecordZeroCost()
{
// Arrange
var result = PowerMonitorTestData.CreateCalculation();
// Act
_sut.RecordCosts(result, 0, 15, PowerMonitorTestData.FixedNow);
// Assert
_sut.LastKnownPrice.Should().Be(0);
_sut.GetTotalCostSnapshot().CostDaily.Should().Be(0);
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
}
[Theory]
[InlineData(0.1891)]
[InlineData(0.0)]
[InlineData(-1.25)]
[InlineData(12.5)]
public void SetPrice_ShouldUpdatePriceAndMarkAsStale(double price)
{
// Act
_sut.SetPrice(price);
// Assert
_sut.LastKnownPrice.Should().Be(price);
_sut.PriceSource.Should().Be("stale");
}
[Fact]
public void RecordCosts_AfterSetPrice_WithZeroPrice_ShouldKeepStalePriceAndSource()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
_sut.SetPrice(0.5);
// Act
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), 0, 15, now);
// Assert
_sut.LastKnownPrice.Should().Be(0.5);
_sut.PriceSource.Should().Be("stale");
var expected = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, 0.5);
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12);
}
#endregion
#region GetAllDeviceCostSnapshots
@@ -197,11 +469,20 @@ public class PowerCostCalculationServiceTests
_sut.GetAllDeviceCostSnapshots().Should().BeEmpty();
}
[Fact]
public void GetDeviceCostSnapshot_UnknownDevice_ShouldReturnEmptySnapshot()
[Theory]
[InlineData("sensor.unknown")]
[InlineData("")]
[InlineData(" ")]
[InlineData("SENSOR.SONOFF_100215C534_POWER")]
public void GetDeviceCostSnapshot_ForUnknownDevice_ShouldReturnEmptySnapshot(string entityId)
{
var snapshot = _sut.GetDeviceCostSnapshot("sensor.unknown");
// Act
var snapshot = _sut.GetDeviceCostSnapshot(entityId);
// Assert
snapshot.Cost15Min.Should().Be(0);
snapshot.CostDaily.Should().Be(0);
snapshot.CostMonthly.Should().Be(0);
snapshot.PartialWindow.Should().BeTrue();
}
@@ -209,19 +490,21 @@ public class PowerCostCalculationServiceTests
#region Snapshot defaults
[Fact]
public void GetTotalCostSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot()
[Theory]
[InlineData(CostBucket.Total)]
[InlineData(CostBucket.Other)]
public void GetSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot(CostBucket bucket)
{
var snapshot = _sut.GetTotalCostSnapshot();
snapshot.CostDaily.Should().Be(0);
snapshot.PartialWindow.Should().BeTrue();
}
// Act
var snapshot = bucket == CostBucket.Total
? _sut.GetTotalCostSnapshot()
: _sut.GetOtherCostSnapshot();
[Fact]
public void GetOtherCostSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot()
{
var snapshot = _sut.GetOtherCostSnapshot();
// Assert
snapshot.Cost15Min.Should().Be(0);
snapshot.Cost1Hour.Should().Be(0);
snapshot.CostDaily.Should().Be(0);
snapshot.CostMonthly.Should().Be(0);
snapshot.PartialWindow.Should().BeTrue();
}
@@ -232,23 +515,26 @@ public class PowerCostCalculationServiceTests
[Fact]
public async Task RecordCosts_ConcurrentAccess_ShouldNotLoseData()
{
var now = new DateTime(2026, 3, 17, 10, 0, 0);
var result = CreateResult(totalWatts: DefaultTotalWatts, smoothedOtherWatts: DefaultSmoothedOtherWatts);
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
const int callsPerThread = 100;
const int threadCount = 10;
// Act
var tasks = Enumerable.Range(0, threadCount)
.Select(_ => Task.Run(() =>
{
for (var i = 0; i < callsPerThread; i++)
{
_sut.RecordCosts(result, DefaultPricePerKwh, 15, now.AddSeconds(1));
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1));
}
}))
.ToArray();
await Task.WhenAll(tasks);
// Assert
var total = _sut.GetTotalCostSnapshot();
total.CostDaily.Should().BeGreaterThan(0);
@@ -257,4 +543,12 @@ public class PowerCostCalculationServiceTests
}
#endregion
private static double ExpectedCost(
double powerWatts,
double pricePerKwh,
int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds) =>
powerWatts / PowerMonitorConsts.WattsPerKilowatt
* pricePerKwh
* ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
}
@@ -1,3 +1,4 @@
using System.Globalization;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -12,8 +13,8 @@ namespace PowerMonitor.Manager.Tests;
public class PowerLimitEnforcementServiceTests
{
private const string BoilerSwitch = "switch.sonoff_1002230e32";
private const string AutoManagement = "switch.boilermonitor_auto_management";
private const string BoilerSwitch = PowerMonitorTestData.BoilerSwitchEntityId;
private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId;
private readonly Mock<IHaContext> _haContextMock;
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock;
@@ -24,16 +25,8 @@ public class PowerLimitEnforcementServiceTests
{
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<PowerLimitEnforcementService>>();
_timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow);
_options = new PowerMonitorOptions
{
EnforceLimitEnabled = true,
PowerLimitWatts = 5500,
RecoverySeconds = 600,
LimitCooldownSeconds = 30,
EnforceSwitchOffEntityIds = [BoilerSwitch],
PauseAndRestoreEntityIds = [AutoManagement]
};
_timeProvider = new FakeTimeProvider(PowerMonitorTestData.FixedUtcNow);
_options = PowerMonitorTestData.CreateLimitEnforcementOptions();
}
private PowerLimitEnforcementService CreateSut() =>
@@ -43,63 +36,96 @@ public class PowerLimitEnforcementServiceTests
Options.Create(_options),
_timeProvider);
private static bool IsTurnOffCall(string domain, string service, string entityId) =>
domain == "switch" && service == "turn_off";
private void VerifyNoServiceCalls() =>
_haContextMock.Verify(
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Never);
private static bool IsTurnOnCall(string domain, string service, string entityId) =>
domain == "switch" && service == "turn_on";
private void VerifyTurnOff(string entityId, int expectedCalls) =>
_haContextMock.Verify(
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
Times.Exactly(expectedCalls));
[Fact]
public void EnforceLimit_WhenDisabled_ShouldNotCallAnyService()
private void VerifyTurnOn(string entityId, int expectedCalls) =>
_haContextMock.Verify(
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
Times.Exactly(expectedCalls));
private void VerifyNotificationCreated(int expectedCalls) =>
_haContextMock.Verify(
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Exactly(expectedCalls));
private void VerifyNotificationDismissed(int expectedCalls) =>
_haContextMock.Verify(
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Exactly(expectedCalls));
#region EnforceLimit
[Theory]
[InlineData(0.0)]
[InlineData(5500.0)]
[InlineData(6000.0)]
[InlineData(1_000_000.0)]
public void EnforceLimit_WhenDisabled_ShouldNotCallAnyService(double powerWatts)
{
// Arrange
_options.EnforceLimitEnabled = false;
var sut = CreateSut();
sut.EnforceLimit(6000);
// Act
sut.EnforceLimit(powerWatts);
_haContextMock.Verify(
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.Never);
// Assert
VerifyNoServiceCalls();
sut.IsLimitActive.Should().BeFalse();
}
[Fact]
public void EnforceLimit_WhenPowerBelowLimit_ShouldNotEnforce()
[Theory]
[InlineData(-1000.0)]
[InlineData(0.0)]
[InlineData(0.5)]
[InlineData(2749.99)]
[InlineData(5499.99)]
[InlineData(5500.0)]
public void EnforceLimit_WhenPowerAtOrBelowLimit_ShouldNotEnforce(double powerWatts)
{
// Arrange
var sut = CreateSut();
sut.EnforceLimit(5000);
// Act
sut.EnforceLimit(powerWatts);
sut.IsLimitActive.Should().BeFalse();
_haContextMock.Verify(
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.Never);
// Assert
sut.IsLimitActive.Should().BeFalse("power equal to the limit must not trigger (strict greater-than)");
VerifyNoServiceCalls();
}
[Fact]
public void EnforceLimit_WhenPowerExceedsLimit_ShouldTurnOffSwitchesAndPauseMonitors()
[Theory]
[InlineData(5500.01)]
[InlineData(6000.0)]
[InlineData(15_000.0)]
[InlineData(1_000_000.0)]
public void EnforceLimit_WhenPowerExceedsLimit_ShouldTurnOffSwitchesAndPauseMonitors(double powerWatts)
{
// Arrange
var sut = CreateSut();
sut.EnforceLimit(6000);
// Act
sut.EnforceLimit(powerWatts);
// Assert
sut.IsLimitActive.Should().BeTrue();
// turn_off called for boiler switch + auto_management
_haContextMock.Verify(
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
Times.Once);
_haContextMock.Verify(
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
Times.Once);
// notification created
_haContextMock.Verify(
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Once);
VerifyTurnOff(BoilerSwitch, 1);
VerifyTurnOff(AutoManagement, 1);
VerifyNotificationCreated(1);
}
[Fact]
public void EnforceLimit_WhenBreached_ShouldTurnOffBoilerBeforeAutoManagement()
{
// Arrange
var calls = new List<(string domain, string service, string? entityId)>();
_haContextMock
.Setup(x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()))
@@ -107,8 +133,10 @@ public class PowerLimitEnforcementServiceTests
calls.Add((d, s, t?.EntityIds?.FirstOrDefault())));
var sut = CreateSut();
// Act
sut.EnforceLimit(6000);
// Assert
var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList();
turnOffCalls.Should().HaveCount(2);
turnOffCalls[0].entityId.Should().Be(BoilerSwitch, "boiler switch must be turned off before auto_management (race-safe order)");
@@ -116,230 +144,304 @@ public class PowerLimitEnforcementServiceTests
}
[Fact]
public void EnforceLimit_WhenAlreadyActiveAndBeforeRecoveryTime_ShouldDoNothing()
public void EnforceLimit_WithMultipleConfiguredEntities_ShouldTurnOffEveryEntityInConfiguredOrder()
{
// Arrange
_options.EnforceSwitchOffEntityIds = ["switch.high_load_a", "switch.high_load_b"];
_options.PauseAndRestoreEntityIds = ["switch.monitor_c"];
var calls = new List<string?>();
_haContextMock
.Setup(x => x.CallService(It.IsAny<string>(), "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()))
.Callback<string, string, ServiceTarget?, object?>((_, _, target, _) =>
calls.Add(target?.EntityIds?.FirstOrDefault()));
var sut = CreateSut();
sut.EnforceLimit(6000);
_haContextMock.Invocations.Clear();
// advance less than recovery
_timeProvider.Advance(TimeSpan.FromMinutes(5));
sut.EnforceLimit(5000);
// Act
sut.EnforceLimit(7000);
// Assert
calls.Should().Equal("switch.high_load_a", "switch.high_load_b", "switch.monitor_c");
sut.IsLimitActive.Should().BeTrue();
_haContextMock.Verify(
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.Never);
}
[Fact]
public void EnforceLimit_WhenRecoveryTimeReachedAndPowerBelowLimit_ShouldRestoreMonitorsAndNotTurnBoilerOn()
public void EnforceLimit_WithNoConfiguredEntities_ShouldStillNotifyAndActivate()
{
// Arrange
_options.EnforceSwitchOffEntityIds = [];
_options.PauseAndRestoreEntityIds = [];
var sut = CreateSut();
// Act
sut.EnforceLimit(6000);
_haContextMock.Invocations.Clear();
_timeProvider.Advance(TimeSpan.FromSeconds(601));
sut.EnforceLimit(4000);
sut.IsLimitActive.Should().BeFalse();
// auto_management turned back ON
// Assert
sut.IsLimitActive.Should().BeTrue();
VerifyNotificationCreated(1);
_haContextMock.Verify(
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
Times.Once);
// boiler switch should NOT be turned back on
_haContextMock.Verify(
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
x => x.CallService("switch", It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Never);
// notification dismissed
_haContextMock.Verify(
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Once);
}
[Fact]
public void EnforceLimit_WhenRecoveryTimeReachedButPowerStillHigh_ShouldStayEnforcedAndResetTimer()
#endregion
#region Recovery
public static IEnumerable<object[]> RecoveryCases =>
[
["not yet due", 300, 3000.0, true, 0],
["one second before due", 599, 3000.0, true, 0],
["exactly due", 600, 3000.0, false, 1],
["just under limit", 601, 5499.99, false, 1],
["zero power", 900, 0.0, false, 1],
["negative power", 601, -10.0, false, 1],
["exactly at limit stays enforced", 601, 5500.0, true, 0],
["above limit stays enforced", 601, 5800.0, true, 0],
["very high power stays enforced", 601, 25_000.0, true, 0]
];
[Theory]
[MemberData(nameof(RecoveryCases))]
public void EnforceLimit_AfterEnforcement_ShouldEvaluateRecovery(
string scenario,
int secondsAfterEnforcement,
double powerWatts,
bool expectedLimitActive,
int expectedRecoveryActions)
{
// Arrange
var sut = CreateSut();
sut.EnforceLimit(6000);
_haContextMock.Invocations.Clear();
_timeProvider.Advance(TimeSpan.FromSeconds(601));
sut.EnforceLimit(5800);
// Act
_timeProvider.Advance(TimeSpan.FromSeconds(secondsAfterEnforcement));
sut.EnforceLimit(powerWatts);
sut.IsLimitActive.Should().BeTrue();
// no restore, no dismiss
_haContextMock.Verify(
x => x.CallService("switch", "turn_on", It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.Never);
_haContextMock.Verify(
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Never);
// Assert
sut.IsLimitActive.Should().Be(expectedLimitActive, $"scenario: {scenario}");
VerifyTurnOn(AutoManagement, expectedRecoveryActions);
VerifyTurnOn(BoilerSwitch, 0);
VerifyNotificationDismissed(expectedRecoveryActions);
}
[Fact]
public void EnforceLimit_WhenRecoveryTimeReachedButPowerStillHigh_ShouldAllowAnotherRecoveryCheckAfterWait()
{
// Arrange
var sut = CreateSut();
sut.EnforceLimit(6000);
// first recovery check - still high, timer resets
// Act - first recovery check finds power still high and resets the timer
_timeProvider.Advance(TimeSpan.FromSeconds(601));
sut.EnforceLimit(5800);
sut.IsLimitActive.Should().BeTrue();
// immediately after - not enough time, no-op
sut.EnforceLimit(3000);
var immediatelyAfter = sut;
immediatelyAfter.EnforceLimit(3000);
// Assert - not enough time has passed for another check
sut.IsLimitActive.Should().BeTrue();
// after another full wait - power dropped, recovers
// Act - after another full wait the power has dropped
_timeProvider.Advance(TimeSpan.FromSeconds(601));
sut.EnforceLimit(3000);
// Assert
sut.IsLimitActive.Should().BeFalse();
VerifyTurnOn(AutoManagement, 1);
}
[Fact]
public void EnforceLimit_WhenCooldownActive_ShouldNotReEnforce()
#endregion
#region Cooldown
[Theory]
[InlineData(0, false)]
[InlineData(29, false)]
[InlineData(30, true)]
[InlineData(31, true)]
[InlineData(600, true)]
public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery, bool expectedLimitActive)
{
// Arrange
var sut = CreateSut();
sut.EnforceLimit(6000);
sut.IsLimitActive.Should().BeTrue();
// recover so we can re-trigger
_timeProvider.Advance(TimeSpan.FromSeconds(601));
sut.EnforceLimit(3000);
sut.IsLimitActive.Should().BeFalse();
_haContextMock.Invocations.Clear();
// immediately breach again - within cooldown, should NOT enforce
// Act
_timeProvider.Advance(TimeSpan.FromSeconds(secondsAfterRecovery));
sut.EnforceLimit(6000);
sut.IsLimitActive.Should().BeFalse("cooldown should block immediate re-enforcement");
_haContextMock.Verify(
x => x.CallService("switch", "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.Never);
// Assert
sut.IsLimitActive.Should().Be(expectedLimitActive);
if (expectedLimitActive)
{
VerifyTurnOff(BoilerSwitch, 1);
VerifyTurnOff(AutoManagement, 1);
VerifyNotificationCreated(1);
}
else
{
VerifyNoServiceCalls();
}
}
[Fact]
public void EnforceLimit_WhenCooldownPassed_ShouldReEnforce()
public void EnforceLimit_ImmediatelyAfterManualReset_ShouldNotReEnforceWithinCooldown()
{
// Arrange
var sut = CreateSut();
sut.EnforceLimit(6000);
_timeProvider.Advance(TimeSpan.FromSeconds(601));
sut.EnforceLimit(3000);
sut.IsLimitActive.Should().BeFalse();
// wait past cooldown
_timeProvider.Advance(TimeSpan.FromSeconds(31));
sut.TriggerLimitBreach();
sut.ResetLimitBreach();
_haContextMock.Invocations.Clear();
// Act
sut.EnforceLimit(6000);
sut.IsLimitActive.Should().BeTrue();
_haContextMock.Verify(
x => x.CallService("switch", "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.AtLeastOnce);
// Assert
sut.IsLimitActive.Should().BeFalse("the manual reset starts the cooldown window");
VerifyNoServiceCalls();
}
#endregion
#region BuildLimitMessage
[Theory]
[InlineData("typical breach", 6.0, 5.5, "6.00 kW", "5.5 kW")]
[InlineData("rounds current to two decimals", 5.999, 5.549, "6.00 kW", "5.5 kW")]
[InlineData("zero current", 0.0, 5.5, "0.00 kW", "5.5 kW")]
[InlineData("negative current", -1.0, 5.5, "-1.00 kW", "5.5 kW")]
[InlineData("large values", 123.456, 100.0, "123.46 kW", "100.0 kW")]
public void BuildLimitMessage_ShouldContainCurrentAndLimitInKw(
string scenario,
double currentKw,
double limitKw,
string expectedCurrentText,
string expectedLimitText)
{
// Act
var message = PowerLimitEnforcementService.BuildLimitMessage(currentKw, limitKw);
// Assert
message.Should().Contain(expectedCurrentText, $"scenario: {scenario}");
message.Should().Contain(expectedLimitText, $"scenario: {scenario}");
message.Should().Contain("exceeded the limit");
}
[Fact]
public void EnforceLimit_WhenExactlyAtLimit_ShouldNotEnforce()
public void BuildLimitMessage_WithCommaDecimalCulture_ShouldStillUseInvariantFormatting()
{
var sut = CreateSut();
// Arrange
var originalCulture = CultureInfo.CurrentCulture;
sut.EnforceLimit(5500);
try
{
CultureInfo.CurrentCulture = new CultureInfo("de-DE");
sut.IsLimitActive.Should().BeFalse("power equal to limit should not trigger (strict greater-than)");
_haContextMock.Verify(
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.Never);
// Act
var message = PowerLimitEnforcementService.BuildLimitMessage(6.0, 5.5);
// Assert
message.Should().Contain("6.00 kW");
message.Should().Contain("5.5 kW");
}
finally
{
CultureInfo.CurrentCulture = originalCulture;
}
}
[Fact]
public void BuildLimitMessage_ShouldContainCurrentAndLimitInKw()
{
var message = PowerLimitEnforcementService.BuildLimitMessage(6.0, 5.5);
#endregion
message.Should().Contain("6.00 kW");
message.Should().Contain("5.5 kW");
}
#region Debug triggers
[Fact]
public void TriggerLimitBreach_WhenNotActive_ShouldEnforceRegardlessOfPower()
{
// Arrange
var sut = CreateSut();
// Act
sut.TriggerLimitBreach();
// Assert
sut.IsLimitActive.Should().BeTrue();
_haContextMock.Verify(
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
Times.Once);
_haContextMock.Verify(
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
Times.Once);
_haContextMock.Verify(
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Once);
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Exactly(3));
VerifyTurnOff(BoilerSwitch, 1);
VerifyTurnOff(AutoManagement, 1);
VerifyNotificationCreated(1);
}
[Fact]
public void TriggerLimitBreach_WhenAlreadyActive_ShouldDoNothing()
{
// Arrange
var sut = CreateSut();
sut.TriggerLimitBreach();
_haContextMock.Invocations.Clear();
// Act
sut.TriggerLimitBreach();
_haContextMock.Verify(
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.Never);
// Assert
VerifyNoServiceCalls();
}
[Fact]
public void ResetLimitBreach_WhenActive_ShouldRecoverWithoutWaiting()
{
// Arrange
var sut = CreateSut();
sut.TriggerLimitBreach();
_haContextMock.Invocations.Clear();
// Act
sut.ResetLimitBreach();
// Assert
sut.IsLimitActive.Should().BeFalse();
_haContextMock.Verify(
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
Times.Once);
_haContextMock.Verify(
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Once);
// boiler switch should NOT be turned on
_haContextMock.Verify(
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
Times.Never);
VerifyTurnOn(AutoManagement, 1);
VerifyTurnOn(BoilerSwitch, 0);
VerifyNotificationDismissed(1);
}
[Fact]
public void ResetLimitBreach_WhenNotActive_ShouldDoNothing()
{
// Arrange
var sut = CreateSut();
// Act
sut.ResetLimitBreach();
_haContextMock.Verify(
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.Never);
// Assert
VerifyNoServiceCalls();
}
[Fact]
public void TriggerLimitBreach_WhenDisabled_ShouldStillEnforce()
{
// Arrange
_options.EnforceLimitEnabled = false;
var sut = CreateSut();
// Act
sut.TriggerLimitBreach();
// Assert
sut.IsLimitActive.Should().BeTrue("debug trigger bypasses EnforceLimitEnabled so the button always works");
_haContextMock.Verify(
x => x.CallService("switch", "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.AtLeastOnce);
VerifyTurnOff(BoilerSwitch, 1);
VerifyNotificationCreated(1);
}
}
#endregion
}
@@ -8,19 +8,19 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="8.0.0">
<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.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<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.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.4.0" />
<PackageReference Include="FluentAssertions" Version="8.11.0" />
<PackageReference Include="Moq" Version="4.21.0" />
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="11.0.1" />
</ItemGroup>
<ItemGroup>
@@ -10,6 +10,24 @@ namespace PowerMonitor.Manager.Tests;
public class PowerMonitorEntityServiceTests
{
private static readonly string[] SystemEntityIds =
[
"sensor.powermonitor_total_power",
"sensor.powermonitor_total_cost_15min",
"sensor.powermonitor_total_cost_1h",
"sensor.powermonitor_total_cost_daily",
"sensor.powermonitor_total_cost_monthly",
"sensor.powermonitor_other_power",
"sensor.powermonitor_other_cost_15min",
"sensor.powermonitor_other_cost_1h",
"sensor.powermonitor_other_cost_daily",
"sensor.powermonitor_other_cost_monthly",
"binary_sensor.powermonitor_anomaly",
"sensor.powermonitor_status",
"button.powermonitor_rediscover_sensors",
"button.powermonitor_trigger_limit_breach"
];
private readonly Mock<IEntityManager> _entityManagerMock;
private readonly Mock<ILogger<PowerMonitorEntityService>> _loggerMock;
private readonly PowerMonitorEntityService _sut;
@@ -18,6 +36,10 @@ public class PowerMonitorEntityServiceTests
{
_entityManagerMock = new Mock<IEntityManager>();
_loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>())).Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())).Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())).Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>())).Returns(Task.CompletedTask);
_sut = new PowerMonitorEntityService(_entityManagerMock.Object, _loggerMock.Object);
}
@@ -26,77 +48,138 @@ public class PowerMonitorEntityServiceTests
[Fact]
public void GetSystemEntitiesList_ShouldReturnAll14SystemEntities()
{
// Act
var result = _sut.GetSystemEntitiesList();
// Assert
result.Should().HaveCount(14);
}
[Fact]
public void GetSystemEntitiesList_ShouldContainAllExpectedEntityIds()
[Theory]
[InlineData("sensor.powermonitor_total_power")]
[InlineData("sensor.powermonitor_total_cost_15min")]
[InlineData("sensor.powermonitor_total_cost_1h")]
[InlineData("sensor.powermonitor_total_cost_daily")]
[InlineData("sensor.powermonitor_total_cost_monthly")]
[InlineData("sensor.powermonitor_other_power")]
[InlineData("sensor.powermonitor_other_cost_15min")]
[InlineData("sensor.powermonitor_other_cost_1h")]
[InlineData("sensor.powermonitor_other_cost_daily")]
[InlineData("sensor.powermonitor_other_cost_monthly")]
[InlineData("binary_sensor.powermonitor_anomaly")]
[InlineData("sensor.powermonitor_status")]
[InlineData("button.powermonitor_rediscover_sensors")]
[InlineData("button.powermonitor_trigger_limit_breach")]
public void GetSystemEntitiesList_ShouldContainExpectedEntityId(string entityId)
{
// Act
var result = _sut.GetSystemEntitiesList();
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_power");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_15min");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_1h");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_daily");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_total_cost_monthly");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_power");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_15min");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_1h");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_daily");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_other_cost_monthly");
result.Should().Contain(e => e.EntityId == "binary_sensor.powermonitor_anomaly");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_status");
result.Should().Contain(e => e.EntityId == "button.powermonitor_rediscover_sensors");
result.Should().Contain(e => e.EntityId == "button.powermonitor_trigger_limit_breach");
// Assert
result.Should().Contain(entity => entity.EntityId == entityId);
}
[Fact]
public void GetSystemEntitiesList_AllEntities_ShouldHaveUniqueEntityIds()
{
// Act
var result = _sut.GetSystemEntitiesList();
result.Select(e => e.EntityId).Should().OnlyHaveUniqueItems();
// Assert
result.Select(entity => entity.EntityId).Should().OnlyHaveUniqueItems();
}
[Fact]
public void GetSystemEntitiesList_AllEntities_ShouldExposeCreationOptions()
{
// Act
var result = _sut.GetSystemEntitiesList();
// Assert
result.Should().OnlyContain(entity => entity.Options != null && entity.Options.UniqueId == entity.EntityId);
}
#endregion
#region GetDeviceEntities
#region GetPowerDeviceEntitiesNames
public static IEnumerable<object[]> DeviceEntityCases =>
[
["sonoff device", "sensor.sonoff_1002230e32_power", "Sonoff Power", "sonoff_1002230e32"],
["simple device", "sensor.tv_power", "TV Power", "tv"],
["device with suffix in name", "sensor.akvariumas_power", "Akvariumas Power", "akvariumas"],
["uppercase entity id", "sensor.TV_POWER", "TV Power", "TV"]
];
[Theory]
[MemberData(nameof(DeviceEntityCases))]
public void GetPowerDeviceEntitiesNames_ShouldReturnFourCostEntitiesPerDevice(
string scenario,
string entityId,
string friendlyName,
string expectedDeviceName)
{
// Arrange
var sensor = PowerMonitorTestData.CreateSensor(entityId, friendlyName);
// Act
var result = PowerMonitorEntityService.GetPowerDeviceEntitiesNames(sensor).ToList();
// Assert
result.Should().HaveCount(4, $"scenario: {scenario}");
result.Select(entity => entity.EntityId).Should().BeEquivalentTo(new[]
{
$"sensor.powermonitor_{expectedDeviceName}_cost_15min",
$"sensor.powermonitor_{expectedDeviceName}_cost_1h",
$"sensor.powermonitor_{expectedDeviceName}_cost_daily",
$"sensor.powermonitor_{expectedDeviceName}_cost_monthly"
}, $"scenario: {scenario}");
result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}");
result.Select(entity => entity.Name).Should().BeEquivalentTo(new[]
{
$"{friendlyName} cost (15 min)",
$"{friendlyName} cost (1h)",
$"{friendlyName} cost (daily)",
$"{friendlyName} cost (monthly)"
}, $"scenario: {scenario}");
}
[Fact]
public void GetDeviceEntities_ShouldReturn4CostEntitiesPerDevice()
public void PowerMonitorEntity_WhenNameIsBlank_ShouldFallBackToIdentifier()
{
var sensor = new PowerSensorInfo
{
EntityId = "sensor.sonoff_1002230e32_power",
FriendlyName = "Sonoff Power",
DeviceName = "sonoff_1002230e32"
};
// Arrange - PowerMonitorEntity falls back to the identifier so MQTT entities always have a name.
var entity = new PowerMonitorEntity("sensor", "powermonitor_test", " ");
var result = PowerMonitorEntityService.GetDeviceEntities(sensor).ToList();
result.Should().HaveCount(4);
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_15min");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_1h");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_daily");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_sonoff_1002230e32_cost_monthly");
// Assert
entity.EntityId.Should().Be("sensor.powermonitor_test");
entity.Name.Should().Be("powermonitor_test");
entity.Options.Should().NotBeNull();
entity.Options!.UniqueId.Should().Be("sensor.powermonitor_test");
entity.Options!.Name.Should().Be("powermonitor_test");
}
#endregion
#region GetDeviceCostEntityIds
[Fact]
public void GetDeviceCostEntityIds_ShouldReturn4EntityIds()
[Theory]
[InlineData("sonoff_abc")]
[InlineData("tv")]
[InlineData("akvariumas")]
public void GetDeviceCostEntityIds_ShouldReturnFourEntityIds(string deviceName)
{
var result = PowerMonitorEntityService.GetDeviceCostEntityIds("sonoff_abc").ToList();
// Act
var result = PowerMonitorEntityService.GetDeviceCostEntityIds(deviceName).ToList();
// Assert
result.Should().HaveCount(4);
result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_15min");
result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_1h");
result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_daily");
result.Should().Contain("sensor.powermonitor_sonoff_abc_cost_monthly");
result.Should().BeEquivalentTo(new[]
{
$"sensor.powermonitor_{deviceName}_cost_15min",
$"sensor.powermonitor_{deviceName}_cost_1h",
$"sensor.powermonitor_{deviceName}_cost_daily",
$"sensor.powermonitor_{deviceName}_cost_monthly"
});
}
#endregion
@@ -106,32 +189,25 @@ public class PowerMonitorEntityServiceTests
[Fact]
public async Task CreateSystemEntitiesAsync_ShouldCreateAll14Entities()
{
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.Returns(Task.CompletedTask);
// Act
await _sut.CreateSystemEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(14));
}
[Fact]
public async Task CreateSystemEntitiesAsync_WhenOneEntityFails_ShouldContinueWithOthers()
public async Task CreateSystemEntitiesAsync_WhenSomeEntitiesFail_ShouldContinueWithOthers()
{
var callCount = 0;
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.Returns(() =>
{
callCount++;
if (callCount == 3)
{
throw new InvalidOperationException("Entity creation failed");
}
return Task.CompletedTask;
});
// Arrange - both 1h cost entities fail, the remaining twelve must still be created.
_entityManagerMock
.Setup(em => em.CreateEntityAsync(It.Is<PowerMonitorEntity>(entity => entity.Identifier.EndsWith("_cost_1h"))))
.ThrowsAsync(new InvalidOperationException("Entity creation failed"));
// Act
await _sut.CreateSystemEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(14));
}
@@ -139,69 +215,143 @@ public class PowerMonitorEntityServiceTests
#region CreateDeviceEntitiesAsync
[Fact]
public async Task CreateDeviceEntitiesAsync_ShouldCreate4EntitiesPerDevice()
[Theory]
[InlineData(0, 0)]
[InlineData(1, 4)]
[InlineData(2, 8)]
[InlineData(5, 20)]
public async Task CreateDeviceEntitiesAsync_ShouldCreateFourEntitiesPerSensor(int sensorCount, int expectedCreates)
{
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.Returns(Task.CompletedTask);
var sensors = new List<PowerSensorInfo>
{
new() { EntityId = "sensor.sonoff_100215c534_power", FriendlyName = "AC Power", DeviceName = "sonoff_100215c534" },
new() { EntityId = "sensor.sonoff_10018909cb_power", FriendlyName = "Induction Power", DeviceName = "sonoff_10018909cb" }
};
// Arrange
var sensors = Enumerable.Range(0, sensorCount)
.Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}"))
.ToList();
// Act
await _sut.CreateDeviceEntitiesAsync(sensors);
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(8));
// Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(expectedCreates));
}
#endregion
#region ResetEntitiesAsync
[Fact]
public async Task ResetEntitiesAsync_ShouldSetDefaultStates()
[Theory]
[InlineData("sensor.powermonitor_total_power", "0")]
[InlineData("sensor.powermonitor_total_cost_15min", "0")]
[InlineData("sensor.powermonitor_total_cost_1h", "0")]
[InlineData("sensor.powermonitor_total_cost_daily", "0")]
[InlineData("sensor.powermonitor_total_cost_monthly", "0")]
[InlineData("sensor.powermonitor_other_power", "0")]
[InlineData("sensor.powermonitor_other_cost_15min", "0")]
[InlineData("sensor.powermonitor_other_cost_1h", "0")]
[InlineData("sensor.powermonitor_other_cost_daily", "0")]
[InlineData("sensor.powermonitor_other_cost_monthly", "0")]
[InlineData("binary_sensor.powermonitor_anomaly", "off")]
[InlineData("sensor.powermonitor_status", "initializing")]
public async Task ResetEntitiesAsync_ShouldSetExpectedDefaultState(string entityId, string expectedState)
{
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
// Act
await _sut.ResetEntitiesAsync();
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "off"), Times.Once);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(entityId, expectedState), Times.Once);
}
[Fact]
public async Task ResetEntitiesAsync_ShouldSetExactlyTwelveStates()
{
// Act
await _sut.ResetEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(12));
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "initializing"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "off"), Times.Once);
}
[Fact]
public async Task ResetEntitiesAsync_WhenStateWriteFails_ShouldNotRethrow()
{
// Arrange
_entityManagerMock
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Failed"));
// Act
var act = () => _sut.ResetEntitiesAsync();
// Assert
await act.Should().NotThrowAsync();
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(12));
}
#endregion
#region CleanupEntitiesAsync
#region RemoveSystemEntitiesAsync
[Fact]
public async Task CleanupEntitiesAsync_ShouldRemoveAllSystemEntities()
public async Task RemoveSystemEntitiesAsync_ShouldRemoveAllSystemEntities()
{
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
// Act
await _sut.RemoveSystemEntitiesAsync();
await _sut.CleanupEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.RemoveEntity(It.Is<string>(id => SystemEntityIds.Contains(id))), Times.Exactly(14));
}
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(14));
[Fact]
public async Task RemoveSystemEntitiesAsync_WhenRemovalFails_ShouldRethrow()
{
// Arrange
_entityManagerMock
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Removal failed"));
// Act
var act = () => _sut.RemoveSystemEntitiesAsync();
// Assert
await act.Should().ThrowAsync<InvalidOperationException>();
}
#endregion
#region CleanupDeviceEntitiesAsync
#region RemoveDeviceEntitiesAsync
[Theory]
[InlineData(0, 0)]
[InlineData(1, 4)]
[InlineData(2, 8)]
public async Task RemoveDeviceEntitiesAsync_ShouldRemoveFourEntitiesPerDevice(int deviceCount, int expectedRemovals)
{
// Arrange
var deviceNames = Enumerable.Range(0, deviceCount)
.Select(index => $"device_{index}")
.ToList();
// Act
await _sut.RemoveDeviceEntitiesAsync(deviceNames);
// Assert
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(expectedRemovals));
}
[Fact]
public async Task CleanupDeviceEntitiesAsync_ShouldRemove4EntitiesPerDevice()
public async Task RemoveDeviceEntitiesAsync_WhenOneRemovalFails_ShouldContinueWithOthers()
{
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
// Arrange
_entityManagerMock
.Setup(em => em.RemoveEntity(It.Is<string>(id => id.Contains("_cost_daily"))))
.ThrowsAsync(new InvalidOperationException("Removal failed"));
await _sut.CleanupDeviceEntitiesAsync(["device_a", "device_b"]);
// Act
var act = () => _sut.RemoveDeviceEntitiesAsync(["device_a", "device_b"]);
// Assert
await act.Should().NotThrowAsync();
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(8));
}
@@ -209,55 +359,117 @@ public class PowerMonitorEntityServiceTests
#region UpdateEntitiesAsync
[Fact]
public async Task UpdateEntitiesAsync_ShouldUpdateAllSystemEntities()
[Theory]
[InlineData("sensor.powermonitor_total_power")]
[InlineData("sensor.powermonitor_total_cost_15min")]
[InlineData("sensor.powermonitor_total_cost_1h")]
[InlineData("sensor.powermonitor_total_cost_daily")]
[InlineData("sensor.powermonitor_total_cost_monthly")]
[InlineData("sensor.powermonitor_other_power")]
[InlineData("sensor.powermonitor_other_cost_15min")]
[InlineData("sensor.powermonitor_other_cost_1h")]
[InlineData("sensor.powermonitor_other_cost_daily")]
[InlineData("sensor.powermonitor_other_cost_monthly")]
[InlineData("binary_sensor.powermonitor_anomaly")]
[InlineData("sensor.powermonitor_status")]
public async Task UpdateEntitiesAsync_ShouldWriteStateAndAttributesForSystemEntity(string entityId)
{
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext();
// Arrange
var context = PowerMonitorTestData.CreateUpdateContext();
// Act
await _sut.UpdateEntitiesAsync(context);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "off"), Times.Once);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(entityId, It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes(entityId, It.IsAny<object>()), Times.Once);
}
[Theory]
[InlineData("sensor.tv_power", "tv")]
[InlineData("sensor.akvariumas_power", "akvariumas")]
public async Task UpdateEntitiesAsync_WithDeviceCosts_ShouldUpdateDeviceEntities(string entityId, string deviceName)
{
// Arrange
var context = PowerMonitorTestData.CreateUpdateContext(
deviceReadings: PowerMonitorTestData.CreateReadings((entityId, 42.0)));
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
foreach (var window in new[] { "15min", "1h", "daily", "monthly" })
{
_entityManagerMock.Verify(
em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny<string>()),
Times.Once);
}
}
[Theory]
[InlineData(false, "off")]
[InlineData(true, "on")]
public async Task UpdateEntitiesAsync_ShouldProjectAnomalyState(bool isAnomaly, string expectedState)
{
// Arrange
var context = PowerMonitorTestData.CreateUpdateContext(isAnomaly: isAnomaly);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState), Times.Once);
}
[Theory]
[InlineData("ok")]
[InlineData("degraded")]
[InlineData("initializing")]
public async Task UpdateEntitiesAsync_ShouldProjectSystemStatus(string systemStatus)
{
// Arrange
var context = PowerMonitorTestData.CreateUpdateContext(systemStatus: systemStatus);
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", systemStatus), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_ShouldFormatStatesWithInvariantPrecision()
{
// Arrange
var context = PowerMonitorTestData.CreateUpdateContext(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.tv_power", 42.0)));
// Act
await _sut.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", "342.0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", "128.5"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_cost_daily", "1.0000"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WhenStateWriteFails_ShouldStillWriteRemainingEntities()
{
// Arrange
_entityManagerMock
.Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Failed"));
var context = PowerMonitorTestData.CreateUpdateContext();
// Act
var act = () => _sut.UpdateEntitiesAsync(context);
// Assert
await act.Should().NotThrowAsync();
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "ok"), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WithDeviceCosts_ShouldUpdateDeviceEntities()
{
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext();
await _sut.UpdateEntitiesAsync(context);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_15min", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_1h", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_daily", It.IsAny<string>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_sonoff_100215c534_cost_monthly", It.IsAny<string>()), Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WhenAnomaly_ShouldSetAnomalyOn()
{
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var context = CreateDefaultContext(isAnomaly: true);
await _sut.UpdateEntitiesAsync(context);
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", "on"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny<object>()), Times.Once);
}
#endregion
@@ -267,70 +479,67 @@ public class PowerMonitorEntityServiceTests
[Fact]
public async Task SetEntityStateSafe_WhenExceptionThrown_ShouldNotRethrow()
{
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
// Arrange
_entityManagerMock
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Failed"));
// Act
var act = () => _sut.SetEntityStateSafe("sensor.test", "42");
// Assert
await act.Should().NotThrowAsync();
}
[Fact]
public async Task SetEntityAttributesSafe_WhenExceptionThrown_ShouldNotRethrow()
{
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
// Arrange
_entityManagerMock
.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.ThrowsAsync(new InvalidOperationException("Failed"));
// Act
var act = () => _sut.SetEntityAttributesSafe("sensor.test", new { });
// Assert
await act.Should().NotThrowAsync();
}
#endregion
private static PowerUpdateContext CreateDefaultContext(bool isAnomaly = false)
#region Cancellation
public static IEnumerable<object[]> CancelledOperations()
{
return new PowerUpdateContext
{
Calculation = new PowerCalculationResult
{
TotalPowerWatts = 341.97,
KnownDevicesSumWatts = 210.93,
RawOtherPowerWatts = 131.04,
SmoothedOtherPowerWatts = 128.5,
DataQuality = "ok",
DevicePowerReadings = new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 8.55,
["sensor.sonoff_10018909cb_power"] = 36.93,
["sensor.tv_power"] = 101.0,
["sensor.akvariumas_power"] = 21.0,
["sensor.sonoff_1002230a48_power"] = 20.06,
["sensor.temp_power"] = 14.0,
["sensor.balkony_laps_power"] = 9.39
}
},
CurrentNordPoolPrice = 0.1791,
PriceUnit = "EUR/kWh",
PriceSource = "live",
DeviceCosts = new Dictionary<string, CostSnapshot>
{
["sensor.sonoff_100215c534_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.004, CostDaily = 0.03, CostMonthly = 0.9 },
["sensor.sonoff_10018909cb_power"] = new() { Cost15Min = 0.002, Cost1Hour = 0.009, CostDaily = 0.11, CostMonthly = 3.3 },
["sensor.tv_power"] = new() { Cost15Min = 0.006, Cost1Hour = 0.024, CostDaily = 0.30, CostMonthly = 9.0 },
["sensor.akvariumas_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.005, CostDaily = 0.06, CostMonthly = 1.8 },
["sensor.sonoff_1002230a48_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.005, CostDaily = 0.06, CostMonthly = 1.8 },
["sensor.temp_power"] = new() { Cost15Min = 0.001, Cost1Hour = 0.003, CostDaily = 0.04, CostMonthly = 1.2 },
["sensor.balkony_laps_power"] = new() { Cost15Min = 0.0005, Cost1Hour = 0.002, CostDaily = 0.03, CostMonthly = 0.9 }
},
TotalCost = new CostSnapshot { Cost15Min = 0.02, Cost1Hour = 0.08, CostDaily = 1.00, CostMonthly = 30.0 },
OtherCost = new CostSnapshot { Cost15Min = 0.008, Cost1Hour = 0.031, CostDaily = 0.38, CostMonthly = 11.4 },
IsAnomaly = isAnomaly,
AnomalyDuration = TimeSpan.Zero,
AnomalyThresholdWatts = 1000,
TrackedSensorCount = 7,
DegradedSensors = [],
SystemStatus = "ok"
};
var cancelled = new CancellationToken(canceled: true);
var sensors = new List<PowerSensorInfo> { PowerMonitorTestData.CreateSensor("sensor.tv_power") };
var context = PowerMonitorTestData.CreateUpdateContext();
yield return ["create system entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.CreateSystemEntitiesAsync(cancelled))];
yield return ["create device entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.CreateDeviceEntitiesAsync(sensors, cancelled))];
yield return ["update entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.UpdateEntitiesAsync(context, cancelled))];
yield return ["reset entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.ResetEntitiesAsync(cancelled))];
yield return ["remove system entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.RemoveSystemEntitiesAsync(cancelled))];
yield return ["remove device entities", (Func<PowerMonitorEntityService, Task>)(sut => sut.RemoveDeviceEntitiesAsync(["tv"], cancelled))];
}
[Theory]
[MemberData(nameof(CancelledOperations))]
public async Task Operation_WithCancelledToken_ShouldThrowAndNotTouchEntities(
string scenario,
Func<PowerMonitorEntityService, Task> operation)
{
// Act
var act = () => operation(_sut);
// Assert
await act.Should().ThrowAsync<OperationCanceledException>($"scenario: {scenario}");
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Never);
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Never);
}
#endregion
}
@@ -6,52 +6,81 @@ namespace PowerMonitor.Manager.Tests;
public class PowerMonitorOptionsTests
{
[Fact]
public void Defaults_ShouldHaveEnabledTrue()
/// <summary>
/// Expected defaults for every public, configurable option. Only public properties are
/// inspected here - no private state is read through reflection.
/// </summary>
public static TheoryData<string, object> ExpectedDefaults => new()
{
{ nameof(PowerMonitorOptions.Enabled), false },
{ nameof(PowerMonitorOptions.MainMeterEntityId), string.Empty },
{ nameof(PowerMonitorOptions.PollIntervalSeconds), PowerMonitorConsts.DefaultPollIntervalSeconds },
{ nameof(PowerMonitorOptions.SmoothingWindowSize), PowerMonitorConsts.DefaultSmoothingWindowSize },
{ nameof(PowerMonitorOptions.AnomalyThresholdWatts), PowerMonitorConsts.DefaultAnomalyThresholdWatts },
{ nameof(PowerMonitorOptions.HighPowerThresholdWatts), PowerMonitorConsts.DefaultHighPowerThresholdWatts },
{ nameof(PowerMonitorOptions.EnforceLimitEnabled), true },
{ nameof(PowerMonitorOptions.PowerLimitWatts), PowerMonitorConsts.DefaultPowerLimitWatts },
{ nameof(PowerMonitorOptions.RecoverySeconds), PowerMonitorConsts.DefaultRecoverySeconds },
{ nameof(PowerMonitorOptions.LimitCooldownSeconds), PowerMonitorConsts.DefaultLimitCooldownSeconds }
};
[Theory]
[MemberData(nameof(ExpectedDefaults))]
public void Defaults_ShouldExposeExpectedValue(string propertyName, object expected)
{
// Arrange
var options = new PowerMonitorOptions();
var property = typeof(PowerMonitorOptions).GetProperty(propertyName);
// Act
var actual = property!.GetValue(options);
// Assert
property.Should().NotBeNull($"PowerMonitorOptions.{propertyName} should be a public property");
actual.Should().Be(expected);
}
public static TheoryData<string> CollectionProperties => new()
{
nameof(PowerMonitorOptions.ExcludedSensorPatterns),
nameof(PowerMonitorOptions.EnforceSwitchOffEntityIds),
nameof(PowerMonitorOptions.PauseAndRestoreEntityIds)
};
[Theory]
[MemberData(nameof(CollectionProperties))]
public void Defaults_ShouldExposeEmptyCollection(string propertyName)
{
// Arrange
var options = new PowerMonitorOptions();
options.Enabled.Should().BeTrue();
// Act
var value = typeof(PowerMonitorOptions).GetProperty(propertyName)!.GetValue(options);
// Assert
value.Should().BeOfType<string[]>();
((string[])value!).Should().BeEmpty();
}
[Fact]
public void Defaults_ShouldHaveExpectedPollInterval()
public void Defaults_ShouldNotShareCollectionInstancesBetweenOptionObjects()
{
var options = new PowerMonitorOptions();
// Arrange - two option objects must not mutate each other's array contents.
var first = new PowerMonitorOptions();
var second = new PowerMonitorOptions();
options.PollIntervalSeconds.Should().Be(PowerMonitorConsts.DefaultPollIntervalSeconds);
}
// Act
first.ExcludedSensorPatterns = ["sensor.custom_*"];
first.EnforceSwitchOffEntityIds = ["switch.custom"];
first.PauseAndRestoreEntityIds = ["switch.custom_monitor"];
[Fact]
public void Defaults_ShouldHaveExpectedSmoothingWindowSize()
{
var options = new PowerMonitorOptions();
options.SmoothingWindowSize.Should().Be(PowerMonitorConsts.DefaultSmoothingWindowSize);
}
[Fact]
public void Defaults_ShouldHaveExpectedAnomalyThreshold()
{
var options = new PowerMonitorOptions();
options.AnomalyThresholdWatts.Should().Be(PowerMonitorConsts.DefaultAnomalyThresholdWatts);
}
[Fact]
public void Defaults_ShouldHaveEmptyMainMeterEntityId()
{
var options = new PowerMonitorOptions();
options.MainMeterEntityId.Should().BeEmpty();
}
[Fact]
public void Defaults_ShouldHaveEmptyExcludedSensorPatterns()
{
var options = new PowerMonitorOptions();
options.ExcludedSensorPatterns.Should().BeEmpty();
// Assert
first.ExcludedSensorPatterns.Should().NotBeSameAs(second.ExcludedSensorPatterns);
first.EnforceSwitchOffEntityIds.Should().NotBeSameAs(second.EnforceSwitchOffEntityIds);
first.PauseAndRestoreEntityIds.Should().NotBeSameAs(second.PauseAndRestoreEntityIds);
second.ExcludedSensorPatterns.Should().BeEmpty();
second.EnforceSwitchOffEntityIds.Should().BeEmpty();
second.PauseAndRestoreEntityIds.Should().BeEmpty();
}
[Fact]
@@ -59,60 +88,4 @@ public class PowerMonitorOptionsTests
{
PowerMonitorOptions.SectionName.Should().Be("PowerMonitor");
}
[Fact]
public void Enabled_WhenSetToFalse_ShouldReturnFalse()
{
var options = new PowerMonitorOptions { Enabled = false };
options.Enabled.Should().BeFalse();
}
[Fact]
public void Defaults_ShouldHaveEnforceLimitEnabledTrue()
{
var options = new PowerMonitorOptions();
options.EnforceLimitEnabled.Should().BeTrue();
}
[Fact]
public void Defaults_ShouldHaveExpectedPowerLimitWatts()
{
var options = new PowerMonitorOptions();
options.PowerLimitWatts.Should().Be(PowerMonitorConsts.DefaultPowerLimitWatts);
}
[Fact]
public void Defaults_ShouldHaveExpectedRecoverySeconds()
{
var options = new PowerMonitorOptions();
options.RecoverySeconds.Should().Be(PowerMonitorConsts.DefaultRecoverySeconds);
}
[Fact]
public void Defaults_ShouldHaveExpectedLimitCooldownSeconds()
{
var options = new PowerMonitorOptions();
options.LimitCooldownSeconds.Should().Be(PowerMonitorConsts.DefaultLimitCooldownSeconds);
}
[Fact]
public void Defaults_ShouldHaveEmptyEnforceSwitchOffEntityIds()
{
var options = new PowerMonitorOptions();
options.EnforceSwitchOffEntityIds.Should().BeEmpty();
}
[Fact]
public void Defaults_ShouldHaveEmptyPauseAndRestoreEntityIds()
{
var options = new PowerMonitorOptions();
options.PauseAndRestoreEntityIds.Should().BeEmpty();
}
}
@@ -0,0 +1,217 @@
using System.Text.Json;
using PowerMonitor.Models;
using PowerMonitorManager;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
namespace PowerMonitor.Manager.Tests;
/// <summary>
/// Shared, deterministic datasets and builders used by the PowerMonitor tests.
/// Keeping the builders and generated series here avoids copy-pasted setup and
/// hard-coded clocks across test classes.
/// </summary>
internal static class PowerMonitorTestData
{
public const double DefaultTotalWatts = 341.97;
public const double DefaultSmoothedOtherWatts = 131.04;
public const double DefaultPricePerKwh = 0.1791;
public const string BoilerSwitchEntityId = "switch.sonoff_1002230e32";
public const string AutoManagementEntityId = "switch.boilermonitor_auto_management";
public const string MainMeterEntityId = "sensor.sonoff_100267d63f_power";
public static readonly DateTime FixedNow = new(2026, 3, 17, 10, 0, 0);
public static readonly DateTime FixedDayStart = new(2026, 3, 17, 0, 0, 0);
public static readonly DateTimeOffset FixedUtcNow = new(2026, 3, 17, 8, 0, 0, TimeSpan.Zero);
/// <summary>
/// Two-device reading set used by the cost calculation tests.
/// </summary>
public static IReadOnlyDictionary<string, double> CreateCostDeviceReadings() => new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 101.0,
["sensor.sonoff_10018909cb_power"] = 109.93
};
/// <summary>
/// Realistic seven-device reading set used by the entity projection tests.
/// </summary>
public static IReadOnlyDictionary<string, double> CreateDeviceReadings() => new Dictionary<string, double>
{
["sensor.sonoff_100215c534_power"] = 8.55,
["sensor.sonoff_10018909cb_power"] = 36.93,
["sensor.tv_power"] = 101.0,
["sensor.akvariumas_power"] = 21.0,
["sensor.sonoff_1002230a48_power"] = 20.06,
["sensor.temp_power"] = 14.0,
["sensor.balkony_laps_power"] = 9.39
};
public static IReadOnlyDictionary<string, double> CreateReadings(params (string EntityId, double Watts)[] readings) =>
readings.ToDictionary(r => r.EntityId, r => r.Watts);
public static PowerCalculationResult CreateCalculation(
double totalWatts = DefaultTotalWatts,
double smoothedOtherWatts = DefaultSmoothedOtherWatts,
IReadOnlyDictionary<string, double>? deviceReadings = null,
string dataQuality = "ok")
{
var readings = deviceReadings ?? CreateCostDeviceReadings();
return new PowerCalculationResult
{
TotalPowerWatts = totalWatts,
KnownDevicesSumWatts = readings.Values.Sum(),
RawOtherPowerWatts = smoothedOtherWatts,
SmoothedOtherPowerWatts = smoothedOtherWatts,
DataQuality = dataQuality,
DevicePowerReadings = readings
};
}
public static CostSnapshot CreateCostSnapshot(
double cost15Min = 0.001,
double cost1Hour = 0.004,
double costDaily = 0.03,
double costMonthly = 0.9,
bool partialWindow = true) => new()
{
Cost15Min = cost15Min,
Cost1Hour = cost1Hour,
CostDaily = costDaily,
CostMonthly = costMonthly,
PartialWindow = partialWindow
};
public static PowerUpdateContext CreateUpdateContext(
bool isAnomaly = false,
double totalWatts = DefaultTotalWatts,
double smoothedOtherWatts = 128.5,
string systemStatus = "ok",
IReadOnlyDictionary<string, double>? deviceReadings = null,
double currentNordPoolPrice = DefaultPricePerKwh,
string priceSource = "live")
{
var readings = deviceReadings ?? CreateDeviceReadings();
var deviceCosts = readings
.Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot(
cost15Min: 0.0005 * (index + 1),
cost1Hour: 0.002 * (index + 1),
costDaily: 0.03 * (index + 1),
costMonthly: 0.9 * (index + 1))))
.ToDictionary(entry => entry.Key, entry => entry.Snapshot);
return new PowerUpdateContext
{
Calculation = CreateCalculation(totalWatts, smoothedOtherWatts, readings),
CurrentNordPoolPrice = currentNordPoolPrice,
PriceUnit = "EUR/kWh",
PriceSource = priceSource,
DeviceCosts = deviceCosts,
TotalCost = CreateCostSnapshot(0.02, 0.08, 1.00, 30.0),
OtherCost = CreateCostSnapshot(0.008, 0.031, 0.38, 11.4),
IsAnomaly = isAnomaly,
AnomalyDuration = TimeSpan.Zero,
AnomalyThresholdWatts = PowerMonitorConsts.DefaultAnomalyThresholdWatts,
TrackedSensorCount = readings.Count,
DegradedSensors = [],
SystemStatus = systemStatus
};
}
public static PowerMonitorOptions CreateOptions(Action<PowerMonitorOptions>? configure = null)
{
var options = new PowerMonitorOptions
{
Enabled = true,
MainMeterEntityId = MainMeterEntityId,
ExcludedSensorPatterns = ["sensor.nordpool_*", "sensor.powermonitor_*"]
};
configure?.Invoke(options);
return options;
}
public static PowerMonitorOptions CreateLimitEnforcementOptions(Action<PowerMonitorOptions>? configure = null) =>
CreateOptions(options =>
{
options.EnforceLimitEnabled = true;
options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts;
options.RecoverySeconds = PowerMonitorConsts.DefaultRecoverySeconds;
options.LimitCooldownSeconds = PowerMonitorConsts.DefaultLimitCooldownSeconds;
options.EnforceSwitchOffEntityIds = [BoilerSwitchEntityId];
options.PauseAndRestoreEntityIds = [AutoManagementEntityId];
configure?.Invoke(options);
});
public static PowerSensorInfo CreateSensor(
string entityId,
string? friendlyName = null,
string? deviceName = null,
string unitOfMeasurement = PowerMonitorConsts.WattUnit) => new()
{
EntityId = entityId,
FriendlyName = friendlyName ?? entityId,
DeviceName = deviceName ?? PowerSensorDiscoveryService.ExtractDeviceName(entityId),
UnitOfMeasurement = unitOfMeasurement
};
public static JsonElement CreateAttributesJson(
string? deviceClass,
string? unitOfMeasurement,
string? friendlyName)
{
var attributes = new Dictionary<string, object?>();
if (deviceClass is not null)
{
attributes["device_class"] = deviceClass;
}
if (unitOfMeasurement is not null)
{
attributes["unit_of_measurement"] = unitOfMeasurement;
}
if (friendlyName is not null)
{
attributes["friendly_name"] = friendlyName;
}
return JsonSerializer.SerializeToElement(attributes);
}
/// <summary>
/// Deterministic, strictly positive and monotonically increasing power samples
/// used by the looping scenarios.
/// </summary>
public static IReadOnlyList<double> CreatePowerSampleSeries(int count = 96) =>
Enumerable.Range(0, count)
.Select(i => Math.Round(50.0 + (i * 37.5) + ((i % 7) * 0.5), 2))
.ToArray();
/// <summary>
/// Deterministic, strictly positive hourly tariff series (EUR/kWh).
/// </summary>
public static IReadOnlyList<double> CreateTariffPriceSeries(int count = 24) =>
Enumerable.Range(0, count)
.Select(i => Math.Round(0.08 + (i * 0.03) + ((i % 5) * 0.0125), 4))
.ToArray();
public static IReadOnlyList<(DateTime Start, double PricePerKwh)> CreateHourlyTariffWindows(DateTime dayStart)
{
var prices = CreateTariffPriceSeries();
return Enumerable.Range(0, prices.Count)
.Select(hour => (dayStart.AddHours(hour), prices[hour]))
.ToArray();
}
public static IReadOnlyList<DateTime> CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15) =>
Enumerable.Range(0, count)
.Select(i => start.AddMinutes(i * intervalMinutes))
.ToArray();
}
@@ -1,4 +1,3 @@
using System.Text.Json;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -22,168 +21,258 @@ public class PowerSensorDiscoveryServiceTests
}
private PowerSensorDiscoveryService CreateSut(
string mainMeterEntityId = "sensor.sonoff_100267d63f_power",
string mainMeterEntityId = PowerMonitorTestData.MainMeterEntityId,
string[]? excludedPatterns = null)
{
var options = Options.Create(new PowerMonitorOptions
var options = Options.Create(PowerMonitorTestData.CreateOptions(option =>
{
MainMeterEntityId = mainMeterEntityId,
ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"]
});
option.MainMeterEntityId = mainMeterEntityId;
option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"];
}));
return new PowerSensorDiscoveryService(_haContextMock.Object, options, _loggerMock.Object);
}
private void SetupEntities(params (string entityId, string? deviceClass, string? unit, string? friendlyName)[] entities)
private Entity SetupEntity(string entityId, string? deviceClass, string? unit, string? friendlyName)
{
var entityList = new List<Entity>();
foreach (var (entityId, deviceClass, unit, friendlyName) in entities)
var entityState = new EntityState
{
var attributes = new Dictionary<string, object?>();
if (deviceClass is not null)
{
attributes["device_class"] = deviceClass;
}
AttributesJson = PowerMonitorTestData.CreateAttributesJson(deviceClass, unit, friendlyName)
};
if (unit is not null)
{
attributes["unit_of_measurement"] = unit;
}
if (friendlyName is not null)
{
attributes["friendly_name"] = friendlyName;
}
var attributesJson = JsonSerializer.SerializeToElement(attributes);
var entityState = new EntityState { AttributesJson = attributesJson };
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
var entity = new Entity(_haContextMock.Object, entityId);
entityList.Add(entity);
}
_haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
return new Entity(_haContextMock.Object, entityId);
}
private void SetupEntities(
params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities) =>
_haContextMock
.Setup(h => h.GetAllEntities())
.Returns(entities.Select(entity => SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName)).ToList());
private void SetupEntitiesWithoutState(params string[] entityIds) =>
_haContextMock
.Setup(h => h.GetAllEntities())
.Returns(entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId)).ToList());
#region Discovery
[Fact]
public void DiscoverDeviceSensors_ShouldFindPowerSensors()
{
// Arrange
SetupEntities(
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"),
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"),
("sensor.temperature", "temperature", "°C", "Temperature")
);
("sensor.temperature", "temperature", "°C", "Temperature"));
var sut = CreateSut();
// Act
var result = sut.DiscoverDeviceSensors();
// Assert
result.Should().HaveCount(2);
result.Should().Contain(s => s.EntityId == "sensor.sonoff_100215c534_power");
result.Should().Contain(s => s.EntityId == "sensor.sonoff_10018909cb_power");
result.Should().Contain(sensor => sensor.EntityId == "sensor.sonoff_100215c534_power");
result.Should().Contain(sensor => sensor.EntityId == "sensor.sonoff_10018909cb_power");
}
[Fact]
public void DiscoverDeviceSensors_ShouldExcludeMainMeter()
{
// Arrange
SetupEntities(
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.tv_power", "power", "W", "TV Power")
);
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
("sensor.tv_power", "power", "W", "TV Power"));
var sut = CreateSut();
// Act
var result = sut.DiscoverDeviceSensors();
// Assert
result.Should().HaveCount(1);
result.Should().NotContain(s => s.EntityId == "sensor.sonoff_100267d63f_power");
result.Should().NotContain(sensor => sensor.EntityId == PowerMonitorTestData.MainMeterEntityId);
}
[Fact]
public void DiscoverDeviceSensors_WhenMainMeterNotConfigured_ShouldIncludeAllPowerSensors()
{
// Arrange
SetupEntities(
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
("sensor.tv_power", "power", "W", "TV Power"));
var sut = CreateSut(mainMeterEntityId: string.Empty);
// Act
var result = sut.DiscoverDeviceSensors();
// Assert
result.Should().HaveCount(2);
result.Should().Contain(sensor => sensor.EntityId == PowerMonitorTestData.MainMeterEntityId);
}
[Fact]
public void DiscoverDeviceSensors_ShouldApplyExclusionPatterns()
{
// Arrange
SetupEntities(
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
("sensor.tv_power", "power", "W", "TV Power"),
("sensor.nordpool_some_power", "power", "W", "NordPool"),
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor")
);
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor"));
var sut = CreateSut();
// Act
var result = sut.DiscoverDeviceSensors();
// Assert
result.Should().HaveCount(1);
result.Should().Contain(s => s.EntityId == "sensor.tv_power");
result.Should().Contain(sensor => sensor.EntityId == "sensor.tv_power");
}
[Fact]
public void DiscoverDeviceSensors_ShouldHandleKilowattUnit()
public void DiscoverDeviceSensors_WhenNoExclusionPatternsConfigured_ShouldKeepMatchingSensors()
{
// Arrange
SetupEntities(
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.sonoff_1002230e32_power", "power", "kW", "Boiler Power")
);
("sensor.tv_power", "power", "W", "TV Power"),
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor"));
var sut = CreateSut();
var sut = CreateSut(excludedPatterns: []);
// Act
var result = sut.DiscoverDeviceSensors();
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.sonoff_1002230e32_power");
result.First().UnitOfMeasurement.Should().Be("kW");
// Assert
result.Should().HaveCount(2);
}
[Theory]
[InlineData("sensor.tv_power", "TV Power", "W", "TV Power", "W", "tv")]
[InlineData("sensor.boiler_power", "Boiler Power", "kW", "Boiler Power", "kW", "boiler")]
[InlineData("sensor.mystery_power", null, "W", "sensor.mystery_power", "W", "mystery")]
public void DiscoverDeviceSensors_ShouldExposeSensorMetadata(
string entityId,
string? friendlyName,
string unit,
string expectedFriendlyName,
string expectedUnit,
string expectedDeviceName)
{
// Arrange
SetupEntities((entityId, "power", unit, friendlyName));
var sut = CreateSut();
// Act
var result = sut.DiscoverDeviceSensors();
// Assert
result.Should().ContainSingle();
var sensor = result.Single();
sensor.EntityId.Should().Be(entityId);
sensor.FriendlyName.Should().Be(expectedFriendlyName);
sensor.UnitOfMeasurement.Should().Be(expectedUnit);
sensor.DeviceName.Should().Be(expectedDeviceName);
}
[Fact]
public void DiscoverDeviceSensors_WhenNoPowerSensors_ShouldReturnEmpty()
{
// Arrange
SetupEntities(
("sensor.temperature", "temperature", "°C", "Temp"),
("switch.some_switch", null, null, "Switch")
);
("switch.some_switch", null, null, "Switch"),
("sensor.energy_usage", "energy", "kWh", "Energy"));
var sut = CreateSut();
// Act
var result = sut.DiscoverDeviceSensors();
// Assert
result.Should().BeEmpty();
}
[Fact]
public void DiscoverDeviceSensors_WhenEntityStateMissing_ShouldSkipEntity()
{
// Arrange - HA can report entities whose state has not been published yet.
var tv = SetupEntity("sensor.tv_power", "power", "W", "TV Power");
_haContextMock
.Setup(h => h.GetAllEntities())
.Returns(new List<Entity> { new(_haContextMock.Object, "sensor.ghost_power"), tv });
var sut = CreateSut();
// Act
var result = sut.DiscoverDeviceSensors();
// Assert
result.Should().ContainSingle();
result.Single().EntityId.Should().Be("sensor.tv_power");
}
[Fact]
public void DiscoverDeviceSensors_WhenHaReportsDuplicateEntities_ShouldMirrorTheEntityList()
{
// Arrange - discovery is a projection of HA's entity list; de-duplication is not its job.
SetupEntities(
("sensor.tv_power", "power", "W", "TV Power"),
("sensor.tv_power", "power", "W", "TV Power"));
var sut = CreateSut();
// Act
var result = sut.DiscoverDeviceSensors();
// Assert
result.Should().HaveCount(2);
result.Select(sensor => sensor.DeviceName).Should().OnlyContain(name => name == "tv");
}
[Fact]
public void DiscoverDeviceSensors_ShouldUpdateCurrentDeviceSensors()
{
// Arrange
SetupEntities(
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.akvariumas_power", "power", "W", "Akvariumas Power")
);
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
("sensor.akvariumas_power", "power", "W", "Akvariumas Power"));
var sut = CreateSut();
sut.CurrentDeviceSensors.Should().BeEmpty();
// Act
sut.DiscoverDeviceSensors();
// Assert
sut.CurrentDeviceSensors.Should().HaveCount(1);
}
[Fact]
public void DiscoverDeviceSensors_ReDiscovery_ShouldReplacePreviousList()
{
// Arrange
SetupEntities(
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
("sensor.sonoff_100215c534_power", "power", "W", "AC Power")
);
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"));
var sut = CreateSut();
sut.DiscoverDeviceSensors();
sut.CurrentDeviceSensors.Should().HaveCount(1);
SetupEntities(
("sensor.sonoff_100267d63f_power", "power", "W", "Total Home Power Usage"),
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"),
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power")
);
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"));
// Act
sut.DiscoverDeviceSensors();
// Assert
sut.CurrentDeviceSensors.Should().HaveCount(2);
}
@@ -197,6 +286,11 @@ public class PowerSensorDiscoveryServiceTests
[InlineData("sensor.tv_power", "tv")]
[InlineData("sensor.temp_power", "temp")]
[InlineData("sensor.power", "power")]
[InlineData("sensor.TV_POWER", "TV")]
[InlineData("sensor.boiler_output_power", "boiler_output")]
[InlineData("sensor.temperature", "temperature")]
[InlineData("tv_power", "tv")]
[InlineData("sensor.", "")]
public void ExtractDeviceName_ShouldStripDomainAndPowerSuffix(string entityId, string expected)
{
PowerSensorDiscoveryService.ExtractDeviceName(entityId).Should().Be(expected);
@@ -209,8 +303,14 @@ public class PowerSensorDiscoveryServiceTests
[Theory]
[InlineData("sensor.nordpool_*", "sensor.nordpool_current_price", true)]
[InlineData("sensor.nordpool_*", "sensor.tv_power", false)]
[InlineData("sensor.nordpool_*", "SENSOR.NORDPOOL_CURRENT_PRICE", true)]
[InlineData("sensor.powermonitor_*", "sensor.powermonitor_other_power", true)]
[InlineData("*_power", "sensor.sonoff_100215c534_power", true)]
[InlineData("*_power", "sensor.sonoff_100215c534_energy", false)]
[InlineData("sensor.tv_power", "sensor.tv_power", true)]
[InlineData("sensor.tv_power", "sensor.tv_power_2", false)]
[InlineData("sensor.?.power", "sensor.a.power", false)]
[InlineData("*", "anything at all", true)]
public void GlobToRegex_ShouldMatchCorrectly(string glob, string input, bool expected)
{
var regex = PowerSensorDiscoveryService.GlobToRegex(glob);
@@ -221,34 +321,50 @@ public class PowerSensorDiscoveryServiceTests
#region IsPowerSensor
[Fact]
public void IsPowerSensor_WithPowerDeviceClassAndWattUnit_ShouldReturnTrue()
[Theory]
[InlineData("power device class with watts", "sensor.ac_power", "power", "W", true)]
[InlineData("power device class with kilowatts", "sensor.boiler_power", "power", "kW", true)]
[InlineData("lowercase unit", "sensor.tv_power", "power", "w", true)]
[InlineData("uppercase device class", "sensor.pc_power", "POWER", "W", true)]
[InlineData("power device class with megawatts", "sensor.plant_power", "power", "MW", false)]
[InlineData("power device class without unit", "sensor.mystery_power", "power", null, false)]
[InlineData("power device class with whitespace unit", "sensor.odd_power", "power", " ", false)]
[InlineData("energy device class", "sensor.energy_usage", "energy", "kWh", false)]
[InlineData("temperature device class", "sensor.hall_temp", "temperature", "°C", false)]
[InlineData("missing device class", "sensor.mystery", null, "W", false)]
[InlineData("non sensor domain", "switch.sonoff_100215c534_power", "power", "W", false)]
[InlineData("binary sensor domain", "binary_sensor.washer_power", "power", "W", false)]
public void IsPowerSensor_ShouldMatchOnlySensorEntitiesWithPowerDeviceClassAndPowerUnit(
string scenario,
string entityId,
string? deviceClass,
string? unit,
bool expected)
{
SetupEntities(("sensor.sonoff_100215c534_power", "power", "W", "AC Power"));
var entity = new Entity(_haContextMock.Object, "sensor.sonoff_100215c534_power");
// Arrange
var entity = SetupEntity(entityId, deviceClass, unit, "Test");
var sut = CreateSut();
sut.IsPowerSensor(entity).Should().BeTrue();
// Act
var result = sut.IsPowerSensor(entity);
// Assert
result.Should().Be(expected, $"scenario: {scenario}");
}
[Fact]
public void IsPowerSensor_WithNonSensorDomain_ShouldReturnFalse()
public void IsPowerSensor_WhenEntityStateMissing_ShouldReturnFalse()
{
SetupEntities(("switch.sonoff_100215c534_power", "power", "W", "AC Power"));
var entity = new Entity(_haContextMock.Object, "switch.sonoff_100215c534_power");
// Arrange
SetupEntitiesWithoutState("sensor.ghost_power");
var entity = new Entity(_haContextMock.Object, "sensor.ghost_power");
var sut = CreateSut();
sut.IsPowerSensor(entity).Should().BeFalse();
}
[Fact]
public void IsPowerSensor_WithTemperatureDeviceClass_ShouldReturnFalse()
{
SetupEntities(("sensor.sonoff_100215c534_temp", "temperature", "°C", "AC Temp"));
var entity = new Entity(_haContextMock.Object, "sensor.sonoff_100215c534_temp");
// Act
var result = sut.IsPowerSensor(entity);
var sut = CreateSut();
sut.IsPowerSensor(entity).Should().BeFalse();
// Assert
result.Should().BeFalse();
}
#endregion