Add shared test data builders and Qodana configuration
- Extract per-monitor *TestData helper classes and rework tests to use them - Add boiler run-time tracker abstraction (implementation pending) - Drop unused NordPool init/update-result types and stale PLAN.md - Add qodana.yaml with the inspection set to keep the analysis focused
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
@@ -12,104 +14,267 @@ public class ExhaustFanControlServiceTests
|
||||
{
|
||||
private const string FanEntityId = "switch.exhaust_fan";
|
||||
|
||||
private readonly ShowerMonitorOptions _defaultOptions = new()
|
||||
{
|
||||
ExhaustFanEntityId = FanEntityId,
|
||||
FanRunAfterShowerMinutes = 10
|
||||
};
|
||||
|
||||
private readonly ShowerMonitorOptions _defaultOptions = ShowerMonitorTestData.CreateOptions();
|
||||
private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider();
|
||||
private readonly Mock<IHaContext> _haContextMock = new();
|
||||
|
||||
private DateTimeOffset Now => _timeProvider.GetUtcNow();
|
||||
|
||||
public static IEnumerable<object[]> ShowerProgressFanStateCases =>
|
||||
[
|
||||
["active while fan is off", ShowerState.Active, "off", true],
|
||||
["active while fan is on", ShowerState.Active, "on", false],
|
||||
["active while fan reports uppercase on", ShowerState.Active, "ON", false],
|
||||
["active while fan is unavailable", ShowerState.Active, "unavailable", true],
|
||||
["active while fan state is unknown", ShowerState.Active, "unknown", true],
|
||||
["active while fan state is empty", ShowerState.Active, "", true],
|
||||
["active while fan state is missing", ShowerState.Active, null!, true],
|
||||
["suspected while fan is off", ShowerState.Suspected, "off", true],
|
||||
["suspected while fan is on", ShowerState.Suspected, "on", false],
|
||||
["idle does not touch the fan", ShowerState.Idle, "off", false],
|
||||
["declining does not turn the fan on", ShowerState.Declining, "off", false],
|
||||
["completed does not turn the fan on", ShowerState.Completed, "off", false]
|
||||
];
|
||||
|
||||
public static IEnumerable<object[]> FanRunAfterCases =>
|
||||
[
|
||||
["well before run-after duration", 10, 60, false],
|
||||
["one second before run-after duration", 10, 599, false],
|
||||
["exactly at run-after duration", 10, 600, true],
|
||||
["one second after run-after duration", 10, 601, true],
|
||||
["well after run-after duration", 10, 660, true],
|
||||
["zero-minute run-after turns off immediately", 0, 0, true],
|
||||
["long run-after keeps fan running", 30, 300, false]
|
||||
];
|
||||
|
||||
public static IEnumerable<object[]> ResetCases =>
|
||||
[
|
||||
["fan on after we turned it on", true, "on", true],
|
||||
["fan reports uppercase on", true, "ON", true],
|
||||
["fan already off again", true, "off", false],
|
||||
["fan unavailable", true, "unavailable", false],
|
||||
["fan state missing", true, null!, false],
|
||||
["we never turned the fan on", false, "on", false]
|
||||
];
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(ShowerProgressFanStateCases))]
|
||||
public void Evaluate_WhileShowerInProgress_TurnsFanOnOnlyWhenNotAlreadyRunning(
|
||||
string scenario,
|
||||
ShowerState state,
|
||||
string? fanState,
|
||||
bool expectTurnOn)
|
||||
{
|
||||
SetupFanState(fanState);
|
||||
var service = CreateService();
|
||||
|
||||
service.Evaluate(state, Now);
|
||||
|
||||
VerifySwitchCall("turn_on", expectTurnOn ? 1 : 0, because: $"scenario: {scenario}");
|
||||
VerifySwitchCall("turn_off", 0, because: $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(FanRunAfterCases))]
|
||||
public void Evaluate_AfterShowerEnds_TurnsFanOffOnlyOnceRunPeriodElapsed(
|
||||
string scenario,
|
||||
int runAfterMinutes,
|
||||
int idleOffsetSecondsFromShowerEnd,
|
||||
bool expectTurnOff)
|
||||
{
|
||||
SetupFanState("off");
|
||||
var service = CreateService(ShowerMonitorTestData.CreateOptions(
|
||||
fanRunAfterShowerMinutes: runAfterMinutes));
|
||||
var showerEnd = Now.AddMinutes(5);
|
||||
|
||||
service.Evaluate(ShowerState.Active, Now);
|
||||
service.Evaluate(ShowerState.Completed, showerEnd);
|
||||
service.Evaluate(ShowerState.Idle, showerEnd.AddSeconds(idleOffsetSecondsFromShowerEnd));
|
||||
|
||||
VerifySwitchCall("turn_on", 1, because: $"scenario: {scenario}");
|
||||
VerifySwitchCall("turn_off", expectTurnOff ? 1 : 0, because: $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ShowerState.Completed)]
|
||||
[InlineData(ShowerState.Declining)]
|
||||
public void Evaluate_EndingStates_StartRunAfterPeriod(ShowerState endingState)
|
||||
{
|
||||
SetupFanState("off");
|
||||
var service = CreateService();
|
||||
|
||||
service.Evaluate(ShowerState.Active, Now);
|
||||
service.Evaluate(endingState, Now.AddMinutes(5));
|
||||
|
||||
VerifySwitchCall("turn_off", 0);
|
||||
|
||||
service.Evaluate(ShowerState.Idle, Now.AddMinutes(15));
|
||||
|
||||
VerifySwitchCall("turn_off", 1);
|
||||
VerifySwitchCall("turn_on", 1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ShowerState.Idle)]
|
||||
[InlineData(ShowerState.Declining)]
|
||||
[InlineData(ShowerState.Completed)]
|
||||
public void Evaluate_AfterShowerEnds_WhenFanWasNotTurnedOnByUs_DoesNotTurnFanOff(ShowerState state)
|
||||
{
|
||||
SetupFanState("off");
|
||||
var service = CreateService();
|
||||
|
||||
service.Evaluate(state, Now);
|
||||
service.Evaluate(ShowerState.Idle, Now.AddHours(1));
|
||||
|
||||
VerifySwitchCall("turn_on", 0);
|
||||
VerifySwitchCall("turn_off", 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WhenShowerStaysActive_TurnsFanOnOnlyOnce()
|
||||
{
|
||||
SetupFanState("off");
|
||||
var service = CreateService();
|
||||
|
||||
service.Evaluate(ShowerState.Active, Now);
|
||||
service.Evaluate(ShowerState.Active, Now.AddSeconds(30));
|
||||
service.Evaluate(ShowerState.Suspected, Now.AddMinutes(1));
|
||||
|
||||
VerifySwitchCall("turn_on", 1);
|
||||
VerifySwitchCall("turn_off", 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WhenShowerResumesDuringRunPeriod_CancelsPendingFanOff()
|
||||
{
|
||||
SetupFanState("off");
|
||||
var service = CreateService();
|
||||
|
||||
service.Evaluate(ShowerState.Active, Now);
|
||||
service.Evaluate(ShowerState.Completed, Now.AddMinutes(5));
|
||||
service.Evaluate(ShowerState.Active, Now.AddMinutes(8));
|
||||
service.Evaluate(ShowerState.Idle, Now.AddMinutes(30));
|
||||
|
||||
VerifySwitchCall("turn_on", 1);
|
||||
VerifySwitchCall("turn_off", 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WhenAnewShowerStartsAfterFanStopped_TurnsFanOnAgain()
|
||||
{
|
||||
SetupFanState("off");
|
||||
var service = CreateService();
|
||||
|
||||
service.Evaluate(ShowerState.Active, Now);
|
||||
service.Evaluate(ShowerState.Completed, Now.AddMinutes(15));
|
||||
service.Evaluate(ShowerState.Idle, Now.AddMinutes(26));
|
||||
service.Evaluate(ShowerState.Active, Now.AddMinutes(40));
|
||||
|
||||
VerifySwitchCall("turn_on", 2);
|
||||
VerifySwitchCall("turn_off", 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_AfterShowerEnds_WhenFanWasAlreadyOn_DoesNotTurnItOff()
|
||||
{
|
||||
SetupFanState("on");
|
||||
var service = CreateService();
|
||||
|
||||
service.Evaluate(ShowerState.Active, Now);
|
||||
service.Evaluate(ShowerState.Completed, Now.AddMinutes(5));
|
||||
service.Evaluate(ShowerState.Idle, Now.AddMinutes(20));
|
||||
|
||||
VerifySwitchCall("turn_on", 0);
|
||||
VerifySwitchCall("turn_off", 0);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(ResetCases))]
|
||||
public void Reset_TurnsFanOffOnlyWhenWeTurnedItOnAndItIsStillOn(
|
||||
string scenario,
|
||||
bool turnOnFirst,
|
||||
string? currentFanState,
|
||||
bool expectTurnOff)
|
||||
{
|
||||
SetupFanState("off");
|
||||
var service = CreateService();
|
||||
|
||||
if (turnOnFirst)
|
||||
{
|
||||
service.Evaluate(ShowerState.Active, Now);
|
||||
SetupFanState(currentFanState);
|
||||
}
|
||||
|
||||
service.Reset();
|
||||
|
||||
VerifySwitchCall("turn_off", expectTurnOff ? 1 : 0, because: $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_IsIdempotent_AndPreventsLaterFanOff()
|
||||
{
|
||||
SetupFanState("off");
|
||||
var service = CreateService();
|
||||
|
||||
service.Evaluate(ShowerState.Active, Now);
|
||||
SetupFanState("on");
|
||||
|
||||
service.Reset();
|
||||
service.Reset();
|
||||
|
||||
VerifySwitchCall("turn_off", 1);
|
||||
|
||||
SetupFanState("off");
|
||||
service.Evaluate(ShowerState.Idle, Now.AddMinutes(20));
|
||||
|
||||
VerifySwitchCall("turn_off", 1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("switch.unknown_fan")]
|
||||
[InlineData(null)]
|
||||
public void Evaluate_WithConfiguredFanEntityId_TargetsThatExactEntity(string? entityId)
|
||||
{
|
||||
var service = CreateService(ShowerMonitorTestData.CreateOptions(exhaustFanEntityId: entityId!));
|
||||
|
||||
service.Evaluate(ShowerState.Active, Now);
|
||||
|
||||
VerifySwitchCall("turn_on", 1, entityId);
|
||||
}
|
||||
|
||||
private ExhaustFanControlService CreateService(ShowerMonitorOptions? options = null)
|
||||
{
|
||||
return new ExhaustFanControlService(_haContextMock.Object, Options.Create(options ?? _defaultOptions));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WhenActive_TurnsFanOn()
|
||||
private void SetupFanState(string? state)
|
||||
{
|
||||
var entityState = new EntityState { State = "off" };
|
||||
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState);
|
||||
|
||||
var service = CreateService();
|
||||
service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow);
|
||||
|
||||
_haContextMock.Verify(x => x.CallService("switch", "turn_on",
|
||||
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Once);
|
||||
_haContextMock
|
||||
.Setup(x => x.GetState(_defaultOptions.ExhaustFanEntityId))
|
||||
.Returns(ShowerMonitorTestData.FanState(state));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WhenActiveAndFanAlreadyOn_DoesNotCallAgain()
|
||||
private void VerifySwitchCall(
|
||||
string service,
|
||||
int expectedCount,
|
||||
string? expectedEntityId = FanEntityId,
|
||||
string? because = null)
|
||||
{
|
||||
var entityState = new EntityState { State = "on" };
|
||||
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState);
|
||||
var targets = _haContextMock.Invocations
|
||||
.Where(invocation => invocation.Method.Name == nameof(IHaContext.CallService)
|
||||
&& (string?)invocation.Arguments[0] == "switch"
|
||||
&& (string?)invocation.Arguments[1] == service)
|
||||
.Select(invocation => (ServiceTarget?)invocation.Arguments[2])
|
||||
.ToList();
|
||||
|
||||
var service = CreateService();
|
||||
service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow);
|
||||
|
||||
_haContextMock.Verify(x => x.CallService("switch", "turn_on",
|
||||
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_AfterShowerEndsAndRunPeriodElapsed_TurnsFanOff()
|
||||
{
|
||||
var entityState = new EntityState { State = "off" };
|
||||
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState);
|
||||
|
||||
var service = CreateService();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
service.Evaluate(ShowerState.Active, now);
|
||||
service.Evaluate(ShowerState.Completed, now.AddMinutes(5));
|
||||
service.Evaluate(ShowerState.Idle, now.AddMinutes(16));
|
||||
|
||||
_haContextMock.Verify(x => x.CallService("switch", "turn_off",
|
||||
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_AfterShowerEndsButRunPeriodNotElapsed_KeepsFanOn()
|
||||
{
|
||||
var entityState = new EntityState { State = "off" };
|
||||
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState);
|
||||
|
||||
var service = CreateService();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
service.Evaluate(ShowerState.Active, now);
|
||||
service.Evaluate(ShowerState.Completed, now.AddMinutes(5));
|
||||
service.Evaluate(ShowerState.Idle, now.AddMinutes(8));
|
||||
|
||||
_haContextMock.Verify(x => x.CallService("switch", "turn_off",
|
||||
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_WhenFanWasTurnedOnByUs_TurnsFanOff()
|
||||
{
|
||||
var entityState = new EntityState { State = "off" };
|
||||
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState);
|
||||
|
||||
var service = CreateService();
|
||||
service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow);
|
||||
|
||||
var fanOnState = new EntityState { State = "on" };
|
||||
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(fanOnState);
|
||||
|
||||
service.Reset();
|
||||
|
||||
_haContextMock.Verify(x => x.CallService("switch", "turn_off",
|
||||
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_WhenFanWasNotTurnedOnByUs_DoesNotTurnFanOff()
|
||||
{
|
||||
var service = CreateService();
|
||||
service.Reset();
|
||||
|
||||
_haContextMock.Verify(x => x.CallService("switch", "turn_off",
|
||||
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
|
||||
targets.Should().HaveCount(expectedCount, because);
|
||||
targets.Should().OnlyContain(
|
||||
target => target != null
|
||||
&& target.EntityIds != null
|
||||
&& target.EntityIds.Count == 1
|
||||
&& target.EntityIds.Single() == expectedEntityId,
|
||||
because);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,105 +1,128 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using ShowerMonitor.Models;
|
||||
using ShowerMonitorManager;
|
||||
|
||||
namespace ShowerMonitor.Manager.Tests;
|
||||
|
||||
public class HumidityRateCalculatorTests
|
||||
{
|
||||
private const int DefaultWindowSize = 5;
|
||||
private const int DefaultWindowSize = ShowerMonitorConsts.DefaultRateWindowSize;
|
||||
|
||||
private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider();
|
||||
|
||||
private DateTimeOffset Now => _timeProvider.GetUtcNow();
|
||||
|
||||
public static IEnumerable<object[]> RateCases =>
|
||||
[
|
||||
["no readings", 5, Array.Empty<double>(), Array.Empty<int>(), 0.0],
|
||||
["single reading", 5, new[] { 52.9 }, new[] { 0 }, 0.0],
|
||||
["rising humidity", 5, new[] { 52.9, 62.9 }, new[] { 0, 60 }, 10.0],
|
||||
["falling humidity", 5, new[] { 62.9, 52.9 }, new[] { 0, 120 }, -5.0],
|
||||
["same timestamp", 5, new[] { 52.9, 62.9 }, new[] { 0, 0 }, 0.0],
|
||||
["flat humidity", 5, new[] { 55.0, 55.0, 55.0 }, new[] { 0, 60, 120 }, 0.0],
|
||||
["linear three readings", 5, new[] { 50.0, 55.0, 60.0 }, new[] { 0, 60, 120 }, 5.0],
|
||||
["window drops stalest reading", 3, new[] { 52.9, 57.9, 62.9, 64.9 }, new[] { 0, 60, 120, 180 }, 3.5],
|
||||
["window keeps only last two readings", 2, new[] { 50.0, 55.0, 60.0 }, new[] { 0, 60, 120 }, 5.0],
|
||||
["single-sample window always returns zero", 1, new[] { 50.0, 55.0, 60.0 }, new[] { 0, 60, 120 }, 0.0],
|
||||
["zero-sized window always returns zero", 0, new[] { 50.0, 55.0, 60.0 }, new[] { 0, 60, 120 }, 0.0],
|
||||
["gap larger than window", 5, new[] { 20.0, 26.0 }, new[] { 0, 3_600 }, 0.1],
|
||||
["out of order timestamps", 5, new[] { 60.0, 50.0 }, new[] { 120, 0 }, 0.0],
|
||||
["very large rise", 5, new[] { 0.0, 10_000.0 }, new[] { 0, 60 }, 10_000.0],
|
||||
["negative humidity values", 5, new[] { -20.0, 0.0 }, new[] { 0, 60 }, 20.0],
|
||||
["tiny rise", 5, new[] { 50.0, 50.001 }, new[] { 0, 60 }, 0.001],
|
||||
["shower spike over sixty seconds", 5, new[] { 52.9, 59.9, 64.9 }, new[] { 0, 30, 60 }, 12.0],
|
||||
["middle readings do not affect the window endpoints", 3, new[] { 40.0, 80.0, 60.0, 45.0 }, new[] { 0, 30, 60, 90 }, -35.0],
|
||||
["small change over fifteen minutes", 5, new[] { 50.0, 50.6 }, new[] { 0, 900 }, 0.04]
|
||||
];
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(RateCases))]
|
||||
public void GetRatePerMinute_ShouldReturnExpectedRate(
|
||||
string scenario,
|
||||
int windowSize,
|
||||
double[] humidities,
|
||||
int[] offsetSeconds,
|
||||
double expectedRate)
|
||||
{
|
||||
humidities.Should().HaveSameCount(offsetSeconds);
|
||||
var calculator = new HumidityRateCalculator(windowSize);
|
||||
|
||||
for (var i = 0; i < humidities.Length; i++)
|
||||
{
|
||||
calculator.RecordReading(humidities[i], Now.AddSeconds(offsetSeconds[i]));
|
||||
}
|
||||
|
||||
calculator.GetRatePerMinute().Should().BeApproximately(expectedRate, 1e-6, $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetRatePerMinute_WithNoReadings_ReturnsZero()
|
||||
public void GetRatePerMinute_WithGeneratedLinearSeries_ReturnsSlopeForEveryWindowSize()
|
||||
{
|
||||
const double ratePerMinute = 2.5;
|
||||
var series = ShowerMonitorTestData.CreateLinearHumiditySeries(
|
||||
startHumidity: 45.0,
|
||||
ratePerMinute: ratePerMinute,
|
||||
sampleCount: 12);
|
||||
|
||||
for (var windowSize = 2; windowSize <= series.Count; windowSize++)
|
||||
{
|
||||
var calculator = new HumidityRateCalculator(windowSize);
|
||||
|
||||
foreach (var sample in series)
|
||||
{
|
||||
calculator.RecordReading(sample.Humidity, Now + sample.Offset);
|
||||
}
|
||||
|
||||
calculator.GetRatePerMinute()
|
||||
.Should()
|
||||
.BeApproximately(ratePerMinute, 1e-9, $"window size {windowSize}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetRatePerMinute_AfterReset_AndWithASingleNewReading_ReturnsZero()
|
||||
{
|
||||
var calculator = new HumidityRateCalculator(DefaultWindowSize);
|
||||
calculator.RecordReading(52.9, Now);
|
||||
calculator.RecordReading(62.9, Now.AddMinutes(1));
|
||||
|
||||
calculator.Reset();
|
||||
calculator.RecordReading(70.0, Now.AddMinutes(2));
|
||||
|
||||
calculator.GetRatePerMinute().Should().Be(0.0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetRatePerMinute_WithSingleReading_ReturnsZero()
|
||||
public void PreviousReading_IsNullBeforeAnyReading()
|
||||
{
|
||||
var calculator = new HumidityRateCalculator(DefaultWindowSize);
|
||||
calculator.RecordReading(52.9, DateTimeOffset.UtcNow);
|
||||
|
||||
calculator.GetRatePerMinute().Should().Be(0.0);
|
||||
calculator.PreviousReading.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetRatePerMinute_WithRisingHumidity_ReturnsPositiveRate()
|
||||
public void PreviousReading_TracksMostRecentReadingEvenAfterWindowEviction()
|
||||
{
|
||||
var calculator = new HumidityRateCalculator(DefaultWindowSize);
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
var calculator = new HumidityRateCalculator(2);
|
||||
|
||||
calculator.RecordReading(52.9, baseTime);
|
||||
calculator.RecordReading(62.9, baseTime.AddMinutes(1));
|
||||
calculator.RecordReading(52.9, Now);
|
||||
calculator.RecordReading(57.9, Now.AddMinutes(1));
|
||||
calculator.RecordReading(64.9, Now.AddMinutes(2));
|
||||
|
||||
calculator.GetRatePerMinute().Should().BeApproximately(10.0, 0.01);
|
||||
calculator.PreviousReading.Should().Be(64.9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetRatePerMinute_WithFallingHumidity_ReturnsNegativeRate()
|
||||
public void Reset_ClearsReadingsAndPreviousReading()
|
||||
{
|
||||
var calculator = new HumidityRateCalculator(DefaultWindowSize);
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
calculator.RecordReading(62.9, baseTime);
|
||||
calculator.RecordReading(52.9, baseTime.AddMinutes(2));
|
||||
|
||||
calculator.GetRatePerMinute().Should().BeApproximately(-5.0, 0.01);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetRatePerMinute_ExceedingWindowSize_DropsStalestReading()
|
||||
{
|
||||
var calculator = new HumidityRateCalculator(3);
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
calculator.RecordReading(52.9, baseTime);
|
||||
calculator.RecordReading(57.9, baseTime.AddMinutes(1));
|
||||
calculator.RecordReading(62.9, baseTime.AddMinutes(2));
|
||||
calculator.RecordReading(64.9, baseTime.AddMinutes(3));
|
||||
|
||||
var rate = calculator.GetRatePerMinute();
|
||||
rate.Should().BeApproximately(3.5, 0.01);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetRatePerMinute_WithSameTimestamp_ReturnsZero()
|
||||
{
|
||||
var calculator = new HumidityRateCalculator(DefaultWindowSize);
|
||||
var sameTime = DateTimeOffset.UtcNow;
|
||||
|
||||
calculator.RecordReading(52.9, sameTime);
|
||||
calculator.RecordReading(62.9, sameTime);
|
||||
|
||||
calculator.GetRatePerMinute().Should().Be(0.0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reset_ClearsAllReadings()
|
||||
{
|
||||
var calculator = new HumidityRateCalculator(DefaultWindowSize);
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
calculator.RecordReading(52.9, baseTime);
|
||||
calculator.RecordReading(62.9, baseTime.AddMinutes(1));
|
||||
calculator.RecordReading(52.9, Now);
|
||||
calculator.RecordReading(62.9, Now.AddMinutes(1));
|
||||
|
||||
calculator.Reset();
|
||||
|
||||
calculator.GetRatePerMinute().Should().Be(0.0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetRatePerMinute_SimulatesShowerSpike_DetectsHighRate()
|
||||
{
|
||||
var calculator = new HumidityRateCalculator(DefaultWindowSize);
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
calculator.RecordReading(52.9, baseTime);
|
||||
calculator.RecordReading(59.9, baseTime.AddSeconds(30));
|
||||
calculator.RecordReading(64.9, baseTime.AddSeconds(60));
|
||||
|
||||
var rate = calculator.GetRatePerMinute();
|
||||
rate.Should().BeGreaterThan(4.0);
|
||||
calculator.PreviousReading.Should().BeNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using ShowerMonitor.Models.Enums;
|
||||
using ShowerMonitorManager;
|
||||
using ShowerMonitorManager.Interface;
|
||||
@@ -9,16 +10,456 @@ namespace ShowerMonitor.Manager.Tests;
|
||||
|
||||
public class ShowerDetectionServiceTests
|
||||
{
|
||||
private readonly ShowerMonitorOptions _defaultOptions = new()
|
||||
private readonly ShowerMonitorOptions _defaultOptions = ShowerMonitorTestData.CreateOptions();
|
||||
private readonly FakeTimeProvider _timeProvider = ShowerMonitorTestData.CreateTimeProvider();
|
||||
|
||||
private DateTimeOffset Now => _timeProvider.GetUtcNow();
|
||||
|
||||
public static IEnumerable<object[]> IdleThresholdCases =>
|
||||
[
|
||||
["both thresholds met exactly", 52.0, 44.0, ShowerState.Suspected],
|
||||
["rate one step under threshold", 51.98, 44.0, ShowerState.Idle],
|
||||
["differential one step under threshold", 52.0, 44.02, ShowerState.Idle],
|
||||
["well above both thresholds", 60.0, 52.0, ShowerState.Suspected],
|
||||
["negative differential", 52.0, 60.0, ShowerState.Idle],
|
||||
["zero rate with large differential", 50.0, 42.0, ShowerState.Idle],
|
||||
["negative rate with large differential", 45.0, 37.0, ShowerState.Idle],
|
||||
["very large humidity spike", 1000.0, 500.0, ShowerState.Suspected]
|
||||
];
|
||||
|
||||
public static IEnumerable<object[]> ConfirmationCases =>
|
||||
[
|
||||
["confirmation window reached", 66.0, 49.5, 120, ShowerState.Active],
|
||||
["confirmation window not yet reached", 66.0, 49.5, 119, ShowerState.Suspected],
|
||||
["same instant as the spike", 66.0, 49.5, 0, ShowerState.Suspected],
|
||||
["peak humidity exactly at threshold", 58.0, 49.0, 120, ShowerState.Active],
|
||||
["peak humidity just below threshold", 57.5, 49.0, 120, ShowerState.Suspected],
|
||||
["differential exactly at threshold", 60.0, 52.0, 120, ShowerState.Active],
|
||||
["differential just below threshold", 66.0, 58.02, 120, ShowerState.Suspected],
|
||||
["very large humidity at confirmation", 1000.0, 900.0, 120, ShowerState.Active]
|
||||
];
|
||||
|
||||
public static IEnumerable<object[]> RecoveryBoundaryCases =>
|
||||
[
|
||||
["differential well under threshold", 52.0, ShowerState.Completed],
|
||||
["differential exactly at threshold", 50.0, ShowerState.Completed],
|
||||
["differential just above threshold", 49.98, ShowerState.Declining]
|
||||
];
|
||||
|
||||
public static IEnumerable<object[]> MaxDurationCases =>
|
||||
[
|
||||
["one second before max duration", 3_599, ShowerState.Active],
|
||||
["exactly at max duration", 3_600, ShowerState.Declining],
|
||||
["one second past max duration", 3_601, ShowerState.Declining]
|
||||
];
|
||||
|
||||
[Fact]
|
||||
public void InitialState_IsIdle()
|
||||
{
|
||||
SpikeRateThreshold = 4.0,
|
||||
MinDifferentialHumidity = 8.0,
|
||||
PeakHumidityThreshold = 58.0,
|
||||
ConfirmationWindowMinutes = 2,
|
||||
RecoveryDifferentialThreshold = 5.0,
|
||||
MaxShowerDurationMinutes = 60,
|
||||
RateWindowSize = 5
|
||||
};
|
||||
var service = CreateService();
|
||||
|
||||
service.CurrentState.Should().Be(ShowerState.Idle);
|
||||
service.CurrentSession.Should().BeNull();
|
||||
service.LastCompletedSession.Should().BeNull();
|
||||
service.TodaySessionCount.Should().Be(0);
|
||||
service.LastRate.Should().Be(0.0);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(IdleThresholdCases))]
|
||||
public void Evaluate_FromIdle_EntersSuspectedOnlyWhenRateAndDifferentialMeetThresholds(
|
||||
string scenario,
|
||||
double bathroomHumidity,
|
||||
double mainHomeHumidity,
|
||||
ShowerState expectedState)
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
service.Evaluate(50.0, 42.0, start);
|
||||
|
||||
var state = service.Evaluate(bathroomHumidity, mainHomeHumidity, start.AddSeconds(30));
|
||||
|
||||
state.Should().Be(expectedState, $"scenario: {scenario}");
|
||||
service.CurrentState.Should().Be(expectedState, $"scenario: {scenario}");
|
||||
service.TodaySessionCount.Should().Be(0);
|
||||
service.LastCompletedSession.Should().BeNull();
|
||||
|
||||
if (expectedState == ShowerState.Suspected)
|
||||
{
|
||||
service.CurrentSession.Should().NotBeNull();
|
||||
service.CurrentSession!.StartTime.Should().Be(start.AddSeconds(30));
|
||||
}
|
||||
else
|
||||
{
|
||||
service.CurrentSession.Should().BeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_FromIdle_WithGradualRise_RemainsIdle()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
service.Evaluate(52.9, 50.5, start);
|
||||
|
||||
var state = service.Evaluate(53.2, 50.5, start.AddSeconds(30));
|
||||
|
||||
state.Should().Be(ShowerState.Idle);
|
||||
service.LastRate.Should().BeApproximately(0.6, 1e-9);
|
||||
service.CurrentSession.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_FromIdle_WithNoPreviousSample_RemainsIdle()
|
||||
{
|
||||
var service = CreateService();
|
||||
|
||||
var state = service.Evaluate(60.0, 50.0, Now);
|
||||
|
||||
state.Should().Be(ShowerState.Idle);
|
||||
service.LastRate.Should().Be(0.0);
|
||||
service.CurrentSession.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_FromIdle_WithStaleTimestamp_RemainsIdle()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
service.Evaluate(52.9, 50.5, start);
|
||||
|
||||
var state = service.Evaluate(70.0, 50.0, start.AddSeconds(-30));
|
||||
|
||||
state.Should().Be(ShowerState.Idle);
|
||||
service.LastRate.Should().Be(0.0);
|
||||
service.CurrentSession.Should().BeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(ConfirmationCases))]
|
||||
public void Evaluate_FromSuspected_ConfirmsOnlyAfterWindowPeakAndDifferential(
|
||||
string scenario,
|
||||
double bathroomHumidity,
|
||||
double mainHomeHumidity,
|
||||
int secondsAfterSpike,
|
||||
ShowerState expectedState)
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
EvaluateBaselineAndSpike(service, start);
|
||||
|
||||
var state = service.Evaluate(
|
||||
bathroomHumidity,
|
||||
mainHomeHumidity,
|
||||
start.AddSeconds(30 + secondsAfterSpike));
|
||||
|
||||
state.Should().Be(expectedState, $"scenario: {scenario}");
|
||||
service.CurrentState.Should().Be(expectedState, $"scenario: {scenario}");
|
||||
service.TodaySessionCount.Should().Be(0);
|
||||
service.LastCompletedSession.Should().BeNull();
|
||||
|
||||
if (expectedState == ShowerState.Active)
|
||||
{
|
||||
service.CurrentSession.Should().NotBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_FromSuspected_WithFallingRateButHighDifferential_RemainsSuspected()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
EvaluateBaselineAndSpike(service, start);
|
||||
|
||||
var state = service.Evaluate(52.0, 43.0, start.AddMinutes(2));
|
||||
|
||||
state.Should().Be(ShowerState.Suspected);
|
||||
service.CurrentSession.Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_FromSuspected_WhenRateAndDifferentialDrop_ReturnsToIdleWithoutSession()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
EvaluateBaselineAndSpike(service, start);
|
||||
|
||||
var state = service.Evaluate(50.0, 43.0, start.AddMinutes(2));
|
||||
|
||||
state.Should().Be(ShowerState.Idle);
|
||||
service.CurrentState.Should().Be(ShowerState.Idle);
|
||||
service.CurrentSession.Should().BeNull();
|
||||
service.TodaySessionCount.Should().Be(0);
|
||||
service.LastCompletedSession.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WithSustainedSpike_TransitionsToActive()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
EvaluateBaselineAndSpike(service, start);
|
||||
|
||||
var state = service.Evaluate(68.0, 49.5, start.AddMinutes(3));
|
||||
|
||||
state.Should().Be(ShowerState.Active);
|
||||
service.CurrentState.Should().Be(ShowerState.Active);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_TracksLastRate()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
|
||||
service.LastRate.Should().Be(0.0);
|
||||
|
||||
EvaluateBaselineAndSpike(service, start);
|
||||
|
||||
service.LastRate.Should().BeApproximately(13.1, 1e-6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_TracksCurrentSessionPeakAndPreEventHumidity()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
service.Evaluate(52.9, 50.5, start);
|
||||
service.Evaluate(58.5, 49.5, start.AddSeconds(30));
|
||||
|
||||
var session = service.CurrentSession!;
|
||||
session.StartTime.Should().Be(start.AddSeconds(30));
|
||||
session.PreEventHumidity.Should().Be(58.5);
|
||||
session.PeakHumidity.Should().Be(58.5);
|
||||
session.PeakTime.Should().Be(start.AddSeconds(30));
|
||||
session.EndTime.Should().BeNull();
|
||||
|
||||
service.Evaluate(66.0, 49.5, start.AddSeconds(60));
|
||||
|
||||
session.PeakHumidity.Should().Be(66.0);
|
||||
session.PeakTime.Should().Be(start.AddSeconds(60));
|
||||
|
||||
service.Evaluate(64.0, 49.5, start.AddSeconds(90));
|
||||
|
||||
session.PeakHumidity.Should().Be(66.0);
|
||||
session.PeakTime.Should().Be(start.AddSeconds(60));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_FullShowerCycle_CompletesSession()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
|
||||
DriveToActive(service, start);
|
||||
service.CurrentState.Should().Be(ShowerState.Active);
|
||||
service.TodaySessionCount.Should().Be(0);
|
||||
|
||||
DryDownToCompletion(service, start);
|
||||
|
||||
service.CurrentState.Should().Be(ShowerState.Completed);
|
||||
service.TodaySessionCount.Should().Be(1);
|
||||
service.CurrentSession.Should().BeNull();
|
||||
|
||||
service.LastCompletedSession.Should().NotBeNull();
|
||||
var session = service.LastCompletedSession!;
|
||||
session.StartTime.Should().Be(start.AddSeconds(30));
|
||||
session.EndTime.Should().Be(start.AddMinutes(13));
|
||||
session.PeakHumidity.Should().Be(70.0);
|
||||
session.PeakTime.Should().Be(start.AddMinutes(4));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_Active_DeclinesWhenRateTurnsNegativeAndDifferentialDropsBelowThreshold()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
DriveToActive(service, start);
|
||||
|
||||
service.Evaluate(66.0, 49.5, start.AddMinutes(4));
|
||||
service.Evaluate(64.0, 49.5, start.AddMinutes(5));
|
||||
service.Evaluate(62.0, 49.5, start.AddMinutes(6));
|
||||
service.Evaluate(60.0, 49.5, start.AddMinutes(7));
|
||||
var stillActive = service.Evaluate(58.0, 49.5, start.AddMinutes(8));
|
||||
var declining = service.Evaluate(56.0, 49.5, start.AddMinutes(9));
|
||||
|
||||
stillActive.Should().Be(ShowerState.Active);
|
||||
declining.Should().Be(ShowerState.Declining);
|
||||
service.TodaySessionCount.Should().Be(0);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(RecoveryBoundaryCases))]
|
||||
public void Evaluate_Declining_CompletesOnlyWhenDifferentialRecovers(
|
||||
string scenario,
|
||||
double mainHomeHumidity,
|
||||
ShowerState expectedState)
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
DriveToActive(service, start);
|
||||
DryDownToThreshold(service, start);
|
||||
|
||||
var declining = service.Evaluate(55.0, mainHomeHumidity, start.AddMinutes(11));
|
||||
var state = service.Evaluate(55.0, mainHomeHumidity, start.AddMinutes(12));
|
||||
|
||||
declining.Should().Be(ShowerState.Declining, $"scenario: {scenario}");
|
||||
state.Should().Be(expectedState, $"scenario: {scenario}");
|
||||
|
||||
if (expectedState == ShowerState.Completed)
|
||||
{
|
||||
service.TodaySessionCount.Should().Be(1);
|
||||
service.LastCompletedSession.Should().NotBeNull();
|
||||
service.LastCompletedSession!.EndTime.Should().Be(start.AddMinutes(12));
|
||||
}
|
||||
else
|
||||
{
|
||||
service.TodaySessionCount.Should().Be(0);
|
||||
service.LastCompletedSession.Should().BeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(MaxDurationCases))]
|
||||
public void Evaluate_Active_DeclinesAtMaxShowerDuration(
|
||||
string scenario,
|
||||
int secondsAfterSessionStart,
|
||||
ShowerState expectedState)
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
DriveToActive(service, start);
|
||||
|
||||
var state = service.Evaluate(68.0, 49.5, start.AddSeconds(30 + secondsAfterSessionStart));
|
||||
|
||||
state.Should().Be(expectedState, $"scenario: {scenario}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_Declining_PastMaxDuration_CompletesEvenWithHighDifferential()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
DriveToActive(service, start);
|
||||
|
||||
var declining = service.Evaluate(68.0, 49.5, start.AddSeconds(30 + 3_600));
|
||||
var completed = service.Evaluate(68.0, 49.5, start.AddSeconds(30 + 3_601));
|
||||
|
||||
declining.Should().Be(ShowerState.Declining);
|
||||
completed.Should().Be(ShowerState.Completed);
|
||||
service.TodaySessionCount.Should().Be(1);
|
||||
service.LastCompletedSession!.EndTime.Should().Be(start.AddSeconds(30 + 3_601));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_Completed_TransitionsToIdleAndResetsRateWindow()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
DriveToCompleted(service, start);
|
||||
service.CurrentState.Should().Be(ShowerState.Completed);
|
||||
|
||||
var idle = service.Evaluate(53.0, 50.5, start.AddMinutes(14));
|
||||
idle.Should().Be(ShowerState.Idle);
|
||||
service.LastRate.Should().NotBe(0.0);
|
||||
|
||||
var stillIdle = service.Evaluate(53.1, 50.5, start.AddMinutes(15));
|
||||
stillIdle.Should().Be(ShowerState.Idle);
|
||||
service.LastRate.Should().Be(0.0);
|
||||
service.TodaySessionCount.Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_BackToBackShowers_CountsAsTwoSessions()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
|
||||
DriveToCompleted(service, start);
|
||||
service.TodaySessionCount.Should().Be(1);
|
||||
|
||||
service.Evaluate(53.0, 50.5, start.AddMinutes(14));
|
||||
DriveToCompleted(service, start.AddMinutes(15));
|
||||
|
||||
service.TodaySessionCount.Should().Be(2);
|
||||
service.LastCompletedSession.Should().NotBeNull();
|
||||
service.LastCompletedSession!.StartTime.Should().Be(start.AddMinutes(15).AddSeconds(30));
|
||||
service.LastCompletedSession!.EndTime.Should().Be(start.AddMinutes(28));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResetDailyCounters_AfterCompletedSession_ClearsCounters()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
DriveToCompleted(service, start);
|
||||
|
||||
service.ResetDailyCounters();
|
||||
|
||||
service.TodaySessionCount.Should().Be(0);
|
||||
service.LastCompletedSession.Should().BeNull();
|
||||
service.CurrentState.Should().Be(ShowerState.Completed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResetDailyCounters_WhileActive_KeepsLiveSession()
|
||||
{
|
||||
var service = CreateService();
|
||||
var start = Now;
|
||||
DriveToActive(service, start);
|
||||
var session = service.CurrentSession;
|
||||
|
||||
service.ResetDailyCounters();
|
||||
|
||||
service.CurrentState.Should().Be(ShowerState.Active);
|
||||
service.CurrentSession.Should().BeSameAs(session);
|
||||
service.TodaySessionCount.Should().Be(0);
|
||||
service.LastCompletedSession.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WithCustomSpikeThreshold_RequiresConfiguredRate()
|
||||
{
|
||||
var service = CreateService(options: ShowerMonitorTestData.CreateOptions(spikeRateThreshold: 20.0));
|
||||
var start = Now;
|
||||
|
||||
service.Evaluate(50.0, 42.0, start);
|
||||
var state = service.Evaluate(52.0, 44.0, start.AddSeconds(30));
|
||||
|
||||
state.Should().Be(ShowerState.Idle);
|
||||
service.LastRate.Should().BeApproximately(4.0, 1e-9);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WithCustomConfirmationWindow_UsesConfiguredWindow()
|
||||
{
|
||||
var service = CreateService(options: ShowerMonitorTestData.CreateOptions(confirmationWindowMinutes: 5));
|
||||
var start = Now;
|
||||
EvaluateBaselineAndSpike(service, start);
|
||||
|
||||
var early = service.Evaluate(68.0, 49.5, start.AddMinutes(3));
|
||||
var confirmed = service.Evaluate(68.0, 49.5, start.AddMinutes(5).AddSeconds(30));
|
||||
|
||||
early.Should().Be(ShowerState.Suspected);
|
||||
confirmed.Should().Be(ShowerState.Active);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WithGeneratedHumiditySweep_ActivatesOnlyAtOrAbovePeakThreshold()
|
||||
{
|
||||
var start = Now;
|
||||
|
||||
for (var humidity = 57.0; humidity <= 61.0; humidity += 0.5)
|
||||
{
|
||||
var service = CreateService();
|
||||
EvaluateBaselineAndSpike(service, start);
|
||||
|
||||
var state = service.Evaluate(humidity, 49.0, start.AddSeconds(30 + 120));
|
||||
var expected = humidity >= 58.0 ? ShowerState.Active : ShowerState.Suspected;
|
||||
|
||||
state.Should().Be(expected, $"humidity {humidity:F1} at confirmation time");
|
||||
}
|
||||
}
|
||||
|
||||
private ShowerDetectionService CreateService(
|
||||
IHumidityRateCalculator? rateCalculator = null,
|
||||
@@ -27,141 +468,44 @@ public class ShowerDetectionServiceTests
|
||||
var opts = options ?? _defaultOptions;
|
||||
var calculator = rateCalculator ?? new HumidityRateCalculator(opts.RateWindowSize);
|
||||
|
||||
return new ShowerDetectionService(
|
||||
calculator,
|
||||
Options.Create(opts));
|
||||
return new ShowerDetectionService(calculator, Options.Create(opts));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitialState_IsIdle()
|
||||
private static void EvaluateBaselineAndSpike(ShowerDetectionService service, DateTimeOffset start)
|
||||
{
|
||||
var service = CreateService();
|
||||
service.CurrentState.Should().Be(ShowerState.Idle);
|
||||
service.Evaluate(52.9, 50.5, start);
|
||||
service.Evaluate(58.5, 49.5, start.AddSeconds(30));
|
||||
service.Evaluate(66.0, 49.5, start.AddSeconds(60));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WithNoSpike_RemainsIdle()
|
||||
private static void DriveToActive(ShowerDetectionService service, DateTimeOffset start)
|
||||
{
|
||||
var service = CreateService();
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
service.Evaluate(52.9, 50.5, baseTime);
|
||||
service.Evaluate(53.2, 50.5, baseTime.AddSeconds(30));
|
||||
|
||||
service.CurrentState.Should().Be(ShowerState.Idle);
|
||||
EvaluateBaselineAndSpike(service, start);
|
||||
service.Evaluate(68.0, 49.5, start.AddMinutes(3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WithShowerSpike_TransitionsToSuspected()
|
||||
private static void DriveToCompleted(ShowerDetectionService service, DateTimeOffset start)
|
||||
{
|
||||
var service = CreateService();
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
service.Evaluate(52.9, 50.5, baseTime);
|
||||
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
|
||||
var state = service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
|
||||
|
||||
state.Should().Be(ShowerState.Suspected);
|
||||
DriveToActive(service, start);
|
||||
DryDownToCompletion(service, start);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_WithSustainedSpike_TransitionsToActive()
|
||||
private static void DryDownToThreshold(ShowerDetectionService service, DateTimeOffset start)
|
||||
{
|
||||
var service = CreateService();
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
service.Evaluate(52.9, 50.5, baseTime);
|
||||
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
|
||||
service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
|
||||
|
||||
var state = service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3));
|
||||
|
||||
state.Should().Be(ShowerState.Active);
|
||||
service.Evaluate(70.0, 50.0, start.AddMinutes(4));
|
||||
service.Evaluate(68.0, 50.0, start.AddMinutes(5));
|
||||
service.Evaluate(66.0, 50.0, start.AddMinutes(6));
|
||||
service.Evaluate(64.0, 50.0, start.AddMinutes(7));
|
||||
service.Evaluate(62.0, 50.0, start.AddMinutes(8));
|
||||
service.Evaluate(60.0, 50.0, start.AddMinutes(9));
|
||||
service.Evaluate(58.0, 50.0, start.AddMinutes(10));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_FullShowerCycle_CompletesSession()
|
||||
private static void DryDownToCompletion(ShowerDetectionService service, DateTimeOffset start)
|
||||
{
|
||||
var service = CreateService();
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
service.Evaluate(52.9, 50.5, baseTime);
|
||||
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
|
||||
service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
|
||||
service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3));
|
||||
|
||||
service.CurrentState.Should().Be(ShowerState.Active);
|
||||
|
||||
service.Evaluate(61.0, 50.0, baseTime.AddMinutes(10));
|
||||
service.Evaluate(56.0, 50.5, baseTime.AddMinutes(15));
|
||||
|
||||
service.Evaluate(53.5, 50.5, baseTime.AddMinutes(20));
|
||||
|
||||
service.TodaySessionCount.Should().BeGreaterThanOrEqualTo(1);
|
||||
service.LastCompletedSession.Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_SuspectedThenDrops_ReturnsToIdle()
|
||||
{
|
||||
var service = CreateService();
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
service.Evaluate(52.9, 50.5, baseTime);
|
||||
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
|
||||
service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
|
||||
|
||||
service.CurrentState.Should().Be(ShowerState.Suspected);
|
||||
|
||||
service.Evaluate(57.0, 50.0, baseTime.AddMinutes(2));
|
||||
service.Evaluate(54.0, 50.0, baseTime.AddMinutes(3));
|
||||
service.Evaluate(52.5, 50.5, baseTime.AddMinutes(4));
|
||||
service.Evaluate(52.0, 50.5, baseTime.AddMinutes(5));
|
||||
|
||||
service.CurrentState.Should().Be(ShowerState.Idle);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResetDailyCounters_ClearsSessionCount()
|
||||
{
|
||||
var service = CreateService();
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
service.Evaluate(52.9, 50.5, baseTime);
|
||||
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
|
||||
service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
|
||||
service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3));
|
||||
service.Evaluate(56.0, 50.5, baseTime.AddMinutes(15));
|
||||
service.Evaluate(53.5, 50.5, baseTime.AddMinutes(20));
|
||||
|
||||
service.ResetDailyCounters();
|
||||
|
||||
service.TodaySessionCount.Should().Be(0);
|
||||
service.LastCompletedSession.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Evaluate_BackToBackShowers_CountsAsTwoSessions()
|
||||
{
|
||||
var service = CreateService();
|
||||
var baseTime = DateTimeOffset.UtcNow;
|
||||
|
||||
service.Evaluate(52.9, 50.5, baseTime);
|
||||
service.Evaluate(58.5, 49.5, baseTime.AddSeconds(30));
|
||||
service.Evaluate(66.0, 49.5, baseTime.AddSeconds(60));
|
||||
service.Evaluate(68.0, 49.5, baseTime.AddMinutes(3));
|
||||
service.Evaluate(56.0, 50.5, baseTime.AddMinutes(10));
|
||||
service.Evaluate(53.5, 50.5, baseTime.AddMinutes(15));
|
||||
|
||||
var firstCount = service.TodaySessionCount;
|
||||
|
||||
service.Evaluate(52.9, 50.5, baseTime.AddMinutes(20));
|
||||
service.Evaluate(58.5, 49.5, baseTime.AddMinutes(20).AddSeconds(30));
|
||||
service.Evaluate(66.0, 49.5, baseTime.AddMinutes(21));
|
||||
service.Evaluate(68.0, 49.5, baseTime.AddMinutes(23));
|
||||
service.Evaluate(56.0, 50.5, baseTime.AddMinutes(30));
|
||||
service.Evaluate(53.5, 50.5, baseTime.AddMinutes(35));
|
||||
|
||||
service.TodaySessionCount.Should().BeGreaterThan(firstCount);
|
||||
DryDownToThreshold(service, start);
|
||||
service.Evaluate(57.0, 50.0, start.AddMinutes(11));
|
||||
service.Evaluate(56.0, 50.0, start.AddMinutes(12));
|
||||
service.Evaluate(55.0, 50.0, start.AddMinutes(13));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,19 +8,19 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="8.0.0">
|
||||
<PackageReference Include="coverlet.collector" Version="10.1.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.4.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="11.0.1" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="FluentAssertions" Version="8.11.0" />
|
||||
<PackageReference Include="Moq" Version="4.21.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using ShowerMonitor.Models;
|
||||
using ShowerMonitorManager.Models;
|
||||
|
||||
namespace ShowerMonitor.Manager.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Shared, deterministic fixtures for the shower monitor tests.
|
||||
/// Keeping options, fan states and sample series here avoids copy-pasted setup
|
||||
/// across test classes and keeps every timestamp independent of the wall clock.
|
||||
/// </summary>
|
||||
internal static class ShowerMonitorTestData
|
||||
{
|
||||
/// <summary>Fixed base time used by all timestamp-sensitive tests.</summary>
|
||||
public static readonly DateTimeOffset BaseTimestamp = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
/// <summary>Creates a fake clock positioned at <see cref="BaseTimestamp"/> unless overridden.</summary>
|
||||
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? start = null) => new(start ?? BaseTimestamp);
|
||||
|
||||
/// <summary>
|
||||
/// Builds monitor options from the production defaults, overriding only the
|
||||
/// values a test cares about.
|
||||
/// </summary>
|
||||
public static ShowerMonitorOptions CreateOptions(
|
||||
string exhaustFanEntityId = ShowerMonitorConsts.ExhaustFanEntityId,
|
||||
int? fanRunAfterShowerMinutes = null,
|
||||
double spikeRateThreshold = ShowerMonitorConsts.DefaultSpikeRateThreshold,
|
||||
double minDifferentialHumidity = ShowerMonitorConsts.DefaultMinDifferentialHumidity,
|
||||
double peakHumidityThreshold = ShowerMonitorConsts.DefaultPeakHumidityThreshold,
|
||||
int confirmationWindowMinutes = ShowerMonitorConsts.DefaultConfirmationWindowMinutes,
|
||||
double recoveryDifferentialThreshold = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold,
|
||||
int? maxShowerDurationMinutes = null,
|
||||
int rateWindowSize = ShowerMonitorConsts.DefaultRateWindowSize)
|
||||
{
|
||||
return new ShowerMonitorOptions
|
||||
{
|
||||
ExhaustFanEntityId = exhaustFanEntityId,
|
||||
FanRunAfterShowerMinutes = fanRunAfterShowerMinutes
|
||||
?? (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes,
|
||||
SpikeRateThreshold = spikeRateThreshold,
|
||||
MinDifferentialHumidity = minDifferentialHumidity,
|
||||
PeakHumidityThreshold = peakHumidityThreshold,
|
||||
ConfirmationWindowMinutes = confirmationWindowMinutes,
|
||||
RecoveryDifferentialThreshold = recoveryDifferentialThreshold,
|
||||
MaxShowerDurationMinutes = maxShowerDurationMinutes
|
||||
?? (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes,
|
||||
RateWindowSize = rateWindowSize
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Creates the HA state payload for the exhaust fan.</summary>
|
||||
public static EntityState FanState(string? state) => new() { State = state };
|
||||
|
||||
/// <summary>A humidity sample with its offset from a test's base timestamp.</summary>
|
||||
public readonly record struct HumiditySample(double Humidity, TimeSpan Offset);
|
||||
|
||||
/// <summary>Builds a sample series from (humidity, offset-in-seconds) pairs.</summary>
|
||||
public static IReadOnlyList<HumiditySample> CreateHumiditySeries(
|
||||
params (double Humidity, int OffsetSeconds)[] samples) =>
|
||||
samples.Select(sample => new HumiditySample(sample.Humidity, TimeSpan.FromSeconds(sample.OffsetSeconds)))
|
||||
.ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// Generates evenly spaced samples along a constant humidity slope, useful for
|
||||
/// exercising every window size against a known rate.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<HumiditySample> CreateLinearHumiditySeries(
|
||||
double startHumidity,
|
||||
double ratePerMinute,
|
||||
int sampleCount,
|
||||
int intervalSeconds = 60) =>
|
||||
Enumerable.Range(0, sampleCount)
|
||||
.Select(i => new HumiditySample(
|
||||
startHumidity + (ratePerMinute * i * intervalSeconds / 60.0),
|
||||
TimeSpan.FromSeconds(i * intervalSeconds)))
|
||||
.ToArray();
|
||||
}
|
||||
Reference in New Issue
Block a user