Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests - Expand single-statement guards and loops into braced blocks - Realign wrapped method arguments, chained calls and continuations - Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty` - Flatten the boiler config expression and reindent the remaining touched files
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class CostAccumulatorTests
|
||||
@@ -27,11 +31,14 @@ public class CostAccumulatorTests
|
||||
|
||||
// Act
|
||||
var tasks = Enumerable.Range(0, threadCount)
|
||||
.Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < callsPerThread; i++) sut.AddCost(incrementPerCall, now.AddSeconds(1));
|
||||
}))
|
||||
.ToArray();
|
||||
.Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < callsPerThread; i++)
|
||||
{
|
||||
sut.AddCost(incrementPerCall, now.AddSeconds(1));
|
||||
}
|
||||
}))
|
||||
.ToArray();
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
@@ -47,11 +54,7 @@ public class CostAccumulatorTests
|
||||
{
|
||||
return window switch
|
||||
{
|
||||
CostWindow.FifteenMinutes => snapshot.Cost15Min,
|
||||
CostWindow.Hour => snapshot.Cost1Hour,
|
||||
CostWindow.Day => snapshot.CostDaily,
|
||||
CostWindow.Month => snapshot.CostMonthly,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(window))
|
||||
CostWindow.FifteenMinutes => snapshot.Cost15Min, CostWindow.Hour => snapshot.Cost1Hour, CostWindow.Day => snapshot.CostDaily, CostWindow.Month => snapshot.CostMonthly, _ => throw new ArgumentOutOfRangeException(nameof(window))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -116,12 +119,16 @@ public class CostAccumulatorTests
|
||||
// Arrange
|
||||
var now = PowerMonitorTestData.FixedNow;
|
||||
var sut = new CostAccumulator(now);
|
||||
|
||||
var increments = PowerMonitorTestData.CreatePowerSampleSeries(50)
|
||||
.Select(watts => watts / 100_000.0)
|
||||
.ToArray();
|
||||
.Select(watts => watts / 100_000.0)
|
||||
.ToArray();
|
||||
|
||||
// Act
|
||||
foreach (var increment in increments) sut.AddCost(increment, now.AddSeconds(1));
|
||||
foreach (var increment in increments)
|
||||
{
|
||||
sut.AddCost(increment, now.AddSeconds(1));
|
||||
}
|
||||
|
||||
// Assert
|
||||
var expected = increments.Sum();
|
||||
@@ -191,7 +198,7 @@ public class CostAccumulatorTests
|
||||
|
||||
#region Window rollovers
|
||||
|
||||
public static TheoryData<string, CostWindow, DateTime, DateTime, double, double> WindowRolloverCases => new()
|
||||
public static TheoryData<string, CostWindow, DateTime, DateTime, double, double> WindowRolloverCases => new TheoryData<string, CostWindow, DateTime, DateTime, double, double>
|
||||
{
|
||||
{
|
||||
"15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0),
|
||||
@@ -323,7 +330,7 @@ public class CostAccumulatorTests
|
||||
|
||||
#region Window boundary detection (static methods)
|
||||
|
||||
public static TheoryData<string, DateTime, DateTime, bool> FifteenMinuteBoundaryCases => new()
|
||||
public static TheoryData<string, DateTime, DateTime, bool> FifteenMinuteBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
|
||||
{
|
||||
{ "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 },
|
||||
@@ -344,7 +351,7 @@ public class CostAccumulatorTests
|
||||
CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
public static TheoryData<string, DateTime, DateTime, bool> HourBoundaryCases => new()
|
||||
public static TheoryData<string, DateTime, DateTime, bool> HourBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
|
||||
{
|
||||
{ "same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false },
|
||||
{
|
||||
@@ -366,7 +373,7 @@ public class CostAccumulatorTests
|
||||
CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
public static TheoryData<string, DateTime, DateTime, bool> DayBoundaryCases => new()
|
||||
public static TheoryData<string, DateTime, DateTime, bool> DayBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
|
||||
{
|
||||
{ "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 },
|
||||
@@ -385,7 +392,7 @@ public class CostAccumulatorTests
|
||||
CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
public static TheoryData<string, DateTime, DateTime, bool> MonthBoundaryCases => new()
|
||||
public static TheoryData<string, DateTime, DateTime, bool> MonthBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
|
||||
{
|
||||
{ "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 },
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class OtherPowerCalculationServiceTests
|
||||
@@ -13,12 +17,13 @@ public class OtherPowerCalculationServiceTests
|
||||
{
|
||||
SmoothingWindowSize = smoothingWindowSize
|
||||
});
|
||||
|
||||
return new OtherPowerCalculationService(options);
|
||||
}
|
||||
|
||||
#region Basic calculation
|
||||
|
||||
public static TheoryData<string, double, double[], double, string> CalculationCases => new()
|
||||
public static TheoryData<string, double, double[], double, string> CalculationCases => new TheoryData<string, double, double[], double, string>
|
||||
{
|
||||
{ "two devices", 341.97, [8.55, 36.93], 296.49, "ok" },
|
||||
{ "no devices", 341.97, [], 341.97, "ok" },
|
||||
@@ -42,9 +47,10 @@ public class OtherPowerCalculationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(1);
|
||||
|
||||
var devices = deviceWatts
|
||||
.Select((watts, index) => (entityId: $"sensor.device{index}_power", watts))
|
||||
.ToDictionary(entry => entry.entityId, entry => entry.watts);
|
||||
.Select((watts, index) => (entityId: $"sensor.device{index}_power", watts))
|
||||
.ToDictionary(entry => entry.entityId, entry => entry.watts);
|
||||
|
||||
// Act
|
||||
var result = sut.Calculate(totalPowerWatts, devices);
|
||||
@@ -166,7 +172,11 @@ public class OtherPowerCalculationServiceTests
|
||||
|
||||
// Act
|
||||
PowerCalculationResult? result = null;
|
||||
for (var i = 0; i < 200; i++) result = sut.Calculate(200.0, new Dictionary<string, double>());
|
||||
|
||||
for (var i = 0; i < 200; i++)
|
||||
{
|
||||
result = sut.Calculate(200.0, new Dictionary<string, double>());
|
||||
}
|
||||
|
||||
// Assert
|
||||
result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1);
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerCostCalculationServiceTests
|
||||
@@ -12,7 +16,7 @@ public class PowerCostCalculationServiceTests
|
||||
Other
|
||||
}
|
||||
|
||||
private readonly PowerCostCalculationService _sut = new();
|
||||
private readonly PowerCostCalculationService _sut = new PowerCostCalculationService();
|
||||
|
||||
#region Snapshot defaults
|
||||
|
||||
@@ -23,8 +27,8 @@ public class PowerCostCalculationServiceTests
|
||||
{
|
||||
// Act
|
||||
var snapshot = bucket == CostBucket.Total
|
||||
? _sut.GetTotalCostSnapshot()
|
||||
: _sut.GetOtherCostSnapshot();
|
||||
? _sut.GetTotalCostSnapshot()
|
||||
: _sut.GetOtherCostSnapshot();
|
||||
|
||||
// Assert
|
||||
snapshot.Cost15Min.Should().Be(0);
|
||||
@@ -49,12 +53,14 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// 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();
|
||||
.Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < callsPerThread; i++)
|
||||
{
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1));
|
||||
}
|
||||
}))
|
||||
.ToArray();
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
@@ -73,14 +79,12 @@ public class PowerCostCalculationServiceTests
|
||||
double pricePerKwh,
|
||||
int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds)
|
||||
{
|
||||
return powerWatts / PowerMonitorConsts.WattsPerKilowatt
|
||||
* pricePerKwh
|
||||
* ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
|
||||
return powerWatts / PowerMonitorConsts.WattsPerKilowatt * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
|
||||
}
|
||||
|
||||
#region CalculateCostIncrement
|
||||
|
||||
public static TheoryData<string, double, double, int, double> CostIncrementCases => new()
|
||||
public static TheoryData<string, double, double, int, double> CostIncrementCases => new TheoryData<string, double, double, int, double>
|
||||
{
|
||||
{ "default polling interval", 341.97, 0.1791, 15, 0.0002551951125 },
|
||||
{ "one kilowatt for one hour", 1000.0, 1.0, PowerMonitorConsts.SecondsPerHour, 1.0 },
|
||||
@@ -121,14 +125,17 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
var costs = samples
|
||||
.Select(watts =>
|
||||
PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds))
|
||||
.ToArray();
|
||||
.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
|
||||
@@ -144,13 +151,14 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||
now);
|
||||
now);
|
||||
|
||||
// Assert
|
||||
var expectedTotal =
|
||||
ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
||||
|
||||
var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts,
|
||||
PowerMonitorTestData.DefaultPricePerKwh);
|
||||
PowerMonitorTestData.DefaultPricePerKwh);
|
||||
|
||||
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expectedTotal, 1e-12);
|
||||
_sut.GetOtherCostSnapshot().CostDaily.Should().BeApproximately(expectedOther, 1e-12);
|
||||
@@ -168,7 +176,7 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||
now);
|
||||
now);
|
||||
|
||||
// Assert
|
||||
var snapshot = _sut.GetDeviceCostSnapshot(entityId);
|
||||
@@ -187,7 +195,7 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||
now);
|
||||
now);
|
||||
|
||||
// Assert
|
||||
var total = _sut.GetTotalCostSnapshot();
|
||||
@@ -218,15 +226,16 @@ public class PowerCostCalculationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var now = PowerMonitorTestData.FixedNow;
|
||||
|
||||
var firstResult = PowerMonitorTestData.CreateCalculation(
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
|
||||
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));
|
||||
now.AddSeconds(15));
|
||||
|
||||
// Assert
|
||||
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
|
||||
@@ -242,7 +251,8 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
var singleDeviceResult = PowerMonitorTestData.CreateCalculation(
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
|
||||
|
||||
_sut.RecordCosts(singleDeviceResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15));
|
||||
|
||||
// Assert
|
||||
@@ -270,10 +280,11 @@ public class PowerCostCalculationServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var now = PowerMonitorTestData.FixedNow;
|
||||
|
||||
var result = PowerMonitorTestData.CreateCalculation(
|
||||
0,
|
||||
0,
|
||||
PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0)));
|
||||
0,
|
||||
0,
|
||||
PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0)));
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
||||
@@ -290,8 +301,9 @@ public class PowerCostCalculationServiceTests
|
||||
{
|
||||
// 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)));
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.glitch_power", -500.0)));
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
||||
@@ -382,17 +394,19 @@ public class PowerCostCalculationServiceTests
|
||||
const double pricePerKwh = 0.2;
|
||||
var timestamps = PowerMonitorTestData.CreateSampleTimestamps(PowerMonitorTestData.FixedDayStart, 96);
|
||||
var wattSamples = PowerMonitorTestData.CreatePowerSampleSeries();
|
||||
|
||||
var expectedPerSlot = timestamps
|
||||
.Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh))
|
||||
.ToArray();
|
||||
.Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh))
|
||||
.ToArray();
|
||||
|
||||
// Act
|
||||
for (var slot = 0; slot < timestamps.Count; slot++)
|
||||
{
|
||||
var result = PowerMonitorTestData.CreateCalculation(
|
||||
wattSamples[slot],
|
||||
wattSamples[slot] / 2,
|
||||
new Dictionary<string, double>());
|
||||
wattSamples[slot],
|
||||
wattSamples[slot] / 2,
|
||||
new Dictionary<string, double>());
|
||||
|
||||
_sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]);
|
||||
}
|
||||
|
||||
@@ -416,10 +430,12 @@ public class PowerCostCalculationServiceTests
|
||||
foreach (var (start, pricePerKwh) in windows)
|
||||
{
|
||||
var watts = 500.0 + start.Hour * 125.0;
|
||||
|
||||
var result = PowerMonitorTestData.CreateCalculation(
|
||||
watts,
|
||||
watts / 4,
|
||||
PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2)));
|
||||
watts,
|
||||
watts / 4,
|
||||
PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2)));
|
||||
|
||||
_sut.RecordCosts(result, pricePerKwh, pollIntervalSeconds, start);
|
||||
expectedPerHour.Add(ExpectedCost(watts, pricePerKwh, pollIntervalSeconds));
|
||||
}
|
||||
@@ -476,8 +492,10 @@ public class PowerCostCalculationServiceTests
|
||||
// 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);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using System.Globalization;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -9,6 +11,8 @@ using NetDaemon.HassModel.Entities;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerLimitEnforcementServiceTests
|
||||
@@ -16,53 +20,53 @@ public class PowerLimitEnforcementServiceTests
|
||||
private const string BoilerSwitch = PowerMonitorTestData.BoilerSwitchEntityId;
|
||||
private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId;
|
||||
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new Mock<ILogger<PowerLimitEnforcementService>>();
|
||||
private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions();
|
||||
private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow);
|
||||
private readonly FakeTimeProvider _timeProvider = new FakeTimeProvider(PowerMonitorTestData.FixedUtcNow);
|
||||
|
||||
private PowerLimitEnforcementService CreateSut()
|
||||
{
|
||||
return new PowerLimitEnforcementService(
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(_options),
|
||||
_timeProvider);
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(_options),
|
||||
_timeProvider);
|
||||
}
|
||||
|
||||
private void VerifyNoServiceCalls()
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
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));
|
||||
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(entityId)), null),
|
||||
Times.Exactly(expectedCalls));
|
||||
}
|
||||
|
||||
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));
|
||||
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));
|
||||
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));
|
||||
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Exactly(expectedCalls));
|
||||
}
|
||||
|
||||
#region EnforceLimit
|
||||
@@ -131,11 +135,13 @@ public class PowerLimitEnforcementServiceTests
|
||||
{
|
||||
// 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?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((d, s, t, _) =>
|
||||
calls.Add((d, s, t?.EntityIds?.FirstOrDefault())));
|
||||
.Setup(x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(),
|
||||
It.IsAny<object?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((d, s, t, _) =>
|
||||
calls.Add((d, s, t?.EntityIds?.FirstOrDefault())));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
@@ -144,8 +150,12 @@ public class PowerLimitEnforcementServiceTests
|
||||
// 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)");
|
||||
|
||||
turnOffCalls[0]
|
||||
.entityId.Should()
|
||||
.Be(BoilerSwitch,
|
||||
"boiler switch must be turned off before auto_management (race-safe order)");
|
||||
|
||||
turnOffCalls[1].entityId.Should().Be(AutoManagement);
|
||||
}
|
||||
|
||||
@@ -156,10 +166,12 @@ public class PowerLimitEnforcementServiceTests
|
||||
_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()));
|
||||
.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();
|
||||
|
||||
// Act
|
||||
@@ -184,16 +196,17 @@ public class PowerLimitEnforcementServiceTests
|
||||
// Assert
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
VerifyNotificationCreated(1);
|
||||
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
x => x.CallService("switch", It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Recovery
|
||||
|
||||
public static TheoryData<string, int, double, bool, int> RecoveryCases => new()
|
||||
public static TheoryData<string, int, double, bool, int> RecoveryCases => new TheoryData<string, int, double, bool, int>
|
||||
{
|
||||
{ "not yet due", 300, 3000.0, true, 0 },
|
||||
{ "one second before due", 599, 3000.0, true, 0 },
|
||||
@@ -268,7 +281,7 @@ public class PowerLimitEnforcementServiceTests
|
||||
[InlineData(31, true)]
|
||||
[InlineData(600, true)]
|
||||
public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery,
|
||||
bool expectedLimitActive)
|
||||
bool expectedLimitActive)
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut();
|
||||
@@ -379,9 +392,11 @@ public class PowerLimitEnforcementServiceTests
|
||||
|
||||
// Assert
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Exactly(3));
|
||||
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);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -5,6 +7,8 @@ using Moq;
|
||||
using PowerMonitor.Models;
|
||||
using PowerMonitorManager;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerMonitorEntityServiceTests
|
||||
@@ -27,18 +31,22 @@ public class PowerMonitorEntityServiceTests
|
||||
"button.powermonitor_trigger_limit_breach"
|
||||
];
|
||||
|
||||
private readonly Mock<IEntityManager> _entityManagerMock = new();
|
||||
private readonly Mock<IEntityManager> _entityManagerMock = new Mock<IEntityManager>();
|
||||
private readonly PowerMonitorEntityService _sut;
|
||||
|
||||
public PowerMonitorEntityServiceTests()
|
||||
{
|
||||
var loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
|
||||
|
||||
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>())).Returns(Task.CompletedTask);
|
||||
_sut = new PowerMonitorEntityService(_entityManagerMock.Object, loggerMock.Object);
|
||||
}
|
||||
@@ -56,6 +64,7 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
// Assert
|
||||
result.Should().HaveCount(4);
|
||||
|
||||
string[] expectedEntityIds =
|
||||
[
|
||||
$"sensor.powermonitor_{deviceName}_cost_15min",
|
||||
@@ -63,6 +72,7 @@ public class PowerMonitorEntityServiceTests
|
||||
$"sensor.powermonitor_{deviceName}_cost_daily",
|
||||
$"sensor.powermonitor_{deviceName}_cost_monthly"
|
||||
];
|
||||
|
||||
result.Should().BeEquivalentTo(expectedEntityIds);
|
||||
}
|
||||
|
||||
@@ -79,15 +89,15 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var sensors = Enumerable.Range(0, sensorCount)
|
||||
.Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}"))
|
||||
.ToList();
|
||||
.Select(index => PowerMonitorTestData.CreateSensor($"sensor.device{index}_power", $"Device {index}"))
|
||||
.ToList();
|
||||
|
||||
// Act
|
||||
await _sut.CreateDeviceEntitiesAsync(sensors);
|
||||
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()),
|
||||
Times.Exactly(expectedCreates));
|
||||
Times.Exactly(expectedCreates));
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -152,7 +162,7 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
#region GetPowerDeviceEntitiesNames
|
||||
|
||||
public static TheoryData<string, string, string, string> DeviceEntityCases => new()
|
||||
public static TheoryData<string, string, string, string> DeviceEntityCases => new TheoryData<string, string, string, string>
|
||||
{
|
||||
{ "sonoff device", "sensor.sonoff_1002230e32_power", "Sonoff Power", "sonoff_1002230e32" },
|
||||
{ "simple device", "sensor.tv_power", "TV Power", "tv" },
|
||||
@@ -176,6 +186,7 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
// Assert
|
||||
result.Should().HaveCount(4, $"scenario: {scenario}");
|
||||
|
||||
string[] expectedEntityIds =
|
||||
[
|
||||
$"sensor.powermonitor_{expectedDeviceName}_cost_15min",
|
||||
@@ -183,8 +194,10 @@ public class PowerMonitorEntityServiceTests
|
||||
$"sensor.powermonitor_{expectedDeviceName}_cost_daily",
|
||||
$"sensor.powermonitor_{expectedDeviceName}_cost_monthly"
|
||||
];
|
||||
|
||||
result.Select(entity => entity.EntityId).Should().BeEquivalentTo(expectedEntityIds, $"scenario: {scenario}");
|
||||
result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}");
|
||||
|
||||
string[] expectedNames =
|
||||
[
|
||||
$"{friendlyName} cost (15 min)",
|
||||
@@ -192,6 +205,7 @@ public class PowerMonitorEntityServiceTests
|
||||
$"{friendlyName} cost (daily)",
|
||||
$"{friendlyName} cost (monthly)"
|
||||
];
|
||||
|
||||
result.Select(entity => entity.Name).Should().BeEquivalentTo(expectedNames, $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
@@ -228,9 +242,9 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// 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"));
|
||||
.Setup(em =>
|
||||
em.CreateEntityAsync(It.Is<PowerMonitorEntity>(entity => entity.Identifier.EndsWith("_cost_1h"))))
|
||||
.ThrowsAsync(new InvalidOperationException("Entity creation failed"));
|
||||
|
||||
// Act
|
||||
await _sut.CreateSystemEntitiesAsync();
|
||||
@@ -282,8 +296,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.ResetEntitiesAsync();
|
||||
@@ -305,7 +319,7 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.RemoveEntity(It.Is<string>(id => SystemEntityIds.Contains(id))),
|
||||
Times.Exactly(14));
|
||||
Times.Exactly(14));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -313,8 +327,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Removal failed"));
|
||||
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Removal failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.RemoveSystemEntitiesAsync();
|
||||
@@ -335,8 +349,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var deviceNames = Enumerable.Range(0, deviceCount)
|
||||
.Select(index => $"device_{index}")
|
||||
.ToList();
|
||||
.Select(index => $"device_{index}")
|
||||
.ToList();
|
||||
|
||||
// Act
|
||||
await _sut.RemoveDeviceEntitiesAsync(deviceNames);
|
||||
@@ -350,8 +364,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.RemoveEntity(It.Is<string>(id => id.Contains("_cost_daily"))))
|
||||
.ThrowsAsync(new InvalidOperationException("Removal failed"));
|
||||
.Setup(em => em.RemoveEntity(It.Is<string>(id => id.Contains("_cost_daily"))))
|
||||
.ThrowsAsync(new InvalidOperationException("Removal failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.RemoveDeviceEntitiesAsync(["device_a", "device_b"]);
|
||||
@@ -398,16 +412,18 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var context = PowerMonitorTestData.CreateUpdateContext(
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings((entityId, 42.0)));
|
||||
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);
|
||||
em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny<string>()),
|
||||
Times.Once);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -423,7 +439,7 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -447,7 +463,7 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
var context = PowerMonitorTestData.CreateUpdateContext(
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.tv_power", 42.0)));
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.tv_power", 42.0)));
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
@@ -455,8 +471,10 @@ public class PowerMonitorEntityServiceTests
|
||||
// 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);
|
||||
Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once);
|
||||
}
|
||||
|
||||
@@ -465,8 +483,9 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
.Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
|
||||
var context = PowerMonitorTestData.CreateUpdateContext();
|
||||
|
||||
// Act
|
||||
@@ -475,8 +494,9 @@ public class PowerMonitorEntityServiceTests
|
||||
// Assert
|
||||
await act.Should().NotThrowAsync();
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "ok"), Times.Once);
|
||||
|
||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny<object>()),
|
||||
Times.Once);
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -488,8 +508,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.SetEntityStateSafe("sensor.test", "42");
|
||||
@@ -503,8 +523,8 @@ public class PowerMonitorEntityServiceTests
|
||||
{
|
||||
// Arrange
|
||||
_entityManagerMock
|
||||
.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||
.ThrowsAsync(new InvalidOperationException("Failed"));
|
||||
|
||||
// Act
|
||||
var act = () => _sut.SetEntityAttributesSafe("sensor.test", new { });
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerMonitorOptionsTests
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#region
|
||||
|
||||
using System.Text.Json;
|
||||
using PowerMonitor.Models;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
/// <summary>
|
||||
@@ -21,11 +25,11 @@ internal static class PowerMonitorTestData
|
||||
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 FixedNow = new DateTime(2026, 3, 17, 10, 0, 0);
|
||||
|
||||
public static readonly DateTime FixedDayStart = new(2026, 3, 17, 0, 0, 0);
|
||||
public static readonly DateTime FixedDayStart = new DateTime(2026, 3, 17, 0, 0, 0);
|
||||
|
||||
public static readonly DateTimeOffset FixedUtcNow = new(2026, 3, 17, 8, 0, 0, TimeSpan.Zero);
|
||||
public static readonly DateTimeOffset FixedUtcNow = new DateTimeOffset(2026, 3, 17, 8, 0, 0, TimeSpan.Zero);
|
||||
|
||||
/// <summary>
|
||||
/// Two-device reading set used by the cost calculation tests.
|
||||
@@ -107,13 +111,14 @@ internal static class PowerMonitorTestData
|
||||
string priceSource = "live")
|
||||
{
|
||||
var readings = deviceReadings ?? CreateDeviceReadings();
|
||||
|
||||
var deviceCosts = readings
|
||||
.Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot(
|
||||
0.0005 * (index + 1),
|
||||
0.002 * (index + 1),
|
||||
0.03 * (index + 1),
|
||||
0.9 * (index + 1))))
|
||||
.ToDictionary(entry => entry.Key, entry => entry.Snapshot);
|
||||
.Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot(
|
||||
0.0005 * (index + 1),
|
||||
0.002 * (index + 1),
|
||||
0.03 * (index + 1),
|
||||
0.9 * (index + 1))))
|
||||
.ToDictionary(entry => entry.Key, entry => entry.Snapshot);
|
||||
|
||||
return new PowerUpdateContext
|
||||
{
|
||||
@@ -143,21 +148,22 @@ internal static class PowerMonitorTestData
|
||||
};
|
||||
|
||||
configure?.Invoke(options);
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
public static PowerMonitorOptions CreateLimitEnforcementOptions(Action<PowerMonitorOptions>? configure = null)
|
||||
{
|
||||
return 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);
|
||||
});
|
||||
{
|
||||
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(
|
||||
@@ -182,11 +188,20 @@ internal static class PowerMonitorTestData
|
||||
{
|
||||
var attributes = new Dictionary<string, object?>();
|
||||
|
||||
if (deviceClass is not null) attributes["device_class"] = deviceClass;
|
||||
if (deviceClass is not null)
|
||||
{
|
||||
attributes["device_class"] = deviceClass;
|
||||
}
|
||||
|
||||
if (unitOfMeasurement is not null) attributes["unit_of_measurement"] = unitOfMeasurement;
|
||||
if (unitOfMeasurement is not null)
|
||||
{
|
||||
attributes["unit_of_measurement"] = unitOfMeasurement;
|
||||
}
|
||||
|
||||
if (friendlyName is not null) attributes["friendly_name"] = friendlyName;
|
||||
if (friendlyName is not null)
|
||||
{
|
||||
attributes["friendly_name"] = friendlyName;
|
||||
}
|
||||
|
||||
return JsonSerializer.SerializeToElement(attributes);
|
||||
}
|
||||
@@ -200,7 +215,7 @@ internal static class PowerMonitorTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2))
|
||||
.Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2))
|
||||
];
|
||||
}
|
||||
|
||||
@@ -212,7 +227,7 @@ internal static class PowerMonitorTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4))
|
||||
.Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4))
|
||||
];
|
||||
}
|
||||
|
||||
@@ -223,7 +238,7 @@ internal static class PowerMonitorTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, prices.Count)
|
||||
.Select(hour => (dayStart.AddHours(hour), prices[hour]))
|
||||
.Select(hour => (dayStart.AddHours(hour), prices[hour]))
|
||||
];
|
||||
}
|
||||
|
||||
@@ -232,7 +247,7 @@ internal static class PowerMonitorTestData
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => start.AddMinutes(i * intervalMinutes))
|
||||
.Select(i => start.AddMinutes(i * intervalMinutes))
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
#region
|
||||
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -6,22 +8,25 @@ using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using PowerMonitorManager;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock = new();
|
||||
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||
private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock = new Mock<ILogger<PowerSensorDiscoveryService>>();
|
||||
|
||||
private PowerSensorDiscoveryService CreateSut(
|
||||
string mainMeterEntityId = PowerMonitorTestData.MainMeterEntityId,
|
||||
string[]? excludedPatterns = null)
|
||||
{
|
||||
var options = Options.Create(PowerMonitorTestData.CreateOptions(option =>
|
||||
{
|
||||
option.MainMeterEntityId = mainMeterEntityId;
|
||||
option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"];
|
||||
}));
|
||||
{
|
||||
option.MainMeterEntityId = mainMeterEntityId;
|
||||
option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"];
|
||||
}));
|
||||
|
||||
return new PowerSensorDiscoveryService(_haContextMock.Object, options, _loggerMock.Object);
|
||||
}
|
||||
|
||||
@@ -33,6 +38,7 @@ public class PowerSensorDiscoveryServiceTests
|
||||
};
|
||||
|
||||
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
||||
|
||||
return new Entity(_haContextMock.Object, entityId);
|
||||
}
|
||||
|
||||
@@ -40,18 +46,18 @@ public class PowerSensorDiscoveryServiceTests
|
||||
params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities)
|
||||
{
|
||||
_haContextMock
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns([
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns([
|
||||
.. entities.Select(entity =>
|
||||
SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName))
|
||||
SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName))
|
||||
]);
|
||||
}
|
||||
|
||||
private void SetupEntitiesWithoutState(params string[] entityIds)
|
||||
{
|
||||
_haContextMock
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]);
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]);
|
||||
}
|
||||
|
||||
#region ExtractDeviceName
|
||||
@@ -102,10 +108,10 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(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"));
|
||||
(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"));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -123,8 +129,8 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "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();
|
||||
|
||||
@@ -141,8 +147,8 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "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(string.Empty);
|
||||
|
||||
@@ -159,10 +165,10 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(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"));
|
||||
(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"));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -179,8 +185,8 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
("sensor.tv_power", "power", "W", "TV Power"),
|
||||
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor"));
|
||||
("sensor.tv_power", "power", "W", "TV Power"),
|
||||
("sensor.powermonitor_other_power", "power", "W", "PowerMonitor"));
|
||||
|
||||
var sut = CreateSut(excludedPatterns: []);
|
||||
|
||||
@@ -225,9 +231,9 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
("sensor.temperature", "temperature", "°C", "Temp"),
|
||||
("switch.some_switch", null, null, "Switch"),
|
||||
("sensor.energy_usage", "energy", "kWh", "Energy"));
|
||||
("sensor.temperature", "temperature", "°C", "Temp"),
|
||||
("switch.some_switch", null, null, "Switch"),
|
||||
("sensor.energy_usage", "energy", "kWh", "Energy"));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -243,9 +249,10 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// 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 });
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns(new List<Entity> { new Entity(_haContextMock.Object, "sensor.ghost_power"), tv });
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -262,8 +269,8 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// 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"));
|
||||
("sensor.tv_power", "power", "W", "TV Power"),
|
||||
("sensor.tv_power", "power", "W", "TV Power"));
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
@@ -280,8 +287,8 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "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();
|
||||
@@ -298,17 +305,17 @@ public class PowerSensorDiscoveryServiceTests
|
||||
{
|
||||
// Arrange
|
||||
SetupEntities(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "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(
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"),
|
||||
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"));
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.sonoff_100215c534_power", "power", "W", "AC Power"),
|
||||
("sensor.sonoff_10018909cb_power", "power", "W", "Induction Power"));
|
||||
|
||||
// Act
|
||||
sut.DiscoverDeviceSensors();
|
||||
|
||||
Reference in New Issue
Block a user