Compare commits

...
7 changed files with 1346 additions and 45 deletions
+154 -11
View File
@@ -39,11 +39,16 @@ reach storage):
- ``start_date`` is a strict ISO date; ``end_date`` is optional and,
when present, on or after ``start_date``.
Month-end policy (documented for Feature 04): a MONTHLY_DAY rule for
the 31st does NOT fire in a 30-day month, and a YEARLY rule for
February 29th does NOT fire in a non-leap year — the engine skips
instead of clamping to month end, because clamping silently moves
"the 31st" to "the 30th" and double-fires tasks.
Month-end policy (implemented in :func:`_occurs_monthly_day` and
documented for Feature 04): in each interval-eligible month, a
MONTHLY_DAY rule for a day that does not exist in that month — the
31st in April, the 30th or 29th in February, February 29th in a
non-leap year — fires on the LAST day of the month instead of being
skipped. A monthly chore still happens in every eligible month,
pinned to the month's end when its nominal date is absent; exactly one
day per eligible month matches the rule (nominal day when it exists,
month end when it does not). The interval anchors on nominal months
elapsed from start_date's month, so clamping never shifts the cadence.
"""
from __future__ import annotations
@@ -265,10 +270,9 @@ class ScheduleRule:
"nth_weekday_weekday", "month")
elif shape is RuleType.MONTHLY_WEEKDAY:
forbidden_fields = ("weekday_set", "day_of_month", "month")
else: # YEARLY
elif shape is RuleType.YEARLY:
forbidden_fields = (
"weekday_set",
"day_of_month",
"nth_weekday",
"nth_weekday_weekday",
)
@@ -311,6 +315,14 @@ class ScheduleRule:
raise RuleValidationError(
f"month must be 1..12, got {self.month!r}"
)
if self.day_of_month is not None and not (
_is_plain_int(self.day_of_month)
and 1 <= self.day_of_month <= 31
):
raise RuleValidationError(
f"day_of_month must be 1..31 for yearly rules, got "
f"{self.day_of_month!r}"
)
def to_dict(self) -> dict:
"""Return the lossless dict form (model-side storage shape).
@@ -418,6 +430,112 @@ def _within_window(rule: ScheduleRule, target: datetime.date) -> bool:
return True
def _month_end(year: int, month: int) -> int:
"""The last calendar day of the given month (leap-aware)."""
if month == 12:
return 31
return (datetime.date(year, month + 1, 1)
- datetime.timedelta(days=1)).day
def _occurs_monthly_day(rule: ScheduleRule, target: datetime.date) -> bool:
"""MONTHLY_DAY evaluation with the documented month-end policy.
Policy: in each interval-eligible month, a rule for a day-of-month
that does not exist in that month (the 31st in April, the 30th in
February, the 29th of February in a non-leap year) fires on the
LAST day of that month instead of being skipped — the chore still
happens that month, pinned to the month's end when its nominal date
is absent.
The interval anchors on months ELAPSED from start_date's month: the
rule fires when the months between the anchor month and the target's
month form a multiple of the interval, keeping "every 2 months on
the 15th" aligned to the anchor month even when the firing lands on
a clamped month-end day.
"""
anchor = _parse_date(rule.start_date)
months_elapsed = (
(target.year - anchor.year) * 12 + (target.month - anchor.month)
)
if months_elapsed % rule.interval != 0:
return False
month_end = _month_end(target.year, target.month)
return target.day == min(rule.day_of_month, month_end)
def _nth_weekday_of_month(
year: int, month: int, weekday: int, nth: int
) -> int | None:
"""The day-of-month of the ``nth`` ``weekday``, or None when the
month has no such occurrence (``nth`` 5 beyond four occurrences).
Positive ``nth`` counts forward (1 = first); ``-1`` counts from the
end (last occurrence, whatever the total). Pure calendar math.
"""
if nth == -1:
last = datetime.date(year, month, _month_end(year, month))
back = (last.weekday() - weekday) % 7
return last.day - back
first = datetime.date(year, month, 1)
first_offset = (weekday - first.weekday()) % 7
day = 1 + first_offset + (nth - 1) * 7
if day > _month_end(year, month):
return None
return day
def _occurs_monthly_weekday(
rule: ScheduleRule, target: datetime.date
) -> bool:
"""MONTHLY_WEEKDAY evaluation.
Fires when the target is the ``nth`` occurrence of
``nth_weekday_weekday`` in its month (1..4 forward, -1 last). A
month with fewer occurrences than ``nth`` (5 on a four-occurrence
month) does not fire — n 5 is accepted by the model but skips such
months, matching the done-condition. The interval anchors on
nominal months elapsed from start_date's month.
"""
anchor = _parse_date(rule.start_date)
months_elapsed = (
(target.year - anchor.year) * 12 + (target.month - anchor.month)
)
if months_elapsed % rule.interval != 0:
return False
if target.weekday() != rule.nth_weekday_weekday:
return False
nth_day = _nth_weekday_of_month(
target.year, target.month, rule.nth_weekday_weekday, rule.nth_weekday
)
return nth_day is not None and target.day == nth_day
def _occurs_yearly(rule: ScheduleRule, target: datetime.date) -> bool:
"""YEARLY evaluation with the documented leap-day clamp policy.
Policy: in each interval-eligible year, the rule fires on
``day_of_month`` of ``month`` when that day exists. A YEARLY rule
for February 29th fires on FEBRUARY 28TH in a non-leap year (the
same clamp-as-month-end policy as MONTHLY_DAY: the annual chore
still happens every year, pinned to February's end when its
nominal date is absent) rather than silently vanishing. A YEARLY
rule with NO day_of_month fires on the first day of ``month``.
The interval anchors on years elapsed from start_date's year.
"""
anchor = _parse_date(rule.start_date)
years_elapsed = target.year - anchor.year
if years_elapsed % rule.interval != 0:
return False
if target.month != rule.month:
return False
if rule.day_of_month is None:
# Day-less yearly rules fire on the first of the month.
return target.day == 1
month_end = _month_end(target.year, target.month)
return target.day == min(rule.day_of_month, month_end)
def occurs_on(rule: ScheduleRule, target: datetime.date) -> bool:
"""Return True when ``rule`` fires on ``target``.
@@ -428,15 +546,37 @@ def occurs_on(rule: ScheduleRule, target: datetime.date) -> bool:
# Dispatch FIRST: an unimplemented shape must raise loudly even for
# dates outside the window, never silently evaluate to False.
shape = rule.rule_type
if shape is not RuleType.DAILY:
if shape not in (
RuleType.DAILY, RuleType.WEEKLY, RuleType.CUSTOM_DAYS,
RuleType.MONTHLY_DAY, RuleType.MONTHLY_WEEKDAY, RuleType.YEARLY,
):
raise NotImplementedError(
f"occurs_on for {shape} lands with its own engine task "
"(Features 04 task sequence)"
)
if not _within_window(rule, target):
return False
offset = (target - _parse_date(rule.start_date)).days
return offset % rule.interval == 0
if shape is RuleType.DAILY:
offset = (target - _parse_date(rule.start_date)).days
return offset % rule.interval == 0
if shape is RuleType.MONTHLY_DAY:
return _occurs_monthly_day(rule, target)
if shape is RuleType.MONTHLY_WEEKDAY:
return _occurs_monthly_weekday(rule, target)
if shape is RuleType.YEARLY:
return _occurs_yearly(rule, target)
# WEEKLY / CUSTOM_DAYS: whole-week anchoring from start_date, never
# ISO week numbers (Feature 04/05 guardrail: 53-week years flip ISO
# parity on January 1st; anchor arithmetic does not).
anchor = _parse_date(rule.start_date)
if shape is RuleType.CUSTOM_DAYS:
interval = 1
else:
interval = rule.interval
week_offset = (target - anchor).days // 7
if week_offset % interval != 0:
return False
return target.weekday() in rule.weekday_set
def occurrences_between(
@@ -448,7 +588,10 @@ def occurrences_between(
inverted bounds; a window entirely outside [rule.start_date,
rule.end_date] yields an empty list.
"""
if rule.rule_type is not RuleType.DAILY:
if rule.rule_type not in (
RuleType.DAILY, RuleType.WEEKLY, RuleType.CUSTOM_DAYS,
RuleType.MONTHLY_DAY, RuleType.MONTHLY_WEEKDAY, RuleType.YEARLY,
):
raise NotImplementedError(
f"occurrences_between for {rule.rule_type} lands with its own "
"engine task (Features 04 task sequence)"
+25 -29
View File
@@ -213,14 +213,32 @@ def test_occurrences_between_year_boundary() -> None:
# ---------------------------------------------------------------------------
def test_occurs_on_rejects_unimplemented_shapes_loudly() -> None:
"""Weekly and beyond land with their own engine tasks; a loud
NotImplementedError beats a silent wrong answer."""
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0}, start_date="2026-09-01"
def test_occurs_on_rejects_unknown_shapes_loudly() -> None:
"""All six model shapes are implemented; a shape added to the model
without an engine arm must raise a loud NotImplementedError rather
than a silent wrong answer. Forged via a private enum extension
because ScheduleRule validation rejects unknown names."""
import enum as enum_module
from custom_components.nestquest import recurrence as mod
ForgedType = enum_module.Enum(
"ForgedType", {"UNKNOWN_SHAPE": "unknown_shape"}
)
with pytest.raises(NotImplementedError):
occurs_on(rule, _d("2026-09-07"))
forged_rule = ScheduleRule.__new__(ScheduleRule)
object.__setattr__(forged_rule, "rule_type", ForgedType.UNKNOWN_SHAPE)
object.__setattr__(forged_rule, "interval", 1)
object.__setattr__(forged_rule, "weekday_set", None)
object.__setattr__(forged_rule, "day_of_month", None)
object.__setattr__(forged_rule, "nth_weekday", None)
object.__setattr__(forged_rule, "nth_weekday_weekday", None)
object.__setattr__(forged_rule, "month", None)
object.__setattr__(forged_rule, "start_date", "2026-09-01")
object.__setattr__(forged_rule, "end_date", None)
for day in ("2026-08-31", "2026-09-15", "2026-12-31"):
with pytest.raises(NotImplementedError):
occurs_on(forged_rule, _d(day))
with pytest.raises(NotImplementedError):
occurrences_between(forged_rule, "2026-08-01", "2026-12-31")
def test_interval_7_preserves_weekday_alignment_across_months() -> None:
"""Weekly-by-interval semantics: every firing lands on the SAME
@@ -268,26 +286,4 @@ def test_occurrences_between_year_boundary_interval_2() -> None:
assert result == ["2026-12-30", "2027-01-01", "2027-01-03"]
def test_occurs_on_unimplemented_shape_raises_even_outside_window() -> None:
"""An unimplemented shape must raise whether the date is inside or
outside the window — silent False would hide a missing engine."""
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0},
start_date="2026-09-01", end_date="2026-09-10",
)
# Before start, inside window, after end: all must raise.
for day in ("2026-08-31", "2026-09-07", "2026-09-20"):
with pytest.raises(NotImplementedError):
occurs_on(rule, _d(day))
def test_occurrences_between_unimplemented_shape_raises_even_disjoint(
tmp_path,
) -> None:
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0}, start_date="2026-09-01"
)
# A range entirely before the rule's start still raises: the shape
# is unimplemented, and silence would hide it.
with pytest.raises(NotImplementedError):
occurrences_between(rule, "2026-08-01", "2026-08-10")
+10 -5
View File
@@ -393,16 +393,21 @@ def test_monthly_day_rejects_month() -> None:
def test_yearly_rejects_day_and_nth_fields() -> None:
with pytest.raises(RuleValidationError, match="must not set"):
ScheduleRule(
rule_type=RuleType.YEARLY, month=6, day_of_month=15,
start_date="2026-09-01",
)
with pytest.raises(RuleValidationError, match="must not set"):
ScheduleRule(
rule_type=RuleType.YEARLY, month=6, nth_weekday=1,
nth_weekday_weekday=0, start_date="2026-09-01",
)
# YEARLY MAY carry an optional day_of_month (Feb 29 rules need it):
rule = ScheduleRule(rule_type=RuleType.YEARLY, month=2,
day_of_month=29, start_date="2026-09-01")
assert rule.day_of_month == 29
# ...but it is still validated when present.
with pytest.raises(RuleValidationError, match="day_of_month"):
ScheduleRule(
rule_type=RuleType.YEARLY, month=6, day_of_month=32,
start_date="2026-09-01",
)
def test_storage_value_mapping() -> None:
+301
View File
@@ -0,0 +1,301 @@
"""Tests for MONTHLY_DAY recurrence with the month-end clamp policy."""
from __future__ import annotations
import datetime
import pytest
from custom_components.nestquest.recurrence import (
RuleType,
RuleValidationError,
ScheduleRule,
_month_end,
occurs_on,
occurrences_between,
)
def _d(date: str) -> datetime.date:
return datetime.date.fromisoformat(date)
# ---------------------------------------------------------------------------
# Nominal-day firings
# ---------------------------------------------------------------------------
def test_monthly_day_15_fires_on_the_15th() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=15,
start_date="2026-01-15",
)
for month in range(1, 13):
assert occurs_on(rule, datetime.date(2026, month, 15)) is True
assert occurs_on(rule, datetime.date(2026, 1, 14)) is False
assert occurs_on(rule, datetime.date(2026, 1, 16)) is False
def test_monthly_day_never_fires_on_other_days() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=10,
start_date="2026-01-10",
)
# Every non-10th day of a short month must be False.
for day in range(1, 30):
if day != 10:
assert occurs_on(
rule, datetime.date(2026, 1, day)
) is False, f"Jan {day}"
def test_monthly_day_never_fires_before_start() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=15,
start_date="2026-03-15",
)
# Feb 15 precedes the start: no firing even though the day matches.
assert occurs_on(rule, datetime.date(2026, 2, 15)) is False
assert occurs_on(rule, datetime.date(2026, 3, 15)) is True
def test_monthly_day_respects_end_date() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=15,
start_date="2026-01-15", end_date="2026-06-15",
)
assert occurs_on(rule, datetime.date(2026, 6, 15)) is True
assert occurs_on(rule, datetime.date(2026, 7, 15)) is False
# ---------------------------------------------------------------------------
# Month-end clamp policy
# ---------------------------------------------------------------------------
def test_month_end_helper_is_leap_aware() -> None:
assert _month_end(2026, 1) == 31
assert _month_end(2026, 4) == 30
assert _month_end(2026, 2) == 28 # non-leap
assert _month_end(2028, 2) == 29 # leap
assert _month_end(2000, 2) == 29 # divisible-by-400 leap
assert _month_end(1900, 2) == 28 # divisible-by-100 non-leap
assert _month_end(2026, 12) == 31
def test_day_31_clamps_to_month_end_in_shorter_months() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=31,
start_date="2026-01-31",
)
# Months with a 31st: fire on the 31st.
for month, day in ((1, 31), (3, 31), (5, 31), (7, 31), (8, 31),
(10, 31), (12, 31)):
assert occurs_on(rule, datetime.date(2026, month, day)) is True, (
f"2026-{month:02d}-{day:02d}"
)
# Months WITHOUT a 31st: fire on the month's last day.
assert occurs_on(rule, datetime.date(2026, 4, 30)) is True # Apr 30
assert occurs_on(rule, datetime.date(2026, 6, 30)) is True # Jun 30
assert occurs_on(rule, datetime.date(2026, 9, 30)) is True # Sep 30
assert occurs_on(rule, datetime.date(2026, 11, 30)) is True # Nov 30
# The day BEFORE the clamp is not a firing.
assert occurs_on(rule, datetime.date(2026, 4, 29)) is False
assert occurs_on(rule, datetime.date(2026, 4, 28)) is False
def test_day_30_clamps_to_feb_28_non_leap() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=30,
start_date="2026-01-30",
)
assert occurs_on(rule, datetime.date(2026, 2, 28)) is True # clamp
# No Feb 29 in 2026 (non-leap): nothing else in February fires.
assert occurs_on(rule, datetime.date(2026, 2, 27)) is False
# Months with a 30th: nominal day.
assert occurs_on(rule, datetime.date(2026, 4, 30)) is True
assert occurs_on(rule, datetime.date(2026, 3, 30)) is True
def test_day_29_feb_clamps_to_28_non_leap_and_29_leap() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=29,
start_date="2026-01-29",
)
# Non-leap 2027: Feb 28 is the clamp.
assert occurs_on(rule, datetime.date(2027, 2, 28)) is True
assert occurs_on(rule, datetime.date(2027, 2, 27)) is False
# Leap 2028: Feb 29 exists — nominal day.
assert occurs_on(rule, datetime.date(2028, 2, 29)) is True
assert occurs_on(rule, datetime.date(2028, 2, 28)) is False
def test_day_30_feb_leap_year_clamps_to_29() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=30,
start_date="2027-01-30",
)
# Leap 2028: Feb has 29 days; the 30th clamps to Feb 29.
assert occurs_on(rule, datetime.date(2028, 2, 29)) is True
# Non-leap 2026 (rule starts 2027 so Feb 2027 is non-leap): clamps 28.
assert occurs_on(rule, datetime.date(2027, 2, 28)) is True
# ---------------------------------------------------------------------------
# Full-year sweeps: the 29th, 30th, 31st across leap and non-leap years
# ---------------------------------------------------------------------------
def _sweep_monthly(rule: ScheduleRule, year: int) -> list[tuple[int, int]]:
"""Every (month, day) in ``rule``'s year the engine says fires."""
hits = []
for month in range(1, 13):
for day in range(1, _month_end(year, month) + 1):
if occurs_on(rule, datetime.date(year, month, day)):
hits.append((month, day))
return hits
def test_full_year_day_31_sweep_2026() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=31,
start_date="2026-01-31",
)
# Exactly one firing per month, twelve total.
hits = _sweep_monthly(rule, 2026)
assert len(hits) == 12
by_month = dict(hits)
assert (by_month[1], by_month[2], by_month[4]) == (31, 28, 30)
assert by_month[2] == 28 # 2026 Feb is non-leap
assert by_month[4] == 30
# Each month has exactly one firing.
months = [month for month, _ in hits]
assert months == list(range(1, 13))
def test_full_year_day_31_sweep_2028_leap() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=31,
start_date="2028-01-31",
)
hits = _sweep_monthly(rule, 2028)
by_month = dict(hits)
assert by_month[2] == 29 # leap February clamps to the 29th
assert by_month[4] == 30
months = [month for month, _ in hits]
assert months == list(range(1, 13))
def test_full_year_day_30_sweep_2028() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=30,
start_date="2028-01-30",
)
hits = _sweep_monthly(rule, 2028)
by_month = dict(hits)
assert by_month[2] == 29 # leap Feb clamps to 29
months = [month for month, _ in hits]
assert months == list(range(1, 13))
def test_full_year_day_29_sweep_2027_non_leap() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=29,
start_date="2027-01-29",
)
hits = _sweep_monthly(rule, 2027)
by_month = dict(hits)
assert by_month[2] == 28 # non-leap Feb clamps to the 28th
months = [month for month, _ in hits]
assert months == list(range(1, 13))
def test_full_year_day_29_sweep_2028_leap() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=29,
start_date="2028-01-29",
)
hits = _sweep_monthly(rule, 2028)
by_month = dict(hits)
assert by_month[2] == 29 # leap Feb has a real 29th: nominal day
months = [month for month, _ in hits]
assert months == list(range(1, 13))
# ---------------------------------------------------------------------------
# Interval arithmetic
# ---------------------------------------------------------------------------
def test_monthly_interval_2_every_second_month() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=15, interval=2,
start_date="2026-01-15",
)
assert occurs_on(rule, datetime.date(2026, 1, 15)) is True
assert occurs_on(rule, datetime.date(2026, 2, 15)) is False
assert occurs_on(rule, datetime.date(2026, 3, 15)) is True
assert occurs_on(rule, datetime.date(2026, 4, 15)) is False
assert occurs_on(rule, datetime.date(2026, 5, 15)) is True
def test_monthly_interval_2_clamped_month_end_alignment() -> None:
"""Interval counts nominal months from the anchor: Jan 31 anchor,
every 2 months -> Jan (m0), Mar (m2), May (m4), Jul (m6). Clamped
firings (Feb 28, Apr 30, Jun 30) occur only in interval months."""
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=31, interval=2,
start_date="2026-01-31",
)
assert occurs_on(rule, datetime.date(2026, 1, 31)) is True # m0
assert occurs_on(rule, datetime.date(2026, 2, 28)) is False # m1
assert occurs_on(rule, datetime.date(2026, 3, 31)) is True # m2
assert occurs_on(rule, datetime.date(2026, 4, 30)) is False # m3
assert occurs_on(rule, datetime.date(2026, 5, 31)) is True # m4
assert occurs_on(rule, datetime.date(2026, 6, 30)) is False # m5
assert occurs_on(rule, datetime.date(2026, 7, 31)) is True # m6
def test_monthly_interval_arithmetic_across_year_boundary() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=15, interval=2,
start_date="2026-11-15",
)
# Nov (m0) fires, Jan 2027 (m2) fires, Mar (m4) fires.
assert occurs_on(rule, datetime.date(2026, 11, 15)) is True
assert occurs_on(rule, datetime.date(2026, 12, 15)) is False
assert occurs_on(rule, datetime.date(2027, 1, 15)) is True
assert occurs_on(rule, datetime.date(2027, 2, 15)) is False
assert occurs_on(rule, datetime.date(2027, 3, 15)) is True
def test_monthly_day_occurrences_between_span() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=31,
start_date="2026-01-31",
)
result = occurrences_between(rule, "2026-01-01", "2026-06-30")
assert result == [
"2026-01-31", "2026-02-28", "2026-03-31", "2026-04-30",
"2026-05-31", "2026-06-30",
]
def test_monthly_day_occurrences_between_rejects_inverted() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=15,
start_date="2026-01-15",
)
with pytest.raises(RuleValidationError, match="on or after"):
occurrences_between(rule, "2026-06-15", "2026-01-15")
def test_monthly_day_clamp_is_one_firing_per_month(tmp_path) -> None:
"""The clamp must not double-fire: only one day per month matches."""
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_DAY, day_of_month=31,
start_date="2026-01-31",
)
hits = _sweep_monthly(rule, 2026)
months = [month for month, _ in hits]
assert months == sorted(months)
assert len(months) == len(set(months)) == 12
+324
View File
@@ -0,0 +1,324 @@
"""Tests for MONTHLY_WEEKDAY (nth-weekday-of-month) recurrence."""
from __future__ import annotations
import datetime
import pytest
from custom_components.nestquest.recurrence import (
RuleType,
RuleValidationError,
ScheduleRule,
_nth_weekday_of_month,
occurs_on,
occurrences_between,
)
def _d(date: str) -> datetime.date:
return datetime.date.fromisoformat(date)
# ---------------------------------------------------------------------------
# The helper: nth occurrence day-of-month
# ---------------------------------------------------------------------------
def test_nth_weekday_helper_first_second_third() -> None:
"""Independently verified: Mar 1 2026 is a Sunday; Wednesdays are
4, 11, 18, 25 (four — no 5th)."""
assert _nth_weekday_of_month(2026, 3, 2, 1) == 4
assert _nth_weekday_of_month(2026, 3, 2, 2) == 11
assert _nth_weekday_of_month(2026, 3, 2, 3) == 18
assert _nth_weekday_of_month(2026, 3, 2, 4) == 25
assert _nth_weekday_of_month(2026, 3, 2, 5) is None
def test_nth_weekday_helper_none_when_month_lacks_nth() -> None:
"""Independently verified: April 2026 Fridays are 3, 10, 17, 24
(four) — no 5th occurrence."""
assert _nth_weekday_of_month(2026, 4, 4, 5) is None
def test_nth_weekday_helper_last() -> None:
"""Independently verified: March 2026 Fridays are 6, 13, 20, 27;
February 2028 Saturdays are 5, 12, 19, 26 (Feb 29 2028 is a
Tuesday, so the last SATURDAY is the 26th, not the last day)."""
assert _nth_weekday_of_month(2026, 3, 4, -1) == 27
# February 2026: 28 days, last day IS a Saturday.
assert _nth_weekday_of_month(2026, 2, 5, -1) == 28
# February 2028: the last Saturday is the 26th (Feb 29 is a Tue).
assert _nth_weekday_of_month(2028, 2, 5, -1) == 26
def test_nth_weekday_helper_last_when_month_has_five() -> None:
"""Independently verified: October 2026 Fridays are 2, 9, 16, 23, 30
(five) — the last is the 30th, and the 5th is the same day."""
assert _nth_weekday_of_month(2026, 10, 4, -1) == 30
assert _nth_weekday_of_month(2026, 10, 4, 5) == 30
def test_helper_zero_and_out_of_range_nth() -> None:
"""The model rejects n 0 before the helper sees it; -1/1..5 only."""
with pytest.raises(RuleValidationError):
ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=0,
nth_weekday_weekday=1, start_date="2026-09-01",
)
with pytest.raises(RuleValidationError):
ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=6,
nth_weekday_weekday=1, start_date="2026-09-01",
)
# ---------------------------------------------------------------------------
# occurs_on: first / second / third / fourth / last across 12 months
# ---------------------------------------------------------------------------
def test_first_tuesday_of_twelve_consecutive_months() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=1,
nth_weekday_weekday=2, # first Wednesday
start_date="2026-01-01",
)
first_wednesdays = [
(1, 7), (2, 4), (3, 4), (4, 1), (5, 6), (6, 3),
(7, 1), (8, 5), (9, 2), (10, 7), (11, 4), (12, 2),
]
for month, day in first_wednesdays:
date = datetime.date(2026, month, day)
assert date.weekday() == 2
assert occurs_on(rule, date) is True, date
# Neighbors do not fire.
assert occurs_on(rule, date - datetime.timedelta(days=7)) is False
assert occurs_on(rule, date + datetime.timedelta(days=7)) is False
def test_second_wednesday_of_twelve_consecutive_months() -> None:
"""Independently verified second Wednesdays of 2026 (Jan 1 is a
Thursday; Wednesdays per month from the calendar): the SECOND one
fires; the FIRST one does not."""
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=2,
nth_weekday_weekday=2,
start_date="2026-01-01",
)
# (month, first_wed, second_wed) from plain datetime arithmetic:
verified = [
(1, 7, 14), (2, 4, 11), (3, 4, 11), (4, 1, 8),
(5, 6, 13), (6, 3, 10), (7, 1, 8), (8, 5, 12),
(9, 2, 9), (10, 7, 14), (11, 4, 11), (12, 2, 9),
]
for month, first_wed, second_wed in verified:
assert _d(f"2026-{month:02d}-{first_wed:02d}").weekday() == 2
assert _d(f"2026-{month:02d}-{second_wed:02d}").weekday() == 2
assert occurs_on(
rule, datetime.date(2026, month, second_wed)
) is True, f"2026-{month:02d}-{second_wed:02d}"
assert occurs_on(
rule, datetime.date(2026, month, first_wed)
) is False, f"2026-{month:02d}-{first_wed:02d}"
def test_third_friday_of_twelve_consecutive_months() -> None:
"""Independently verified 2026 Fridays; the THIRD fires, the SECOND
does not."""
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=3,
nth_weekday_weekday=4,
start_date="2026-01-01",
)
verified = [
# (month, first_fri, second_fri, third_fri)
(1, 2, 9, 16), (2, 6, 13, 20), (3, 6, 13, 20),
(4, 3, 10, 17), (5, 1, 8, 15), (6, 5, 12, 19),
(7, 3, 10, 17), (8, 7, 14, 21), (9, 4, 11, 18),
(10, 2, 9, 16), (11, 6, 13, 20), (12, 4, 11, 18),
]
for month, first_fri, second_fri, third_fri in verified:
third = _d(f"2026-{month:02d}-{third_fri:02d}")
assert third.weekday() == 4
assert occurs_on(rule, third) is True, third
second = _d(f"2026-{month:02d}-{second_fri:02d}")
assert occurs_on(rule, second) is False, second
def test_fourth_wednesday_of_twelve_consecutive_months() -> None:
"""Independently verified 2026 Wednesdays; the FOURTH fires, the
THIRD does not."""
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=4,
nth_weekday_weekday=2,
start_date="2026-01-01",
)
verified = [
# (month, third_wed, fourth_wed)
(1, 21, 28), (2, 18, 25), (3, 18, 25), (4, 15, 22),
(5, 20, 27), (6, 17, 24), (7, 15, 22), (8, 19, 26),
(9, 16, 23), (10, 21, 28), (11, 18, 25), (12, 16, 23),
]
for month, third_wed, fourth_wed in verified:
fourth = _d(f"2026-{month:02d}-{fourth_wed:02d}")
assert fourth.weekday() == 2
assert occurs_on(rule, fourth) is True, fourth
third = _d(f"2026-{month:02d}-{third_wed:02d}")
assert not occurs_on(rule, third), third
def test_last_monday_of_twelve_consecutive_months() -> None:
"""Independently verified last Mondays of 2026; each fires, and the
PREVIOUS Monday of the same month does not (it is nth-from-last
minus one, i.e. the second-to-last)."""
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=-1,
nth_weekday_weekday=0,
start_date="2026-01-01",
)
verified = [
# (month, last_monday)
(1, 26), (2, 23), (3, 30), (4, 27), (5, 25), (6, 29),
(7, 27), (8, 31), (9, 28), (10, 26), (11, 30), (12, 28),
]
for month, last_monday in verified:
date = _d(f"2026-{month:02d}-{last_monday:02d}")
assert date.weekday() == 0
assert occurs_on(rule, date) is True, date
# The Monday a week earlier is NOT the last: must not fire.
week_before = date - datetime.timedelta(days=7)
if week_before.month == month:
assert occurs_on(rule, week_before) is False, week_before
# ---------------------------------------------------------------------------
# The five-occurrence skip: a 5th on a four-occurrence month
# ---------------------------------------------------------------------------
def test_fifth_weekday_skips_four_occurrence_months() -> None:
"""Independently verified: 2026 months with FIVE Mondays are March,
June, August, November — every other month (four Mondays) must fire
on no day at all, and each hit must be the month's FINAL Monday."""
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=5,
nth_weekday_weekday=0, # fifth Monday
start_date="2026-01-01",
)
five_monday_months = {3: 30, 6: 29, 8: 31, 11: 30}
hit_months = set()
for month in range(1, 13):
if month in five_monday_months:
day = five_monday_months[month]
hit = _d(f"2026-{month:02d}-{day:02d}")
assert hit.weekday() == 0
assert occurs_on(rule, hit) is True, hit
# It is the FINAL Monday of the month: sweep EVERY remaining
# calendar day after the hit — none may fire.
for later in range(day + 1, _month_end_days(2026, month) + 1):
assert occurs_on(
rule, datetime.date(2026, month, later)
) is False, f"2026-{month:02d}-{later:02d}"
# The Monday a week earlier is not the fifth.
assert occurs_on(
rule, datetime.date(2026, month, day - 7)
) is False
hit_months.add(month)
else:
for day in range(1, _month_end_days(2026, month) + 1):
assert occurs_on(
rule, datetime.date(2026, month, day)
) is False, f"2026-{month:02d}-{day:02d}"
assert hit_months == {3, 6, 8, 11}, hit_months
def _month_end_days(year: int, month: int) -> int:
if month == 12:
return 31
return (datetime.date(year, month + 1, 1)
- datetime.timedelta(days=1)).day
def test_fifth_weekday_fires_in_five_occurrence_months() -> None:
"""Independently verified: October 2026 Fridays are 2, 9, 16, 23, 30
(five) — the 5th (and last) is the 30th; April 2026 has four Fridays
(3, 10, 17, 24) so no day in April fires."""
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=5,
nth_weekday_weekday=4, # Fridays
start_date="2026-01-01",
)
# October: the 30th fires, is a Friday, and no Monday-later day
# (the 31st) is a Friday: the 30th is the FINAL Friday.
oct_30 = datetime.date(2026, 10, 30)
assert oct_30.weekday() == 4
assert occurs_on(rule, oct_30) is True
assert occurs_on(rule, datetime.date(2026, 10, 31)) is False
# April: no Friday-5th, so no day fires.
for day in range(1, _month_end_days(2026, 4) + 1):
assert occurs_on(rule, datetime.date(2026, 4, day)) is False, (
f"2026-04-{day:02d}"
)
# ---------------------------------------------------------------------------
# Interval arithmetic
# ---------------------------------------------------------------------------
def test_monthly_weekday_interval_2() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=2,
nth_weekday_weekday=2, interval=2, start_date="2026-01-01",
)
# Jan (m0) fires on the 2nd Tuesday; Feb (m1) skipped; Mar (m2) fires.
jan_second = _nth_weekday_of_month(2026, 1, 2, 2)
assert occurs_on(rule, datetime.date(2026, 1, jan_second)) is True
feb_second = _nth_weekday_of_month(2026, 2, 2, 2)
assert occurs_on(rule, datetime.date(2026, 2, feb_second)) is False
mar_second = _nth_weekday_of_month(2026, 3, 2, 2)
assert occurs_on(rule, datetime.date(2026, 3, mar_second)) is True
def test_monthly_weekday_interval_across_year_boundary() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=1,
nth_weekday_weekday=2, interval=3, start_date="2026-11-01",
)
# Nov (m0) fires; Dec (m1), Jan (m2) skip; Feb (m3) fires.
nov_first = _nth_weekday_of_month(2026, 11, 2, 1)
assert occurs_on(rule, datetime.date(2026, 11, nov_first)) is True
dec_first = _nth_weekday_of_month(2026, 12, 2, 1)
assert occurs_on(rule, datetime.date(2026, 12, dec_first)) is False
jan_first = _nth_weekday_of_month(2027, 1, 2, 1)
assert occurs_on(rule, datetime.date(2027, 1, jan_first)) is False
feb_first = _nth_weekday_of_month(2027, 2, 2, 1)
assert occurs_on(rule, datetime.date(2027, 2, feb_first)) is True
# ---------------------------------------------------------------------------
# occurrences_between
# ---------------------------------------------------------------------------
def test_monthly_weekday_occurrences_between_span() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=2,
nth_weekday_weekday=4, # second Friday
start_date="2026-01-01", end_date="2026-04-30",
)
result = occurrences_between(rule, "2026-01-01", "2026-04-30")
# Independently verified second Fridays: Jan 9 (Jan 1 Thu), Feb 13
# (Feb 1 Sun), Mar 13 (Mar 1 Sun), Apr 10 (Apr 1 Wed).
assert result == [
"2026-01-09", "2026-02-13", "2026-03-13", "2026-04-10",
]
def test_monthly_weekday_occurrences_between_rejects_inverted() -> None:
rule = ScheduleRule(
rule_type=RuleType.MONTHLY_WEEKDAY, nth_weekday=1,
nth_weekday_weekday=1, start_date="2026-01-01",
)
with pytest.raises(RuleValidationError, match="on or after"):
occurrences_between(rule, "2026-06-01", "2026-01-01")
+299
View File
@@ -0,0 +1,299 @@
"""Tests for weekly and custom day-set recurrence evaluation."""
from __future__ import annotations
import datetime
import pytest
from custom_components.nestquest.recurrence import (
RuleType,
RuleValidationError,
ScheduleRule,
occurs_on,
occurrences_between,
)
def _d(date: str) -> datetime.date:
return datetime.date.fromisoformat(date)
# 2026-09-01 is a TUESDAY (weekday 1).
# Anchor-week arithmetic (start_date = Tue Sep 1): week 0 spans
# Sep 1-7, week 1 spans Sep 8-14, week 2 spans Sep 15-21, and so on —
# whole weeks elapsed from the anchor, NOT calendar-Sunday weeks.
# A weekly Mon/Wed/Fri (0,2,4) rule at interval 1 anchored here fires
# on Wed Sep 2, Fri Sep 4 (both week 0), then Mon Sep 7, Wed Sep 9,
# Fri Sep 11 (week 1), Mon Sep 14... (week 2), and so on.
def test_weekly_fires_exactly_on_set_weekdays() -> None:
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0, 2, 4},
start_date="2026-09-01",
)
# Sep 2026: 1=Tue(1), 2=Wed(2), 4=Fri(4), 7=Mon(0), 8=Tue(1), 9=Wed,
# 10=Thu(3), 11=Fri(4)
assert occurs_on(rule, _d("2026-09-01")) is False # Tue NOT in set
assert occurs_on(rule, _d("2026-09-02")) is True # Wed in set
assert occurs_on(rule, _d("2026-09-03")) is False # Thu not in set
assert occurs_on(rule, _d("2026-09-04")) is True # Fri in set
assert occurs_on(rule, _d("2026-09-05")) is False # Sat
assert occurs_on(rule, _d("2026-09-06")) is False # Sun
assert occurs_on(rule, _d("2026-09-07")) is True # Mon
assert occurs_on(rule, _d("2026-09-08")) is False # Tue not in set
def test_weekly_start_date_itself_may_not_be_in_set() -> None:
"""start_date anchors the WEEK count, not a firing day: a Tuesday
start for a Mon/Wed/Fri rule fires on Wed Sep 2, not Sep 1."""
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0, 2, 4},
start_date="2026-09-01",
)
assert occurs_on(rule, _d("2026-09-01")) is False # Tue=1, not in set
assert occurs_on(rule, _d("2026-09-02")) is True # Wed=2
assert occurs_on(rule, _d("2026-09-04")) is True # Fri=4
assert occurs_on(rule, _d("2026-09-07")) is True # Mon, next week
def test_weekly_never_fires_before_start() -> None:
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={2}, # Wednesdays
start_date="2026-09-02", # a Wednesday
)
# Wed Sep 2 is the anchor day and in-set: fires. Wed Aug 26 (one
# week BEFORE the anchor, in-set) must not fire: pre-window.
assert occurs_on(rule, _d("2026-09-02")) is True
assert occurs_on(rule, _d("2026-08-26")) is False # Wed, before start
assert occurs_on(rule, _d("2026-09-09")) is True # Wed, next week
def test_weekly_respects_end_date() -> None:
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0, 2, 4},
start_date="2026-09-01", end_date="2026-09-10",
)
assert occurs_on(rule, _d("2026-09-09")) is True # Wed within end
assert occurs_on(rule, _d("2026-09-11")) is False # Fri after end
def test_weekly_interval_2_fires_on_alternate_weeks() -> None:
"""Interval 2: fires on set weekdays only in even week-offsets."""
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0}, interval=2,
start_date="2026-09-07", # a Monday
)
# Week 0 (Sep 7-13): fires Mon Sep 7.
assert occurs_on(rule, _d("2026-09-07")) is True
# Week 1 (Sep 14-20): skipped.
assert occurs_on(rule, _d("2026-09-14")) is False
# Week 2 (Sep 21-27): fires Mon Sep 21.
assert occurs_on(rule, _d("2026-09-21")) is True
# Week 3 (Sep 28-Oct 4): skipped; Mon Sep 28 does not fire.
assert occurs_on(rule, _d("2026-09-28")) is False
# Week 4 (Oct 5-11): fires Mon Oct 5.
assert occurs_on(rule, _d("2026-10-05")) is True
def test_weekly_interval_3_every_third_week() -> None:
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={3}, interval=3,
start_date="2026-09-03", # a Thursday
)
assert occurs_on(rule, _d("2026-09-03")) is True # week 0
assert occurs_on(rule, _d("2026-09-10")) is False # week 1
assert occurs_on(rule, _d("2026-09-17")) is False # week 2
assert occurs_on(rule, _d("2026-09-24")) is True # week 3
assert occurs_on(rule, _d("2026-10-15")) is True # week 6
def test_weekly_interval_2_never_fires_in_odd_weeks_across_months() -> None:
"""The week offset is anchored to start_date across month edges."""
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={2}, interval=2,
start_date="2026-09-02", # a Wednesday
)
# Week 0: Wed Sep 2 fires. Week 1: Wed Sep 9 skipped.
# Week 2: Wed Sep 16 fires. Week 3: Wed Sep 23 skipped.
# Week 4 (Oct): Wed Sep 30 fires (still week 4!). Week 5: Wed Oct 7 skipped.
assert occurs_on(rule, _d("2026-09-02")) is True
assert occurs_on(rule, _d("2026-09-09")) is False
assert occurs_on(rule, _d("2026-09-16")) is True
assert occurs_on(rule, _d("2026-09-23")) is False
assert occurs_on(rule, _d("2026-09-30")) is True
assert occurs_on(rule, _d("2026-10-07")) is False
assert occurs_on(rule, _d("2026-10-14")) is True
def test_custom_days_interval_1_behaves_like_weekly() -> None:
"""CUSTOM_DAYS with interval 1 behaves identically to WEEKLY."""
weekly = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={1, 3, 5},
start_date="2026-09-01",
)
custom = ScheduleRule(
rule_type=RuleType.CUSTOM_DAYS, weekday_set={1, 3, 5},
start_date="2026-09-01",
)
# Whole month of September must match exactly.
for day in range(1, 31):
date = datetime.date(2026, 9, day)
assert occurs_on(weekly, date) == occurs_on(custom, date), date
def test_custom_days_never_fires_before_start(tmp_path) -> None:
rule = ScheduleRule(
rule_type=RuleType.CUSTOM_DAYS, weekday_set={0},
start_date="2026-09-07", # a Monday
)
assert occurs_on(rule, _d("2026-09-06")) is False # Sun, before
assert occurs_on(rule, _d("2026-09-07")) is True # Mon, on
def test_hand_checked_8_week_sequence_weekly_mon_wed_fri() -> None:
"""The done-condition's hand-checked sequence: 8 weeks of a
Mon/Wed/Fri rule anchored at Tue 2026-09-01, interval 1.
Anchor weeks from Tue Sep 1 (week 0 = Sep 1-7, week 1 = Sep 8-14,
... week 7 = Oct 20-26). Mon/Wed/Fri firings (interval 1, so every
in-set weekday fires regardless of week):
Week 0 (Sep 1-7): Wed 2, Fri 4 (Mon Sep 7 is ALSO week 0:
6 elapsed days // 7 = 0 — the anchor week
boundary sits on Sep 8, not on the Monday)
Week 1 (Sep 8-14): Wed 9, Fri 11, Mon 14 (13 elapsed days // 7 = 1)
Week 2 (Sep 15-21): Wed 16, Fri 18, Mon 21
Week 3 (Sep 22-28): Wed 23, Fri 25, Mon 28
Week 4 (Sep 29-Oct 5): Wed 30, Fri 2 (Oct), Mon 5 (Oct)
Week 5 (Oct 6-12): Wed 7, Fri 9, Mon 12
Week 6 (Oct 13-19): Wed 14, Fri 16, Mon 19
Week 7 (Oct 20-26): Wed 21, Fri 23, Mon 26
"""
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0, 2, 4},
start_date="2026-09-01", end_date="2026-10-26",
)
expected = [
"2026-09-02", "2026-09-04",
"2026-09-07", "2026-09-09", "2026-09-11",
"2026-09-14", "2026-09-16", "2026-09-18",
"2026-09-21", "2026-09-23", "2026-09-25",
"2026-09-28", "2026-09-30", "2026-10-02",
"2026-10-05", "2026-10-07", "2026-10-09",
"2026-10-12", "2026-10-14", "2026-10-16",
"2026-10-19", "2026-10-21", "2026-10-23", "2026-10-26",
]
actual = occurrences_between(rule, "2026-09-01", "2026-10-26")
assert actual == expected, (
f"diff: {set(expected) ^ set(actual)}"
)
def test_hand_checked_8_week_sequence_weekly_interval_2_mondays() -> None:
"""8 weeks of a Monday rule at interval 2, anchored Mon 2026-09-07
(week 0 = Sep 7-13): fires in weeks 0, 2, 4, 6 -> Mon Sep 7, Mon Sep 21,
Mon Oct 5, Mon Oct 19."""
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0}, interval=2,
start_date="2026-09-07", end_date="2026-10-31",
)
actual = occurrences_between(rule, "2026-09-07", "2026-10-31")
assert actual == ["2026-09-07", "2026-09-21", "2026-10-05", "2026-10-19"]
def test_custom_days_hand_checked_8_week_sequence() -> None:
"""8 weeks of a Tue/Thu/Sun rule (1,3,6) anchored Mon 2026-09-07:
fires Tue 8, Thu 10, Sun 13, then weekly."""
rule = ScheduleRule(
rule_type=RuleType.CUSTOM_DAYS, weekday_set={1, 3, 6},
start_date="2026-09-07",
)
# Anchor weeks from Mon Sep 7 (w0 = Sep 7-13 ... w7 = Oct 26-Nov 1):
# Tue/Thu/Sun firings per week, 8 weeks fully covered.
actual = occurrences_between(rule, "2026-09-07", "2026-11-01")
assert actual == [
"2026-09-08", "2026-09-10", "2026-09-13",
"2026-09-15", "2026-09-17", "2026-09-20",
"2026-09-22", "2026-09-24", "2026-09-27",
"2026-09-29", "2026-10-01", "2026-10-04",
"2026-10-06", "2026-10-08", "2026-10-11",
"2026-10-13", "2026-10-15", "2026-10-18",
"2026-10-20", "2026-10-22", "2026-10-25",
"2026-10-27", "2026-10-29", "2026-11-01",
]
def test_weekly_survives_53_week_year_boundary() -> None:
"""Anchor arithmetic never flips at Jan 1 (the ISO parity trap):
a weekly rule spanning New Year keeps its weekday pattern."""
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={3}, # Thursdays
start_date="2026-12-24", # a Thursday
)
# Thursdays around New Year 2026->2027: Dec 24, 31, Jan 7, 14.
assert occurs_on(rule, _d("2026-12-24")) is True
assert occurs_on(rule, _d("2026-12-31")) is True
assert occurs_on(rule, _d("2027-01-07")) is True
assert occurs_on(rule, _d("2027-01-14")) is True
# Interleaved days are not Thursdays.
assert occurs_on(rule, _d("2027-01-04")) is False # Monday
assert occurs_on(rule, _d("2027-01-05")) is False # Tuesday
def test_weekly_interval_2_across_year_boundary() -> None:
"""Interval weeks continue across Jan 1 with no parity flip."""
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={4}, interval=2,
start_date="2026-12-25", # a Friday
)
# Weeks: Dec 25 (w0) fires, Jan 1 (w1) skipped, Jan 8 (w2) fires,
# Jan 15 (w3) skipped, Jan 22 (w4) fires.
assert occurs_on(rule, _d("2026-12-25")) is True
assert occurs_on(rule, _d("2027-01-01")) is False
assert occurs_on(rule, _d("2027-01-08")) is True
assert occurs_on(rule, _d("2027-01-15")) is False
assert occurs_on(rule, _d("2027-01-22")) is True
def test_occurrences_between_weekly_disjoint(tmp_path) -> None:
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={1},
start_date="2026-09-01", end_date="2026-09-30",
)
assert occurrences_between(rule, "2026-10-01", "2026-10-31") == []
def test_occurrences_between_weekly_interval_2_span() -> None:
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0}, interval=2,
start_date="2026-09-07", end_date="2026-10-31",
)
result = occurrences_between(rule, "2026-09-01", "2026-10-31")
assert result == ["2026-09-07", "2026-09-21", "2026-10-05", "2026-10-19"]
def test_occurrences_between_rejects_inverted_bounds() -> None:
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0}, start_date="2026-09-01"
)
with pytest.raises(RuleValidationError, match="on or after"):
occurrences_between(rule, "2026-10-10", "2026-09-01")
def test_weekly_interval_2_non_monday_anchor_boundary() -> None:
"""The anchor week is anchored at start_date, NOT a calendar week:
a Tuesday-anchored Monday rule fires on Mon Sep 7 (week 0 extends
through Sep 7), skips Mon Sep 14 (week 1), fires Mon Sep 21 (week 2)."""
rule = ScheduleRule(
rule_type=RuleType.WEEKLY, weekday_set={0}, interval=2,
start_date="2026-09-01", # a TUESDAY anchor
)
# Sep 7 - Sep 1 = 6 days -> week 0 (even): fires.
assert occurs_on(rule, _d("2026-09-07")) is True
# Sep 14: 13 days -> week 1 (odd): skipped.
assert occurs_on(rule, _d("2026-09-14")) is False
# Sep 21: 20 days -> week 2 (even): fires.
assert occurs_on(rule, _d("2026-09-21")) is True
# Sep 28: 27 days -> week 3 (odd): skipped.
assert occurs_on(rule, _d("2026-09-28")) is False
# Oct 5: 34 days -> week 4 (even): fires.
assert occurs_on(rule, _d("2026-10-05")) is True
+233
View File
@@ -0,0 +1,233 @@
"""Tests for YEARLY recurrence with the leap-day clamp policy."""
from __future__ import annotations
import datetime
import pytest
from custom_components.nestquest.recurrence import (
RuleType,
RuleValidationError,
ScheduleRule,
occurs_on,
occurrences_between,
)
def _d(date: str) -> datetime.date:
return datetime.date.fromisoformat(date)
# ---------------------------------------------------------------------------
# Nominal-day firings across four consecutive years (incl. leap 2028)
# ---------------------------------------------------------------------------
def test_yearly_june_15_four_consecutive_years() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=6, day_of_month=15,
start_date="2026-06-15",
)
for year in (2026, 2027, 2028, 2029):
assert occurs_on(rule, datetime.date(year, 6, 15)) is True, year
assert occurs_on(rule, datetime.date(2026, 6, 14)) is False
assert occurs_on(rule, datetime.date(2026, 6, 16)) is False
assert occurs_on(rule, datetime.date(2026, 5, 15)) is False
assert occurs_on(rule, datetime.date(2026, 7, 15)) is False
def test_yearly_feb_15_across_four_years() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=2, day_of_month=15,
start_date="2026-02-15",
)
# Feb 15 exists every year; the leap day is irrelevant.
for year in (2026, 2027, 2028, 2029):
assert occurs_on(rule, datetime.date(year, 2, 15)) is True, year
def test_yearly_never_fires_before_start() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=6, day_of_month=15,
start_date="2027-06-15",
)
assert occurs_on(rule, datetime.date(2026, 6, 15)) is False
assert occurs_on(rule, datetime.date(2027, 6, 15)) is True
def test_yearly_respects_end_date() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=6, day_of_month=15,
start_date="2026-06-15", end_date="2028-06-15",
)
assert occurs_on(rule, datetime.date(2028, 6, 15)) is True
assert occurs_on(rule, datetime.date(2029, 6, 15)) is False
# ---------------------------------------------------------------------------
# Leap-day policy: Feb 29 rule fires Feb 28 in non-leap years
# ---------------------------------------------------------------------------
def test_yearly_feb_29_clamps_to_feb_28_non_leap() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=2, day_of_month=29,
start_date="2026-02-28",
)
# 2026 non-leap: no Feb 29 — the clamp fires Feb 28.
assert occurs_on(rule, datetime.date(2026, 2, 28)) is True
assert occurs_on(rule, datetime.date(2026, 2, 27)) is False
# 2027 non-leap: same clamp.
assert occurs_on(rule, datetime.date(2027, 2, 28)) is True
def test_yearly_feb_29_fires_feb_29_in_leap_years() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=2, day_of_month=29,
start_date="2026-02-28",
)
# 2028 leap: Feb 29 exists — nominal day.
assert occurs_on(rule, datetime.date(2028, 2, 29)) is True
assert occurs_on(rule, datetime.date(2028, 2, 28)) is False
def test_yearly_feb_29_four_consecutive_years() -> None:
"""The done-condition's four-year sweep: 2026 (clamp 28), 2027
(clamp 28), 2028 (leap: nominal 29), 2029 (clamp 28)."""
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=2, day_of_month=29,
start_date="2026-02-28",
)
assert occurs_on(rule, datetime.date(2026, 2, 28)) is True
assert occurs_on(rule, datetime.date(2027, 2, 28)) is True
assert occurs_on(rule, datetime.date(2028, 2, 29)) is True
assert occurs_on(rule, datetime.date(2029, 2, 28)) is True
# No other day in those Februaries fires.
for year, non_firing in (
(2026, (27,)), (2027, (26, 27)), (2028, (27,)),
(2029, (26, 27)),
):
for day in non_firing:
assert occurs_on(rule, datetime.date(year, 2, day)) is False
def test_yearly_feb_30_is_impossible_by_model() -> None:
"""The model rejects day_of_month 30+ for February? No — 30/31 are
accepted (1..31) and clamp to the month end like MONTHLY_DAY."""
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=2, day_of_month=30,
start_date="2027-02-28",
)
# Non-leap 2027: Feb 28 is the month end — the clamp fires it.
assert occurs_on(rule, datetime.date(2027, 2, 28)) is True
# Leap 2028: Feb 29 is the month end — clamps there.
assert occurs_on(rule, datetime.date(2028, 2, 29)) is True
assert occurs_on(rule, datetime.date(2028, 2, 28)) is False
# ---------------------------------------------------------------------------
# Day-less YEARLY rules fire on the first of the month
# ---------------------------------------------------------------------------
def test_yearly_without_day_fires_on_first_of_month() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=6, start_date="2026-01-01",
)
assert occurs_on(rule, datetime.date(2026, 6, 1)) is True
assert occurs_on(rule, datetime.date(2026, 6, 2)) is False
assert occurs_on(rule, datetime.date(2026, 5, 1)) is False
assert occurs_on(rule, datetime.date(2027, 6, 1)) is True
# ---------------------------------------------------------------------------
# Interval: every N years
# ---------------------------------------------------------------------------
def test_yearly_interval_2_every_second_year() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=6, day_of_month=15, interval=2,
start_date="2026-06-15",
)
assert occurs_on(rule, datetime.date(2026, 6, 15)) is True # y0
assert occurs_on(rule, datetime.date(2027, 6, 15)) is False # y1
assert occurs_on(rule, datetime.date(2028, 6, 15)) is True # y2
assert occurs_on(rule, datetime.date(2029, 6, 15)) is False # y3
assert occurs_on(rule, datetime.date(2030, 6, 15)) is True # y4
def test_yearly_interval_2_leap_day_every_second_year() -> None:
"""A Feb 29 rule at interval 2 anchored 2026 fires in even years:
2026 clamps (Feb 28), 2027 skips, 2028 hits the nominal Feb 29."""
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=2, day_of_month=29, interval=2,
start_date="2026-02-28",
)
assert occurs_on(rule, datetime.date(2026, 2, 28)) is True # y0 clamp
assert occurs_on(rule, datetime.date(2027, 2, 28)) is False # y1
assert occurs_on(rule, datetime.date(2028, 2, 29)) is True # y2 nominal
assert occurs_on(rule, datetime.date(2029, 2, 28)) is False # y3
assert occurs_on(rule, datetime.date(2030, 2, 28)) is True # y4 clamp
def test_yearly_interval_3_across_start_year() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=3, day_of_month=10, interval=3,
start_date="2026-03-10",
)
assert occurs_on(rule, datetime.date(2026, 3, 10)) is True
assert occurs_on(rule, datetime.date(2027, 3, 10)) is False
assert occurs_on(rule, datetime.date(2028, 3, 10)) is False
assert occurs_on(rule, datetime.date(2029, 3, 10)) is True
# ---------------------------------------------------------------------------
# occurrences_between
# ---------------------------------------------------------------------------
def test_yearly_occurrences_between_span() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=2, day_of_month=29,
start_date="2026-02-28",
)
result = occurrences_between(rule, "2026-01-01", "2029-12-31")
assert result == [
"2026-02-28", "2027-02-28", "2028-02-29", "2029-02-28",
]
def test_yearly_occurrences_between_disjoint_range() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=6, day_of_month=15,
start_date="2026-06-15",
)
# The rule only ever fires in June: other months are empty.
assert occurrences_between(rule, "2027-01-01", "2027-05-31") == []
assert occurrences_between(rule, "2027-07-01", "2027-12-31") == []
def test_yearly_occurrences_between_rejects_inverted() -> None:
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=2, day_of_month=29,
start_date="2026-02-28",
)
with pytest.raises(RuleValidationError, match="on or after"):
occurrences_between(rule, "2029-01-01", "2026-01-01")
# ---------------------------------------------------------------------------
# Day of month 31 in a 30-day month: clamp consistency with MONTHLY_DAY
# ---------------------------------------------------------------------------
def test_yearly_june_31_clamps_to_june_30() -> None:
"""June has 30 days: a June 31st yearly rule clamps to June 30."""
rule = ScheduleRule(
rule_type=RuleType.YEARLY, month=6, day_of_month=31,
start_date="2026-06-30",
)
assert occurs_on(rule, datetime.date(2026, 6, 30)) is True
assert occurs_on(rule, datetime.date(2027, 6, 30)) is True
assert occurs_on(rule, datetime.date(2026, 6, 29)) is False