Files
HomeAssistant/PowerMonitor.Manager.Tests/PowerCostCalculationServiceTests.cs
T
gitea_admin 5777e641f6 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
2026-11-29 21:30:13 +02:00

555 lines
20 KiB
C#

using FluentAssertions;
using PowerMonitorManager;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
namespace PowerMonitor.Manager.Tests;
public class PowerCostCalculationServiceTests
{
public enum CostBucket
{
Total,
Other
}
private readonly PowerCostCalculationService _sut = new();
#region CalculateCostIncrement
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]
];
[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_ForGeneratedPowerSeries_ShouldBeProportionalToPower()
{
// Arrange
const double pricePerKwh = 0.25;
const int pollIntervalSeconds = 15;
var samples = PowerMonitorTestData.CreatePowerSampleSeries(25);
var unitCost = PowerCostCalculationService.CalculateCostIncrement(1_000.0, pricePerKwh, pollIntervalSeconds);
// 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
#region RecordCosts
[Fact]
public void RecordCosts_ShouldCreateTotalAndOtherSnapshots()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
// Assert
var expectedTotal = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts, PowerMonitorTestData.DefaultPricePerKwh);
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expectedTotal, 1e-12);
_sut.GetOtherCostSnapshot().CostDaily.Should().BeApproximately(expectedOther, 1e-12);
_sut.GetTotalCostSnapshot().PartialWindow.Should().BeTrue();
}
[Theory]
[InlineData("sensor.sonoff_100215c534_power")]
[InlineData("sensor.sonoff_10018909cb_power")]
public void RecordCosts_ShouldCreatePositiveDeviceSnapshotForEveryReading(string entityId)
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
// 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()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
// Assert
var total = _sut.GetTotalCostSnapshot();
var other = _sut.GetOtherCostSnapshot();
total.CostDaily.Should().BeGreaterThan(other.CostDaily);
}
[Fact]
public void RecordCosts_MultipleCalls_ShouldAccumulate()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
// Act
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
var firstCost = _sut.GetTotalCostSnapshot().CostDaily;
_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()
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var firstResult = PowerMonitorTestData.CreateCalculation(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
// Act
_sut.RecordCosts(firstResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(1);
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.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 InitialPrice_ShouldBeZeroAndLive()
{
_sut.LastKnownPrice.Should().Be(0);
_sut.PriceSource.Should().Be("live");
}
[Theory]
[InlineData(0.0001)]
[InlineData(0.1791)]
[InlineData(0.2492)]
[InlineData(1.5)]
[InlineData(100.0)]
public void RecordCosts_WithPositivePrice_ShouldStoreLivePrice(double price)
{
// Act
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), price, 15, PowerMonitorTestData.FixedNow);
// Assert
_sut.LastKnownPrice.Should().Be(price);
_sut.PriceSource.Should().Be("live");
}
[Theory]
[InlineData(0.0)]
[InlineData(-0.0001)]
[InlineData(-5.0)]
public void RecordCosts_WithNonPositivePrice_ShouldFallBackToLastKnownPrice(double invalidPrice)
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation();
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
// 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
[Fact]
public void GetAllDeviceCostSnapshots_WhenEmpty_ShouldReturnEmpty()
{
_sut.GetAllDeviceCostSnapshots().Should().BeEmpty();
}
[Theory]
[InlineData("sensor.unknown")]
[InlineData("")]
[InlineData(" ")]
[InlineData("SENSOR.SONOFF_100215C534_POWER")]
public void GetDeviceCostSnapshot_ForUnknownDevice_ShouldReturnEmptySnapshot(string entityId)
{
// 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();
}
#endregion
#region Snapshot defaults
[Theory]
[InlineData(CostBucket.Total)]
[InlineData(CostBucket.Other)]
public void GetSnapshot_BeforeAnyRecording_ShouldReturnEmptySnapshot(CostBucket bucket)
{
// Act
var snapshot = bucket == CostBucket.Total
? _sut.GetTotalCostSnapshot()
: _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();
}
#endregion
#region Thread safety
[Fact]
public async Task RecordCosts_ConcurrentAccess_ShouldNotLoseData()
{
// 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, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1));
}
}))
.ToArray();
await Task.WhenAll(tasks);
// Assert
var total = _sut.GetTotalCostSnapshot();
total.CostDaily.Should().BeGreaterThan(0);
var devices = _sut.GetAllDeviceCostSnapshots();
devices.Should().HaveCount(2);
}
#endregion
private static double ExpectedCost(
double powerWatts,
double pricePerKwh,
int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds) =>
powerWatts / PowerMonitorConsts.WattsPerKilowatt
* pricePerKwh
* ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
}