Add shared test data builders and Qodana configuration

- Extract per-monitor *TestData helper classes and rework tests to use them
- Add boiler run-time tracker abstraction (implementation pending)
- Drop unused NordPool init/update-result types and stale PLAN.md
- Add qodana.yaml with the inspection set to keep the analysis focused
This commit is contained in:
2026-11-29 21:30:13 +02:00
parent 1152462765
commit 5777e641f6
79 changed files with 7162 additions and 3196 deletions
@@ -11,14 +11,10 @@ namespace LightMonitor.Manager.Tests;
public class LightControlServiceTests
{
private const string LightEntityId = "light.sonoff_1002214d40";
private const string SunEntityId = "sun.sun";
private const string LightEntityId = LightMonitorTestData.LightEntityId;
private const string SunEntityId = LightMonitorTestData.SunEntityId;
private readonly LightMonitorOptions _defaultOptions = new()
{
LightEntityId = LightEntityId,
SunEntityId = SunEntityId
};
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
private readonly Mock<IHaContext> _haContextMock = new();
@@ -30,87 +26,116 @@ public class LightControlServiceTests
Options.Create(options ?? _defaultOptions));
}
[Fact]
public void TurnOnLight_WhenDarkAndLightIsOff_ShouldTurnOnLight()
private void SetupState(string entityId, string? state)
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon });
_haContextMock.Setup(x => x.GetState(LightEntityId))
.Returns(new EntityState { State = "off" });
_haContextMock.Setup(x => x.GetState(entityId))
.Returns(LightMonitorTestData.CreateOptionalState(state));
}
var service = CreateService();
service.TurnOnLight();
private void VerifyTurnOn(string entityId, bool shouldTurnOn)
{
if (!shouldTurnOn)
{
_haContextMock.Verify(x => x.CallService(
It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
Times.Never);
return;
}
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Once);
It.Is<ServiceTarget>(target => target.EntityIds != null && target.EntityIds.Contains(entityId)),
It.IsAny<object?>()),
Times.Once);
}
[Theory]
[MemberData(nameof(LightMonitorTestData.SunStateTurnOnCases), MemberType = typeof(LightMonitorTestData))]
public void TurnOnLight_ShouldOnlyTurnOnWhenSunIsBelowHorizon(string? sunState, bool shouldTurnOn)
{
SetupState(SunEntityId, sunState);
SetupState(LightEntityId, "off");
CreateService().TurnOnLight();
VerifyTurnOn(LightEntityId, shouldTurnOn);
}
[Theory]
[MemberData(nameof(LightMonitorTestData.LightStateTurnOnCases), MemberType = typeof(LightMonitorTestData))]
public void TurnOnLight_WhenSunIsBelowHorizon_ShouldOnlyTurnOnWhenLightIsNotAlreadyOn(
string? lightState,
bool shouldTurnOn)
{
SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon);
SetupState(LightEntityId, lightState);
CreateService().TurnOnLight();
VerifyTurnOn(LightEntityId, shouldTurnOn);
}
[Fact]
public void TurnOnLight_WhenDarkAndLightIsAlreadyOn_ShouldNotCallService()
public void TurnOnLight_ShouldTargetTheConfiguredLightEntity()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon });
_haContextMock.Setup(x => x.GetState(LightEntityId))
.Returns(new EntityState { State = "on" });
const string customLightEntityId = "light.kitchen_ceiling";
var options = LightMonitorTestData.CreateOptions(lightEntityId: customLightEntityId);
var service = CreateService();
service.TurnOnLight();
SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon);
SetupState(customLightEntityId, "off");
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
CreateService(options).TurnOnLight();
VerifyTurnOn(customLightEntityId, true);
}
[Fact]
public void TurnOnLight_WhenSunIsAboveHorizon_ShouldNotTurnOnLight()
public void TurnOnLight_WithDefaultOptions_ShouldTargetTheDefaultLightEntity()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns(new EntityState { State = LightMonitorConsts.SunAboveHorizon });
var options = new LightMonitorOptions();
var service = CreateService();
service.TurnOnLight();
SetupState(LightMonitorConsts.DefaultSunEntityId, LightMonitorConsts.SunBelowHorizon);
SetupState(LightMonitorConsts.DefaultLightEntityId, null);
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
CreateService(options).TurnOnLight();
VerifyTurnOn(LightMonitorConsts.DefaultLightEntityId, true);
}
[Fact]
public void TurnOnLight_WhenSunStateIsNull_ShouldNotTurnOnLight()
public void TurnOnLight_WhenSunIsAboveHorizon_ShouldNotReadTheLightState()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns((EntityState?)null);
SetupState(SunEntityId, LightMonitorConsts.SunAboveHorizon);
var service = CreateService();
service.TurnOnLight();
CreateService().TurnOnLight();
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
_haContextMock.Verify(x => x.GetState(LightEntityId), Times.Never);
}
[Theory]
[InlineData("")]
[InlineData(" ")]
public void TurnOnLight_WhenSunEntityIdIsBlank_ShouldNotTurnOnLight(string sunEntityId)
{
var options = LightMonitorTestData.CreateOptions(sunEntityId: sunEntityId);
SetupState(LightEntityId, "off");
CreateService(options).TurnOnLight();
VerifyTurnOn(LightEntityId, false);
}
[Fact]
public void TurnOnLight_WhenSunStateIsUnavailable_ShouldNotTurnOnLight()
public void TurnOnLight_ShouldReadEachStateAtMostOnce()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns(new EntityState { State = "unavailable" });
SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon);
SetupState(LightEntityId, LightMonitorConsts.LightOnState);
var service = CreateService();
service.TurnOnLight();
CreateService().TurnOnLight();
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
}
[Fact]
public void TurnOnLight_WhenLightStateIsNull_ShouldTurnOnLight()
{
_haContextMock.Setup(x => x.GetState(SunEntityId))
.Returns(new EntityState { State = LightMonitorConsts.SunBelowHorizon });
_haContextMock.Setup(x => x.GetState(LightEntityId))
.Returns((EntityState?)null);
var service = CreateService();
service.TurnOnLight();
_haContextMock.Verify(x => x.CallService("light", "turn_on",
It.IsAny<ServiceTarget>(), It.IsAny<object?>()), Times.Once);
_haContextMock.Verify(x => x.GetState(SunEntityId), Times.Once);
_haContextMock.Verify(x => x.GetState(LightEntityId), Times.Once);
VerifyTurnOn(LightEntityId, false);
}
}
@@ -8,18 +8,18 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="8.0.0">
<PackageReference Include="coverlet.collector" Version="10.1.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="FluentAssertions" Version="8.11.0" />
<PackageReference Include="Moq" Version="4.21.0" />
</ItemGroup>
<ItemGroup>
@@ -1,4 +1,5 @@
using System.Reactive.Subjects;
using FluentAssertions;
using LightMonitor.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -13,25 +14,28 @@ namespace LightMonitor.Manager.Tests;
public class LightMonitorInitTests
{
private const string SunEntityId = "sun.sun";
private const string PersonEntityId = "person.marius";
private const string SunEntityId = LightMonitorTestData.SunEntityId;
private const string PersonEntityId = LightMonitorTestData.PrimaryPersonEntityId;
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<IPresenceService> _presenceServiceMock = new();
private readonly Mock<ILightControlService> _lightControlServiceMock = new();
private readonly Subject<StateChange> _stateChangesSubject = new();
private readonly LightMonitorOptions _defaultOptions = new()
{
Enabled = true,
SunEntityId = SunEntityId,
PersonEntityIds = [PersonEntityId]
};
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
private LightMonitorInit CreateSut(LightMonitorOptions? options = null)
private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null)
{
_haContextMock.Setup(x => x.StateAllChanges())
.Returns(_stateChangesSubject);
if (subscriptionException is null)
{
_haContextMock.Setup(x => x.StateAllChanges())
.Returns(_stateChangesSubject);
}
else
{
_haContextMock.Setup(x => x.StateAllChanges())
.Throws(subscriptionException);
}
return new LightMonitorInit(
_haContextMock.Object,
@@ -44,124 +48,219 @@ public class LightMonitorInitTests
private void EmitStateChange(string entityId, string? oldState, string? newState)
{
var entity = new Entity(_haContextMock.Object, entityId);
var old = oldState is not null ? new EntityState { State = oldState } : null;
var @new = newState is not null ? new EntityState { State = newState } : null;
_stateChangesSubject.OnNext(new StateChange(entity, old, @new));
_stateChangesSubject.OnNext(new StateChange(
entity,
LightMonitorTestData.CreateOptionalState(oldState),
LightMonitorTestData.CreateOptionalState(newState)));
}
private void VerifyTurnOn(bool shouldTurnOn)
{
if (shouldTurnOn)
{
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once);
}
else
{
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
}
}
[Theory]
[MemberData(nameof(LightMonitorTestData.PersonNewStateCases), MemberType = typeof(LightMonitorTestData))]
public void PersonStateChange_ShouldTurnOnLightOnlyWhenNewStateIsHome(string? newState, bool shouldTurnOn)
{
CreateSut();
EmitStateChange(PersonEntityId, "not_home", newState);
VerifyTurnOn(shouldTurnOn);
}
[Theory]
[MemberData(nameof(LightMonitorTestData.PersonArrivalTransitions), MemberType = typeof(LightMonitorTestData))]
public void PersonStateChange_ToHome_ShouldIgnoreOnlyRecoveryTransitions(string? oldState, bool shouldTurnOn)
{
CreateSut();
EmitStateChange(PersonEntityId, oldState, LightMonitorConsts.PersonHomeState);
VerifyTurnOn(shouldTurnOn);
}
[Theory]
[InlineData(LightMonitorTestData.PrimaryPersonEntityId)]
[InlineData(LightMonitorTestData.SecondaryPersonEntityId)]
[InlineData(LightMonitorTestData.PhonePersonEntityId)]
public void PersonStateChange_ShouldTurnOnLightForEveryConfiguredPerson(string personEntityId)
{
CreateSut();
EmitStateChange(personEntityId, "not_home", LightMonitorConsts.PersonHomeState);
VerifyTurnOn(true);
}
[Fact]
public void PersonStateChange_FromNotHomeToHome_ShouldCallTurnOnLight()
public void PersonStateChange_ForUnconfiguredPerson_ShouldNotTurnOnLight()
{
CreateSut(LightMonitorTestData.CreateOptions(personEntityIds: [PersonEntityId]));
EmitStateChange(
LightMonitorTestData.SecondaryPersonEntityId,
"not_home",
LightMonitorConsts.PersonHomeState);
VerifyTurnOn(false);
}
[Fact]
public void PersonStateChange_ShouldNotConsultThePresenceService()
{
CreateSut();
EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once);
VerifyTurnOn(true);
_presenceServiceMock.Verify(x => x.IsAnyoneHome(), Times.Never);
}
[Fact]
public void PersonStateChange_FromUnavailableToHome_ShouldNotCallTurnOnLight()
{
CreateSut();
EmitStateChange(PersonEntityId, LightMonitorConsts.UnavailableState, LightMonitorConsts.PersonHomeState);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
}
[Fact]
public void PersonStateChange_FromUnknownToHome_ShouldNotCallTurnOnLight()
{
CreateSut();
EmitStateChange(PersonEntityId, LightMonitorConsts.UnknownState, LightMonitorConsts.PersonHomeState);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
}
[Fact]
public void PersonStateChange_FromNullToHome_ShouldNotCallTurnOnLight()
{
CreateSut();
EmitStateChange(PersonEntityId, null, LightMonitorConsts.PersonHomeState);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
}
[Fact]
public void PersonStateChange_FromNotHomeToNotHome_ShouldNotCallTurnOnLight()
{
CreateSut();
EmitStateChange(PersonEntityId, "not_home", "not_home");
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
}
[Fact]
public void SunStateChange_FromAboveHorizonToBelowHorizon_WhenSomeoneIsHome_ShouldCallTurnOnLight()
[Theory]
[MemberData(nameof(LightMonitorTestData.SunStateTurnOnCases), MemberType = typeof(LightMonitorTestData))]
public void SunStateChange_ShouldTurnOnLightOnlyWhenNewStateIsBelowHorizon(string? newState, bool shouldTurnOn)
{
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true);
CreateSut();
EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, newState);
VerifyTurnOn(shouldTurnOn);
}
[Theory]
[MemberData(nameof(LightMonitorTestData.SunBelowHorizonTransitions), MemberType = typeof(LightMonitorTestData))]
public void SunStateChange_ToBelowHorizon_ShouldIgnoreOnlyRecoveryTransitions(
string? oldState,
bool shouldTurnOn)
{
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true);
CreateSut();
EmitStateChange(SunEntityId, oldState, LightMonitorConsts.SunBelowHorizon);
VerifyTurnOn(shouldTurnOn);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void SunStateChange_ToBelowHorizon_ShouldTurnOnLightOnlyWhenSomeoneIsHome(bool anyoneHome)
{
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(anyoneHome);
CreateSut();
EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once);
VerifyTurnOn(anyoneHome);
_presenceServiceMock.Verify(x => x.IsAnyoneHome(), Times.Once);
}
[Fact]
public void SunStateChange_FromAboveHorizonToBelowHorizon_WhenNoOneIsHome_ShouldNotCallTurnOnLight()
public void SunStateChange_WithNoConfiguredPersons_ShouldStillReactToTheSun()
{
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(false);
CreateSut();
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true);
CreateSut(LightMonitorTestData.CreateOptions(personEntityIds: []));
EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
VerifyTurnOn(true);
}
[Fact]
public void SunStateChange_FromUnavailableToBelowHorizon_ShouldNotCallTurnOnLight()
public void SunStateChange_WhenPresenceCheckThrows_ShouldKeepListening()
{
_presenceServiceMock.SetupSequence(x => x.IsAnyoneHome())
.Throws(new InvalidOperationException("presence failed"))
.Returns(true);
CreateSut();
var act = () => EmitStateChange(
SunEntityId,
LightMonitorConsts.SunAboveHorizon,
LightMonitorConsts.SunBelowHorizon);
act.Should().NotThrow();
VerifyTurnOn(false);
EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon);
VerifyTurnOn(true);
}
[Fact]
public void PersonStateChange_WhenTurnOnLightThrows_ShouldKeepListening()
{
_lightControlServiceMock.SetupSequence(x => x.TurnOnLight())
.Throws(new InvalidOperationException("light failed"))
.Pass();
CreateSut();
var act = () => EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState);
act.Should().NotThrow();
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once);
EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Exactly(2));
}
[Fact]
public void Constructor_WhenStateSubscriptionThrows_ShouldNotThrow()
{
var act = () => CreateSut(subscriptionException: new InvalidOperationException("state stream failed"));
act.Should().NotThrow();
VerifyTurnOn(false);
}
[Fact]
public async Task InitializeAsync_ShouldCompleteWithoutThrowing()
{
var sut = CreateSut();
var act = () => sut.InitializeAsync();
await act.Should().NotThrowAsync();
}
[Fact]
public void StateChange_ForUnrelatedEntity_ShouldNotTurnOnLight()
{
CreateSut();
EmitStateChange("sensor.sun_next_dawn", LightMonitorConsts.UnavailableState, LightMonitorConsts.SunBelowHorizon);
VerifyTurnOn(false);
}
[Fact]
public void SunStateChange_WhenStateDoesNotActuallyChange_ShouldNotTurnOnLight()
{
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true);
CreateSut();
EmitStateChange(SunEntityId, LightMonitorConsts.UnavailableState, LightMonitorConsts.SunBelowHorizon);
EmitStateChange(SunEntityId, LightMonitorConsts.SunBelowHorizon, LightMonitorConsts.SunBelowHorizon);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
VerifyTurnOn(false);
}
[Fact]
public void SunStateChange_FromUnknownToBelowHorizon_ShouldNotCallTurnOnLight()
{
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true);
CreateSut();
EmitStateChange(SunEntityId, LightMonitorConsts.UnknownState, LightMonitorConsts.SunBelowHorizon);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
}
[Fact]
public void SunStateChange_FromNullToBelowHorizon_ShouldNotCallTurnOnLight()
{
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true);
CreateSut();
EmitStateChange(SunEntityId, null, LightMonitorConsts.SunBelowHorizon);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
}
[Fact]
public void SunStateChange_FromBelowHorizonToAboveHorizon_ShouldNotCallTurnOnLight()
public void PersonStateChange_WhenStateDoesNotActuallyChange_ShouldNotTurnOnLight()
{
CreateSut();
EmitStateChange(SunEntityId, LightMonitorConsts.SunBelowHorizon, LightMonitorConsts.SunAboveHorizon);
EmitStateChange(PersonEntityId, LightMonitorConsts.PersonHomeState, LightMonitorConsts.PersonHomeState);
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
VerifyTurnOn(false);
}
}
@@ -0,0 +1,179 @@
using LightMonitor.Models;
using LightMonitorManager.Models;
using NetDaemon.HassModel.Entities;
namespace LightMonitor.Manager.Tests;
/// <summary>
/// Deterministic, reusable fixtures for the LightMonitor tests.
/// Keeping the option builder, state builders and generated state tables here
/// avoids copy-pasted setup across the test classes.
/// </summary>
internal static class LightMonitorTestData
{
public const string LightEntityId = "light.sonoff_1002214d40";
public const string SunEntityId = "sun.sun";
public const string PrimaryPersonEntityId = "person.marius";
public const string SecondaryPersonEntityId = "person.erika";
public const string PhonePersonEntityId = "person.home_phone";
public static readonly string[] PersonEntityIds =
[
PrimaryPersonEntityId,
SecondaryPersonEntityId,
PhonePersonEntityId
];
private static readonly string?[] PresenceStates =
[
LightMonitorConsts.PersonHomeState,
"not_home",
LightMonitorConsts.UnavailableState,
null
];
/// <summary>
/// Builds light monitor options with production-compatible defaults.
/// </summary>
public static LightMonitorOptions CreateOptions(
string lightEntityId = LightEntityId,
string sunEntityId = SunEntityId,
IEnumerable<string>? personEntityIds = null,
bool enabled = true) => new()
{
Enabled = enabled,
LightEntityId = lightEntityId,
SunEntityId = sunEntityId,
PersonEntityIds = personEntityIds?.ToArray() ?? [.. PersonEntityIds]
};
/// <summary>
/// Builds an <see cref="EntityState"/> carrying <paramref name="state"/>.
/// </summary>
public static EntityState CreateState(string? state) => new() { State = state };
/// <summary>
/// Builds an <see cref="EntityState"/>, or <c>null</c> when the entity has no state at all
/// (as returned by <c>IHaContext.GetState</c> for a missing entity).
/// </summary>
public static EntityState? CreateOptionalState(string? state) =>
state is null ? null : CreateState(state);
/// <summary>
/// Sun states that should (<c>true</c>) or should not (<c>false</c>) cause a light turn on.
/// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and
/// missing states must never turn the light on.
/// </summary>
public static TheoryData<string?, bool> SunStateTurnOnCases { get; } = new()
{
{ LightMonitorConsts.SunBelowHorizon, true },
{ LightMonitorConsts.SunBelowHorizon.ToUpperInvariant(), true },
{ "Below_Horizon", true },
{ LightMonitorConsts.SunAboveHorizon, false },
{ LightMonitorConsts.SunAboveHorizon.ToUpperInvariant(), false },
{ LightMonitorConsts.UnavailableState, false },
{ LightMonitorConsts.UnknownState, false },
{ string.Empty, false },
{ " ", false },
{ null, false }
};
/// <summary>
/// Light states evaluated while the sun is below the horizon. Only "on" (any casing)
/// suppresses the turn on call; everything else, including missing state, turns it on.
/// </summary>
public static TheoryData<string?, bool> LightStateTurnOnCases { get; } = new()
{
{ LightMonitorConsts.LightOnState, false },
{ LightMonitorConsts.LightOnState.ToUpperInvariant(), false },
{ "On", false },
{ "off", true },
{ "OFF", true },
{ LightMonitorConsts.UnavailableState, true },
{ LightMonitorConsts.UnknownState, true },
{ string.Empty, true },
{ " ", true },
{ null, true }
};
/// <summary>
/// Person states checked against the "arrived home" transition.
/// Only "home" in any casing counts.
/// </summary>
public static TheoryData<string?, bool> PersonNewStateCases { get; } = new()
{
{ LightMonitorConsts.PersonHomeState, true },
{ "HOME", true },
{ "Home", true },
{ "hOmE", true },
{ "not_home", false },
{ "not_home ", false },
{ LightMonitorConsts.UnavailableState, false },
{ LightMonitorConsts.UnknownState, false },
{ string.Empty, false },
{ " ", false },
{ null, false }
};
/// <summary>
/// Old person states for a transition to "home". Recovery from unavailable, unknown or
/// missing state must be ignored; every other old state is a real arrival.
/// </summary>
public static TheoryData<string?, bool> PersonArrivalTransitions { get; } = new()
{
{ "not_home", true },
{ "work", true },
{ string.Empty, true },
{ LightMonitorConsts.UnavailableState, false },
{ LightMonitorConsts.UnknownState, false },
{ null, false }
};
/// <summary>
/// Old sun states for a transition to "below_horizon". Recovery from unavailable, unknown
/// or missing state must be ignored.
/// </summary>
public static TheoryData<string?, bool> SunBelowHorizonTransitions { get; } = new()
{
{ LightMonitorConsts.SunAboveHorizon, true },
{ string.Empty, true },
{ LightMonitorConsts.UnavailableState, false },
{ LightMonitorConsts.UnknownState, false },
{ null, false }
};
/// <summary>
/// Every 4^3 = 64 combination of home / not_home / unavailable / missing state across the
/// three configured person entities.
/// </summary>
public static TheoryData<string?[]> PresenceStateMatrix { get; } = CreatePresenceStateMatrix();
/// <summary>
/// Person id configurations that resolve to "nobody tracked".
/// </summary>
public static TheoryData<string[]> NoPersonEntityIdSets { get; } = new()
{
{ [] },
{ [string.Empty] },
{ [" "] }
};
private static TheoryData<string?[]> CreatePresenceStateMatrix()
{
var matrix = new TheoryData<string?[]>();
foreach (var first in PresenceStates)
{
foreach (var second in PresenceStates)
{
foreach (var third in PresenceStates)
{
matrix.Add([first, second, third]);
}
}
}
return matrix;
}
}
@@ -1,4 +1,5 @@
using FluentAssertions;
using LightMonitor.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
@@ -13,10 +14,7 @@ public class PresenceServiceTests
{
private readonly Mock<IHaContext> _haContextMock = new();
private readonly LightMonitorOptions _defaultOptions = new()
{
PersonEntityIds = ["person.marius", "person.erika", "person.home_phone"]
};
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
private PresenceService CreateService(LightMonitorOptions? options = null)
{
@@ -26,120 +24,106 @@ public class PresenceServiceTests
Options.Create(options ?? _defaultOptions));
}
[Fact]
public void IsAnyoneHome_WhenOnePersonIsHome_ShouldReturnTrue()
private void SetupStates(IReadOnlyList<string?> personStates)
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = "home" });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "not_home" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns(new EntityState { State = "not_home" });
var service = CreateService();
service.IsAnyoneHome().Should().BeTrue();
}
[Fact]
public void IsAnyoneHome_WhenAllPersonsAreHome_ShouldReturnTrue()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = "home" });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "home" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns(new EntityState { State = "home" });
var service = CreateService();
service.IsAnyoneHome().Should().BeTrue();
}
[Fact]
public void IsAnyoneHome_WhenNoPersonIsHome_ShouldReturnFalse()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = "not_home" });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "not_home" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns(new EntityState { State = "not_home" });
var service = CreateService();
service.IsAnyoneHome().Should().BeFalse();
}
[Fact]
public void IsAnyoneHome_WhenStateIsUnavailable_ShouldSkipAndReturnFalse()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = "unavailable" });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "unknown" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns((EntityState?)null);
var service = CreateService();
service.IsAnyoneHome().Should().BeFalse();
}
[Fact]
public void IsAnyoneHome_WhenStateIsNull_ShouldSkipAndReturnFalse()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns((EntityState?)null);
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns((EntityState?)null);
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns((EntityState?)null);
var service = CreateService();
service.IsAnyoneHome().Should().BeFalse();
}
[Fact]
public void IsAnyoneHome_WhenMixedStatesWithOneHome_ShouldReturnTrue()
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = "unavailable" });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "home" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns((EntityState?)null);
var service = CreateService();
service.IsAnyoneHome().Should().BeTrue();
for (var index = 0; index < personStates.Count; index++)
{
_haContextMock.Setup(x => x.GetState(LightMonitorTestData.PersonEntityIds[index]))
.Returns(LightMonitorTestData.CreateOptionalState(personStates[index]));
}
}
[Theory]
[InlineData("HOME")]
[InlineData("Home")]
[InlineData("home")]
public void IsAnyoneHome_CaseInsensitiveHomeState_ShouldReturnTrue(string homeState)
[MemberData(nameof(LightMonitorTestData.PresenceStateMatrix), MemberType = typeof(LightMonitorTestData))]
public void IsAnyoneHome_ForEveryPresenceCombination_ShouldReturnTrueOnlyWhenSomeoneIsHome(string?[] personStates)
{
_haContextMock.Setup(x => x.GetState("person.marius"))
.Returns(new EntityState { State = homeState });
_haContextMock.Setup(x => x.GetState("person.erika"))
.Returns(new EntityState { State = "not_home" });
_haContextMock.Setup(x => x.GetState("person.home_phone"))
.Returns(new EntityState { State = "not_home" });
SetupStates(personStates);
var service = CreateService();
var expected = personStates.Any(state =>
string.Equals(state, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase));
service.IsAnyoneHome().Should().BeTrue();
CreateService().IsAnyoneHome().Should().Be(expected);
}
[Theory]
[MemberData(nameof(LightMonitorTestData.PersonNewStateCases), MemberType = typeof(LightMonitorTestData))]
public void IsAnyoneHome_ShouldOnlyTreatHomeStateAsPresent(string? state, bool expected)
{
_haContextMock.Setup(x => x.GetState(LightMonitorTestData.PrimaryPersonEntityId))
.Returns(LightMonitorTestData.CreateOptionalState(state));
var options = LightMonitorTestData.CreateOptions(
personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]);
CreateService(options).IsAnyoneHome().Should().Be(expected);
}
[Theory]
[MemberData(nameof(LightMonitorTestData.NoPersonEntityIdSets), MemberType = typeof(LightMonitorTestData))]
public void IsAnyoneHome_WithNoUsablePersonEntityIds_ShouldReturnFalse(string[] personEntityIds)
{
var options = LightMonitorTestData.CreateOptions(personEntityIds: personEntityIds);
CreateService(options).IsAnyoneHome().Should().BeFalse();
}
[Fact]
public void IsAnyoneHome_WithEmptyPersonList_ShouldReturnFalse()
public void IsAnyoneHome_WithEmptyPersonList_ShouldNotQueryAnyEntity()
{
var options = new LightMonitorOptions { PersonEntityIds = [] };
var service = CreateService(options);
var options = LightMonitorTestData.CreateOptions(personEntityIds: []);
CreateService(options).IsAnyoneHome().Should().BeFalse();
_haContextMock.Verify(x => x.GetState(It.IsAny<string>()), Times.Never);
}
[Fact]
public void IsAnyoneHome_ShouldStopCheckingAfterTheFirstHomePerson()
{
_haContextMock.Setup(x => x.GetState(LightMonitorTestData.PrimaryPersonEntityId))
.Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState));
CreateService().IsAnyoneHome().Should().BeTrue();
_haContextMock.Verify(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId), Times.Never);
_haContextMock.Verify(x => x.GetState(LightMonitorTestData.PhonePersonEntityId), Times.Never);
}
[Fact]
public void IsAnyoneHome_ShouldCheckEveryConfiguredPersonWhenNobodyIsHome()
{
CreateService().IsAnyoneHome().Should().BeFalse();
foreach (var personEntityId in LightMonitorTestData.PersonEntityIds)
{
_haContextMock.Verify(x => x.GetState(personEntityId), Times.Once);
}
}
[Fact]
public void IsAnyoneHome_ShouldIgnorePersonsThatAreNotConfigured()
{
_haContextMock.Setup(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId))
.Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState));
var options = LightMonitorTestData.CreateOptions(
personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]);
CreateService(options).IsAnyoneHome().Should().BeFalse();
_haContextMock.Verify(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId), Times.Never);
}
[Fact]
public void IsAnyoneHome_WithDefaultOptions_ShouldQueryAllDefaultPersonEntities()
{
var service = CreateService(new LightMonitorOptions());
service.IsAnyoneHome().Should().BeFalse();
foreach (var personEntityId in LightMonitorConsts.DefaultPersonEntityIds)
{
_haContextMock.Verify(x => x.GetState(personEntityId), Times.Once);
}
}
}