Apply code formatting cleanup across monitor projects
- Reindent appsettings.json and the MSBuild project files - Collapse single-statement guard blocks and tidy using and member order - Normalize XML doc indentation and file endings - Reorder BatteryMonitor test-data helpers and move the exclusion tests into their own region - Carry the same formatting through the boiler config, control, entity and test files
This commit is contained in:
@@ -13,6 +13,60 @@ public class CostAccumulatorTests
|
||||
Month
|
||||
}
|
||||
|
||||
#region Thread safety
|
||||
|
||||
[Fact]
|
||||
public async Task AddCost_ConcurrentAccess_ShouldNotLoseData()
|
||||
{
|
||||
// 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(() =>
|
||||
{
|
||||
for (var i = 0; i < callsPerThread; i++) sut.AddCost(incrementPerCall, now.AddSeconds(1));
|
||||
}))
|
||||
.ToArray();
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
// Assert
|
||||
var snapshot = sut.GetSnapshot();
|
||||
const double expected = incrementPerCall * callsPerThread * threadCount;
|
||||
snapshot.CostMonthly.Should().BeApproximately(expected, 0.0001);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private static double GetCurrent(CostSnapshot snapshot, CostWindow window)
|
||||
{
|
||||
return 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)
|
||||
{
|
||||
return window switch
|
||||
{
|
||||
CostWindow.FifteenMinutes => snapshot.Previous15Min,
|
||||
CostWindow.Hour => snapshot.Previous1Hour,
|
||||
CostWindow.Day => snapshot.PreviousDaily,
|
||||
CostWindow.Month => snapshot.PreviousMonthly,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(window))
|
||||
};
|
||||
}
|
||||
|
||||
#region AddCost and GetSnapshot
|
||||
|
||||
[Fact]
|
||||
@@ -67,10 +121,7 @@ public class CostAccumulatorTests
|
||||
.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();
|
||||
@@ -142,21 +193,66 @@ public class CostAccumulatorTests
|
||||
|
||||
public static TheoryData<string, CostWindow, DateTime, DateTime, double, double> WindowRolloverCases => new()
|
||||
{
|
||||
{ "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 }
|
||||
{
|
||||
"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]
|
||||
@@ -251,7 +347,9 @@ public class CostAccumulatorTests
|
||||
public static TheoryData<string, DateTime, DateTime, bool> HourBoundaryCases => new()
|
||||
{
|
||||
{ "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, 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 },
|
||||
@@ -292,7 +390,10 @@ public class CostAccumulatorTests
|
||||
{ "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 },
|
||||
{
|
||||
"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 }
|
||||
};
|
||||
@@ -305,55 +406,4 @@ public class CostAccumulatorTests
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Thread safety
|
||||
|
||||
[Fact]
|
||||
public async Task AddCost_ConcurrentAccess_ShouldNotLoseData()
|
||||
{
|
||||
// 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(() =>
|
||||
{
|
||||
for (var i = 0; i < callsPerThread; i++)
|
||||
{
|
||||
sut.AddCost(incrementPerCall, now.AddSeconds(1));
|
||||
}
|
||||
}))
|
||||
.ToArray();
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
// Assert
|
||||
var snapshot = sut.GetSnapshot();
|
||||
const double 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))
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ public class OtherPowerCalculationServiceTests
|
||||
string expectedDataQuality)
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(smoothingWindowSize: 1);
|
||||
var sut = CreateSut(1);
|
||||
var devices = deviceWatts
|
||||
.Select((watts, index) => (entityId: $"sensor.device{index}_power", watts))
|
||||
.ToDictionary(entry => entry.entityId, entry => entry.watts);
|
||||
@@ -62,7 +62,7 @@ public class OtherPowerCalculationServiceTests
|
||||
public void Calculate_ShouldIncludeAllDeviceReadingsInResult()
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(smoothingWindowSize: 1);
|
||||
var sut = CreateSut(1);
|
||||
var devices = PowerMonitorTestData.CreateCostDeviceReadings();
|
||||
|
||||
// Act
|
||||
@@ -78,7 +78,7 @@ public class OtherPowerCalculationServiceTests
|
||||
public void Calculate_ShouldCopyDeviceReadingsInsteadOfAliasingThem()
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(smoothingWindowSize: 1);
|
||||
var sut = CreateSut(1);
|
||||
var devices = new Dictionary<string, double> { ["sensor.tv_power"] = 100.0 };
|
||||
|
||||
// Act
|
||||
@@ -98,7 +98,7 @@ public class OtherPowerCalculationServiceTests
|
||||
public void Calculate_FirstSample_ShouldReturnRawValueWithoutSmoothing()
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(smoothingWindowSize: 10);
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
var result = sut.Calculate(341.97, new Dictionary<string, double>());
|
||||
@@ -111,7 +111,7 @@ public class OtherPowerCalculationServiceTests
|
||||
public void Calculate_WithSmoothing_ShouldApplyExponentialMovingAverage()
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(smoothingWindowSize: 4);
|
||||
var sut = CreateSut(4);
|
||||
|
||||
// Act
|
||||
var result1 = sut.Calculate(341.97, new Dictionary<string, double>());
|
||||
@@ -127,7 +127,7 @@ public class OtherPowerCalculationServiceTests
|
||||
public void Calculate_WithSmoothingWindowOfOne_ShouldFollowRawValueExactly()
|
||||
{
|
||||
// Arrange - alpha becomes 1, so the previous value has no influence.
|
||||
var sut = CreateSut(smoothingWindowSize: 1);
|
||||
var sut = CreateSut(1);
|
||||
|
||||
// Act
|
||||
sut.Calculate(500.0, new Dictionary<string, double>());
|
||||
@@ -141,7 +141,7 @@ public class OtherPowerCalculationServiceTests
|
||||
public void Calculate_ShouldDampenSingleSpike()
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(smoothingWindowSize: 10);
|
||||
var sut = CreateSut();
|
||||
sut.Calculate(100.0, new Dictionary<string, double>());
|
||||
|
||||
// Act
|
||||
@@ -166,10 +166,7 @@ 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);
|
||||
@@ -179,7 +176,7 @@ public class OtherPowerCalculationServiceTests
|
||||
public void Calculate_WithGeneratedSeries_ShouldNeverOvershootTheInputRange()
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(smoothingWindowSize: 5);
|
||||
var sut = CreateSut(5);
|
||||
var samples = PowerMonitorTestData.CreatePowerSampleSeries(50);
|
||||
|
||||
// Act
|
||||
@@ -198,7 +195,7 @@ public class OtherPowerCalculationServiceTests
|
||||
public void Reset_ShouldClearSmoothedState()
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(smoothingWindowSize: 10);
|
||||
var sut = CreateSut();
|
||||
sut.Calculate(341.97, new Dictionary<string, double>());
|
||||
sut.Calculate(341.97, new Dictionary<string, double>());
|
||||
|
||||
@@ -214,7 +211,7 @@ public class OtherPowerCalculationServiceTests
|
||||
public void Reset_WhenCalledBeforeAnyCalculation_ShouldKeepFirstSampleRaw()
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut(smoothingWindowSize: 10);
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
sut.Reset();
|
||||
@@ -225,4 +222,4 @@ public class OtherPowerCalculationServiceTests
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,70 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
private readonly PowerCostCalculationService _sut = new();
|
||||
|
||||
#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)
|
||||
{
|
||||
return powerWatts / PowerMonitorConsts.WattsPerKilowatt
|
||||
* pricePerKwh
|
||||
* ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
|
||||
}
|
||||
|
||||
#region CalculateCostIncrement
|
||||
|
||||
public static TheoryData<string, double, double, int, double> CostIncrementCases => new()
|
||||
@@ -57,15 +121,14 @@ public class PowerCostCalculationServiceTests
|
||||
|
||||
// Act
|
||||
var costs = samples
|
||||
.Select(watts => PowerCostCalculationService.CalculateCostIncrement(watts, pricePerKwh, pollIntervalSeconds))
|
||||
.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
|
||||
@@ -80,11 +143,14 @@ public class PowerCostCalculationServiceTests
|
||||
var result = PowerMonitorTestData.CreateCalculation();
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||
now);
|
||||
|
||||
// Assert
|
||||
var expectedTotal = ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
||||
var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
||||
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);
|
||||
@@ -101,7 +167,8 @@ public class PowerCostCalculationServiceTests
|
||||
var result = PowerMonitorTestData.CreateCalculation();
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||
now);
|
||||
|
||||
// Assert
|
||||
var snapshot = _sut.GetDeviceCostSnapshot(entityId);
|
||||
@@ -119,7 +186,8 @@ public class PowerCostCalculationServiceTests
|
||||
var result = PowerMonitorTestData.CreateCalculation();
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, now);
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds,
|
||||
now);
|
||||
|
||||
// Assert
|
||||
var total = _sut.GetTotalCostSnapshot();
|
||||
@@ -157,7 +225,8 @@ public class PowerCostCalculationServiceTests
|
||||
_sut.RecordCosts(firstResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
||||
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(1);
|
||||
|
||||
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15));
|
||||
_sut.RecordCosts(PowerMonitorTestData.CreateCalculation(), PowerMonitorTestData.DefaultPricePerKwh, 15,
|
||||
now.AddSeconds(15));
|
||||
|
||||
// Assert
|
||||
_sut.GetAllDeviceCostSnapshots().Should().HaveCount(2);
|
||||
@@ -202,9 +271,9 @@ public class PowerCostCalculationServiceTests
|
||||
// Arrange
|
||||
var now = PowerMonitorTestData.FixedNow;
|
||||
var result = PowerMonitorTestData.CreateCalculation(
|
||||
totalWatts: 0,
|
||||
smoothedOtherWatts: 0,
|
||||
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0)));
|
||||
0,
|
||||
0,
|
||||
PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 0)));
|
||||
|
||||
// Act
|
||||
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now);
|
||||
@@ -321,9 +390,9 @@ public class PowerCostCalculationServiceTests
|
||||
for (var slot = 0; slot < timestamps.Count; slot++)
|
||||
{
|
||||
var result = PowerMonitorTestData.CreateCalculation(
|
||||
totalWatts: wattSamples[slot],
|
||||
smoothedOtherWatts: wattSamples[slot] / 2,
|
||||
deviceReadings: new Dictionary<string, double>());
|
||||
wattSamples[slot],
|
||||
wattSamples[slot] / 2,
|
||||
new Dictionary<string, double>());
|
||||
_sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]);
|
||||
}
|
||||
|
||||
@@ -348,9 +417,9 @@ public class PowerCostCalculationServiceTests
|
||||
{
|
||||
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)));
|
||||
watts,
|
||||
watts / 4,
|
||||
PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2)));
|
||||
_sut.RecordCosts(result, pricePerKwh, pollIntervalSeconds, start);
|
||||
expectedPerHour.Add(ExpectedCost(watts, pricePerKwh, pollIntervalSeconds));
|
||||
}
|
||||
@@ -407,7 +476,8 @@ public class PowerCostCalculationServiceTests
|
||||
// Assert
|
||||
_sut.LastKnownPrice.Should().Be(PowerMonitorTestData.DefaultPricePerKwh);
|
||||
_sut.PriceSource.Should().Be("live");
|
||||
var expected = 2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
||||
var expected =
|
||||
2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
|
||||
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12);
|
||||
}
|
||||
|
||||
@@ -486,68 +556,4 @@ public class PowerCostCalculationServiceTests
|
||||
}
|
||||
|
||||
#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);
|
||||
}
|
||||
}
|
||||
@@ -18,40 +18,52 @@ public class PowerLimitEnforcementServiceTests
|
||||
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new();
|
||||
private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow);
|
||||
private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions();
|
||||
private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow);
|
||||
|
||||
private PowerLimitEnforcementService CreateSut() =>
|
||||
new(
|
||||
private PowerLimitEnforcementService CreateSut()
|
||||
{
|
||||
return new PowerLimitEnforcementService(
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(_options),
|
||||
_timeProvider);
|
||||
}
|
||||
|
||||
private void VerifyNoServiceCalls() =>
|
||||
private void VerifyNoServiceCalls()
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
private void VerifyTurnOff(string entityId, int expectedCalls) =>
|
||||
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));
|
||||
}
|
||||
|
||||
private void VerifyTurnOn(string entityId, int 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));
|
||||
}
|
||||
|
||||
private void VerifyNotificationCreated(int 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) =>
|
||||
private void VerifyNotificationDismissed(int expectedCalls)
|
||||
{
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Exactly(expectedCalls));
|
||||
}
|
||||
|
||||
#region EnforceLimit
|
||||
|
||||
@@ -120,7 +132,8 @@ 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?>()))
|
||||
.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();
|
||||
@@ -131,7 +144,8 @@ 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);
|
||||
}
|
||||
|
||||
@@ -253,7 +267,8 @@ public class PowerLimitEnforcementServiceTests
|
||||
[InlineData(30, true)]
|
||||
[InlineData(31, true)]
|
||||
[InlineData(600, true)]
|
||||
public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery, bool expectedLimitActive)
|
||||
public void EnforceLimit_AfterRecovery_ShouldReEnforceOnlyOnceCooldownElapsed(int secondsAfterRecovery,
|
||||
bool expectedLimitActive)
|
||||
{
|
||||
// Arrange
|
||||
var sut = CreateSut();
|
||||
@@ -435,4 +450,4 @@ public class PowerLimitEnforcementServiceTests
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,35 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<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.12.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<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.11.0" />
|
||||
<PackageReference Include="Moq" Version="4.21.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="11.0.1" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<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.12.0"/>
|
||||
<PackageReference Include="xunit" Version="2.9.3"/>
|
||||
<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.11.0"/>
|
||||
<PackageReference Include="Moq" Version="4.21.0"/>
|
||||
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="11.0.1"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
|
||||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj"/>
|
||||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -33,13 +33,65 @@ public class PowerMonitorEntityServiceTests
|
||||
public PowerMonitorEntityServiceTests()
|
||||
{
|
||||
var 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.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);
|
||||
}
|
||||
|
||||
#region GetDeviceCostEntityIds
|
||||
|
||||
[Theory]
|
||||
[InlineData("sonoff_abc")]
|
||||
[InlineData("tv")]
|
||||
[InlineData("akvariumas")]
|
||||
public void GetDeviceCostEntityIds_ShouldReturnFourEntityIds(string deviceName)
|
||||
{
|
||||
// Act
|
||||
var result = PowerMonitorEntityService.GetDeviceCostEntityIds(deviceName).ToList();
|
||||
|
||||
// Assert
|
||||
result.Should().HaveCount(4);
|
||||
string[] expectedEntityIds =
|
||||
[
|
||||
$"sensor.powermonitor_{deviceName}_cost_15min",
|
||||
$"sensor.powermonitor_{deviceName}_cost_1h",
|
||||
$"sensor.powermonitor_{deviceName}_cost_daily",
|
||||
$"sensor.powermonitor_{deviceName}_cost_monthly"
|
||||
];
|
||||
result.Should().BeEquivalentTo(expectedEntityIds);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region CreateDeviceEntitiesAsync
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 0)]
|
||||
[InlineData(1, 4)]
|
||||
[InlineData(2, 8)]
|
||||
[InlineData(5, 20)]
|
||||
public async Task CreateDeviceEntitiesAsync_ShouldCreateFourEntitiesPerSensor(int sensorCount, int expectedCreates)
|
||||
{
|
||||
// Arrange
|
||||
var sensors = Enumerable.Range(0, sensorCount)
|
||||
.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));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetSystemEntitiesList
|
||||
|
||||
[Fact]
|
||||
@@ -159,31 +211,6 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetDeviceCostEntityIds
|
||||
|
||||
[Theory]
|
||||
[InlineData("sonoff_abc")]
|
||||
[InlineData("tv")]
|
||||
[InlineData("akvariumas")]
|
||||
public void GetDeviceCostEntityIds_ShouldReturnFourEntityIds(string deviceName)
|
||||
{
|
||||
// Act
|
||||
var result = PowerMonitorEntityService.GetDeviceCostEntityIds(deviceName).ToList();
|
||||
|
||||
// Assert
|
||||
result.Should().HaveCount(4);
|
||||
string[] expectedEntityIds =
|
||||
[
|
||||
$"sensor.powermonitor_{deviceName}_cost_15min",
|
||||
$"sensor.powermonitor_{deviceName}_cost_1h",
|
||||
$"sensor.powermonitor_{deviceName}_cost_daily",
|
||||
$"sensor.powermonitor_{deviceName}_cost_monthly"
|
||||
];
|
||||
result.Should().BeEquivalentTo(expectedEntityIds);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region CreateSystemEntitiesAsync
|
||||
|
||||
[Fact]
|
||||
@@ -201,7 +228,8 @@ 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"))))
|
||||
.Setup(em =>
|
||||
em.CreateEntityAsync(It.Is<PowerMonitorEntity>(entity => entity.Identifier.EndsWith("_cost_1h"))))
|
||||
.ThrowsAsync(new InvalidOperationException("Entity creation failed"));
|
||||
|
||||
// Act
|
||||
@@ -213,29 +241,6 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
#endregion
|
||||
|
||||
#region CreateDeviceEntitiesAsync
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 0)]
|
||||
[InlineData(1, 4)]
|
||||
[InlineData(2, 8)]
|
||||
[InlineData(5, 20)]
|
||||
public async Task CreateDeviceEntitiesAsync_ShouldCreateFourEntitiesPerSensor(int sensorCount, int expectedCreates)
|
||||
{
|
||||
// Arrange
|
||||
var sensors = Enumerable.Range(0, sensorCount)
|
||||
.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));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ResetEntitiesAsync
|
||||
|
||||
[Theory]
|
||||
@@ -299,7 +304,8 @@ public class PowerMonitorEntityServiceTests
|
||||
await _sut.RemoveSystemEntitiesAsync();
|
||||
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.RemoveEntity(It.Is<string>(id => SystemEntityIds.Contains(id))), Times.Exactly(14));
|
||||
_entityManagerMock.Verify(em => em.RemoveEntity(It.Is<string>(id => SystemEntityIds.Contains(id))),
|
||||
Times.Exactly(14));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -399,11 +405,9 @@ public class PowerMonitorEntityServiceTests
|
||||
|
||||
// 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]
|
||||
@@ -412,13 +416,14 @@ public class PowerMonitorEntityServiceTests
|
||||
public async Task UpdateEntitiesAsync_ShouldProjectAnomalyState(bool isAnomaly, string expectedState)
|
||||
{
|
||||
// Arrange
|
||||
var context = PowerMonitorTestData.CreateUpdateContext(isAnomaly: isAnomaly);
|
||||
var context = PowerMonitorTestData.CreateUpdateContext(isAnomaly);
|
||||
|
||||
// Act
|
||||
await _sut.UpdateEntitiesAsync(context);
|
||||
|
||||
// Assert
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState), Times.Once);
|
||||
_entityManagerMock.Verify(em => em.SetEntityState("binary_sensor.powermonitor_anomaly", expectedState),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -450,7 +455,8 @@ 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);
|
||||
_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);
|
||||
}
|
||||
|
||||
@@ -469,7 +475,8 @@ 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);
|
||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny<object>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -513,7 +520,7 @@ public class PowerMonitorEntityServiceTests
|
||||
public static TheoryData<string, Func<PowerMonitorEntityService, Task>> CancelledOperations()
|
||||
{
|
||||
var data = new TheoryData<string, Func<PowerMonitorEntityService, Task>>();
|
||||
var cancelled = new CancellationToken(canceled: true);
|
||||
var cancelled = new CancellationToken(true);
|
||||
List<PowerSensorInfo> sensors = [PowerMonitorTestData.CreateSensor("sensor.tv_power")];
|
||||
var context = PowerMonitorTestData.CreateUpdateContext();
|
||||
|
||||
@@ -545,4 +552,4 @@ public class PowerMonitorEntityServiceTests
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,13 @@ namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerMonitorOptionsTests
|
||||
{
|
||||
public static TheoryData<string> CollectionProperties =>
|
||||
[
|
||||
nameof(PowerMonitorOptions.ExcludedSensorPatterns),
|
||||
nameof(PowerMonitorOptions.EnforceSwitchOffEntityIds),
|
||||
nameof(PowerMonitorOptions.PauseAndRestoreEntityIds)
|
||||
];
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(PowerMonitorOptions.Enabled), false)]
|
||||
[InlineData(nameof(PowerMonitorOptions.MainMeterEntityId), "")]
|
||||
@@ -31,13 +38,6 @@ public class PowerMonitorOptionsTests
|
||||
actual.Should().Be(expected);
|
||||
}
|
||||
|
||||
public static TheoryData<string> CollectionProperties =>
|
||||
[
|
||||
nameof(PowerMonitorOptions.ExcludedSensorPatterns),
|
||||
nameof(PowerMonitorOptions.EnforceSwitchOffEntityIds),
|
||||
nameof(PowerMonitorOptions.PauseAndRestoreEntityIds)
|
||||
];
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(CollectionProperties))]
|
||||
public void Defaults_ShouldExposeEmptyCollection(string propertyName)
|
||||
@@ -96,4 +96,4 @@ public class PowerMonitorOptionsTests
|
||||
{
|
||||
PowerMonitorOptions.SectionName.Should().Be("PowerMonitor");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,9 @@ 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.
|
||||
/// 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
|
||||
{
|
||||
@@ -28,30 +28,38 @@ internal static class PowerMonitorTestData
|
||||
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.
|
||||
/// Two-device reading set used by the cost calculation tests.
|
||||
/// </summary>
|
||||
public static IReadOnlyDictionary<string, double> CreateCostDeviceReadings() => new Dictionary<string, double>
|
||||
public static IReadOnlyDictionary<string, double> CreateCostDeviceReadings()
|
||||
{
|
||||
["sensor.sonoff_100215c534_power"] = 101.0,
|
||||
["sensor.sonoff_10018909cb_power"] = 109.93
|
||||
};
|
||||
return 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.
|
||||
/// Realistic seven-device reading set used by the entity projection tests.
|
||||
/// </summary>
|
||||
private static Dictionary<string, double> CreateDeviceReadings() => new()
|
||||
private static Dictionary<string, double> CreateDeviceReadings()
|
||||
{
|
||||
["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
|
||||
};
|
||||
return 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 IReadOnlyDictionary<string, double> CreateReadings(params (string EntityId, double Watts)[] readings)
|
||||
{
|
||||
return readings.ToDictionary(r => r.EntityId, r => r.Watts);
|
||||
}
|
||||
|
||||
public static PowerCalculationResult CreateCalculation(
|
||||
double totalWatts = DefaultTotalWatts,
|
||||
@@ -77,14 +85,17 @@ internal static class PowerMonitorTestData
|
||||
double cost1Hour = 0.004,
|
||||
double costDaily = 0.03,
|
||||
double costMonthly = 0.9,
|
||||
bool partialWindow = true) => new()
|
||||
bool partialWindow = true)
|
||||
{
|
||||
Cost15Min = cost15Min,
|
||||
Cost1Hour = cost1Hour,
|
||||
CostDaily = costDaily,
|
||||
CostMonthly = costMonthly,
|
||||
PartialWindow = partialWindow
|
||||
};
|
||||
return new CostSnapshot
|
||||
{
|
||||
Cost15Min = cost15Min,
|
||||
Cost1Hour = cost1Hour,
|
||||
CostDaily = costDaily,
|
||||
CostMonthly = costMonthly,
|
||||
PartialWindow = partialWindow
|
||||
};
|
||||
}
|
||||
|
||||
public static PowerUpdateContext CreateUpdateContext(
|
||||
bool isAnomaly = false,
|
||||
@@ -98,10 +109,10 @@ internal static class PowerMonitorTestData
|
||||
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))))
|
||||
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
|
||||
@@ -135,8 +146,9 @@ internal static class PowerMonitorTestData
|
||||
return options;
|
||||
}
|
||||
|
||||
public static PowerMonitorOptions CreateLimitEnforcementOptions(Action<PowerMonitorOptions>? configure = null) =>
|
||||
CreateOptions(options =>
|
||||
public static PowerMonitorOptions CreateLimitEnforcementOptions(Action<PowerMonitorOptions>? configure = null)
|
||||
{
|
||||
return CreateOptions(options =>
|
||||
{
|
||||
options.EnforceLimitEnabled = true;
|
||||
options.PowerLimitWatts = PowerMonitorConsts.DefaultPowerLimitWatts;
|
||||
@@ -146,18 +158,22 @@ internal static class PowerMonitorTestData
|
||||
options.PauseAndRestoreEntityIds = [AutoManagementEntityId];
|
||||
configure?.Invoke(options);
|
||||
});
|
||||
}
|
||||
|
||||
public static PowerSensorInfo CreateSensor(
|
||||
string entityId,
|
||||
string? friendlyName = null,
|
||||
string? deviceName = null,
|
||||
string unitOfMeasurement = PowerMonitorConsts.WattUnit) => new()
|
||||
string unitOfMeasurement = PowerMonitorConsts.WattUnit)
|
||||
{
|
||||
EntityId = entityId,
|
||||
FriendlyName = friendlyName ?? entityId,
|
||||
DeviceName = deviceName ?? PowerSensorDiscoveryService.ExtractDeviceName(entityId),
|
||||
UnitOfMeasurement = unitOfMeasurement
|
||||
};
|
||||
return new PowerSensorInfo
|
||||
{
|
||||
EntityId = entityId,
|
||||
FriendlyName = friendlyName ?? entityId,
|
||||
DeviceName = deviceName ?? PowerSensorDiscoveryService.ExtractDeviceName(entityId),
|
||||
UnitOfMeasurement = unitOfMeasurement
|
||||
};
|
||||
}
|
||||
|
||||
public static JsonElement CreateAttributesJson(
|
||||
string? deviceClass,
|
||||
@@ -166,42 +182,39 @@ 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deterministic, strictly positive and monotonically increasing power samples
|
||||
/// used by the looping scenarios.
|
||||
/// 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))
|
||||
];
|
||||
public static IReadOnlyList<double> CreatePowerSampleSeries(int count = 96)
|
||||
{
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => Math.Round(50.0 + i * 37.5 + i % 7 * 0.5, 2))
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deterministic, strictly positive hourly tariff series (EUR/kWh).
|
||||
/// Deterministic, strictly positive hourly tariff series (EUR/kWh).
|
||||
/// </summary>
|
||||
private 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))
|
||||
];
|
||||
private static IReadOnlyList<double> CreateTariffPriceSeries(int count = 24)
|
||||
{
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => Math.Round(0.08 + i * 0.03 + i % 5 * 0.0125, 4))
|
||||
];
|
||||
}
|
||||
|
||||
public static IReadOnlyList<(DateTime Start, double PricePerKwh)> CreateHourlyTariffWindows(DateTime dayStart)
|
||||
{
|
||||
@@ -214,9 +227,12 @@ internal static class PowerMonitorTestData
|
||||
];
|
||||
}
|
||||
|
||||
public static IReadOnlyList<DateTime> CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15) =>
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => start.AddMinutes(i * intervalMinutes))
|
||||
];
|
||||
}
|
||||
public static IReadOnlyList<DateTime> CreateSampleTimestamps(DateTime start, int count, int intervalMinutes = 15)
|
||||
{
|
||||
return
|
||||
[
|
||||
.. Enumerable.Range(0, count)
|
||||
.Select(i => start.AddMinutes(i * intervalMinutes))
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -37,15 +37,63 @@ public class PowerSensorDiscoveryServiceTests
|
||||
}
|
||||
|
||||
private void SetupEntities(
|
||||
params (string EntityId, string? DeviceClass, string? Unit, string? FriendlyName)[] entities) =>
|
||||
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))]);
|
||||
.Returns([
|
||||
.. entities.Select(entity =>
|
||||
SetupEntity(entity.EntityId, entity.DeviceClass, entity.Unit, entity.FriendlyName))
|
||||
]);
|
||||
}
|
||||
|
||||
private void SetupEntitiesWithoutState(params string[] entityIds) =>
|
||||
private void SetupEntitiesWithoutState(params string[] entityIds)
|
||||
{
|
||||
_haContextMock
|
||||
.Setup(h => h.GetAllEntities())
|
||||
.Returns([.. entityIds.Select(entityId => new Entity(_haContextMock.Object, entityId))]);
|
||||
}
|
||||
|
||||
#region ExtractDeviceName
|
||||
|
||||
[Theory]
|
||||
[InlineData("sensor.sonoff_1002230e32_power", "sonoff_1002230e32")]
|
||||
[InlineData("sensor.sonoff_100215c534_power", "sonoff_100215c534")]
|
||||
[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);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GlobToRegex
|
||||
|
||||
[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);
|
||||
regex.IsMatch(input).Should().Be(expected);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Discovery
|
||||
|
||||
@@ -96,7 +144,7 @@ public class PowerSensorDiscoveryServiceTests
|
||||
(PowerMonitorTestData.MainMeterEntityId, "power", "W", "Total Home Power Usage"),
|
||||
("sensor.tv_power", "power", "W", "TV Power"));
|
||||
|
||||
var sut = CreateSut(mainMeterEntityId: string.Empty);
|
||||
var sut = CreateSut(string.Empty);
|
||||
|
||||
// Act
|
||||
var result = sut.DiscoverDeviceSensors();
|
||||
@@ -271,47 +319,6 @@ public class PowerSensorDiscoveryServiceTests
|
||||
|
||||
#endregion
|
||||
|
||||
#region ExtractDeviceName
|
||||
|
||||
[Theory]
|
||||
[InlineData("sensor.sonoff_1002230e32_power", "sonoff_1002230e32")]
|
||||
[InlineData("sensor.sonoff_100215c534_power", "sonoff_100215c534")]
|
||||
[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);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GlobToRegex
|
||||
|
||||
[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);
|
||||
regex.IsMatch(input).Should().Be(expected);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IsPowerSensor
|
||||
|
||||
[Theory]
|
||||
@@ -359,4 +366,4 @@ public class PowerSensorDiscoveryServiceTests
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user