mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-23 14:36:18 +01:00
Derive meal slots from an eating window and a meal count
First step of the configurable meal schedule: the pure arithmetic, in both languages, with nothing wired to it yet. MealSchedule(8, 20, 5) gives 08, 11, 14, 17, 20; the default MealSchedule(8, 20, 4) reproduces the hours that are currently hardcoded, so nothing changes behaviour until a user picks something else. Two properties are load-bearing and both are tested rather than asserted in prose: Integer arithmetic only, no floats and no round(). Python's round() is banker's (round(2.5) == 2) and Dart's is half-away-from-zero (2.5.round() == 3), so a floating-point derivation would silently disagree across devices -- and a slot one device offers but the other does not is a checkpoint that can never be satisfied, i.e. a permanent lock. The shared vector table plus an identical 6912-case sweep in both suites is what catches that class of bug before it reaches a device. Counts are clamped to the window width rather than rejected. A narrow window (08-12 across 6 meals) would otherwise repeat an hour -- 8, 9, 10, 10, 11, 12 -- and slot hours are used as set members, map keys and notification ids, so a repeat silently drops a checkpoint. Clamping also means the two languages cannot disagree about which inputs are errors. The enforcement cutoff is now derived as last + 2h (clamped to midnight) rather than sharing the constant that also bounded the slot range. The clamp matters: 23:00 + 2 = 25 would make `hour < cutoff` vacuously true and the window would never close. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0159b4E5hh512jYUeaJVNxfM
This commit is contained in:
parent
cbbebee79b
commit
83c3030b55
154
app/lib/models/meal_schedule.dart
Normal file
154
app/lib/models/meal_schedule.dart
Normal file
@ -0,0 +1,154 @@
|
||||
/// The user's eating window and meal count, and the slot hours they imply.
|
||||
///
|
||||
/// A schedule is three numbers -- the first meal hour, the last meal hour, and
|
||||
/// how many meals fall between them inclusive -- from which the intermediate
|
||||
/// checkpoints are derived by even division. `MealSchedule(8, 20, 5)` yields
|
||||
/// `[8, 11, 14, 17, 20]`.
|
||||
///
|
||||
/// This file is pure: no clock, no storage, no settings lookup. Persistence
|
||||
/// lives in `services/meal_schedule_service.dart`, and the slot arithmetic
|
||||
/// that consumes a schedule lives in `models/slot.dart`.
|
||||
///
|
||||
/// KEEP IN SYNC WITH `diet_guard/_meal_schedule.py`. The two must agree on
|
||||
/// every input, because a device that derives different slots than its peer
|
||||
/// nags for checkpoints the other never offers -- and a slot that can never be
|
||||
/// satisfied is a permanent lock. Two rules make that agreement checkable:
|
||||
///
|
||||
/// * **Integer arithmetic only.** No doubles and no `round()` anywhere in the
|
||||
/// derivation. Dart's `round()` is half-away-from-zero (`2.5.round() == 3`)
|
||||
/// while Python's is banker's rounding (`round(2.5) == 2`), so any
|
||||
/// floating-point path is a latent cross-language split brain. `~/` here,
|
||||
/// `//` there.
|
||||
/// * **Clamp, don't reject.** Every out-of-range input is normalised to the
|
||||
/// nearest legal schedule rather than throwing, so the two languages cannot
|
||||
/// disagree about which inputs are errors.
|
||||
library;
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Fewest meals a schedule may describe.
|
||||
const int kMinMealCount = 2;
|
||||
|
||||
/// Most meals a schedule may describe.
|
||||
///
|
||||
/// Bounded by legibility, not nutrition: the pills that render these have to
|
||||
/// stay readable on a phone at their widest (all-logged) size -- see
|
||||
/// `test/widgets/slot_selector_row_test.dart`.
|
||||
const int kMaxMealCount = 6;
|
||||
|
||||
/// Earliest hour a meal may be scheduled at.
|
||||
const int kFirstHour = 0;
|
||||
|
||||
/// Latest hour a meal may be scheduled at.
|
||||
const int kLastHour = 23;
|
||||
|
||||
/// Grace period after the final checkpoint, before the gate stops firing.
|
||||
///
|
||||
/// Deliberately a constant rather than the slot spacing: it is how long you
|
||||
/// have to log a late dinner, which has nothing to do with how many meals you
|
||||
/// eat. Tying it to the spacing would stretch the lockout window to midnight
|
||||
/// at four meals, contradicting the "don't trap me overnight" intent.
|
||||
const int kEnforcementTailHours = 2;
|
||||
|
||||
const int _hoursPerDay = 24;
|
||||
|
||||
int _clamp(int value, int low, int high) =>
|
||||
value < low ? low : (value > high ? high : value);
|
||||
|
||||
/// An eating window and the number of meals inside it.
|
||||
@immutable
|
||||
class MealSchedule {
|
||||
/// Creates a [MealSchedule].
|
||||
const MealSchedule({
|
||||
required this.first,
|
||||
required this.last,
|
||||
required this.count,
|
||||
});
|
||||
|
||||
/// Hour of the first meal, 0-23.
|
||||
final int first;
|
||||
|
||||
/// Hour of the last meal, strictly after [first].
|
||||
final int last;
|
||||
|
||||
/// Total meals including both endpoints.
|
||||
final int count;
|
||||
|
||||
/// Returns an equivalent schedule guaranteed to satisfy the invariants.
|
||||
///
|
||||
/// Ordering matters: [first] is clamped into the day, then [last] is clamped
|
||||
/// to leave at least one hour of window, then [count] is clamped to the
|
||||
/// window's width. That last clamp is the load-bearing one -- see [slots].
|
||||
MealSchedule normalized() {
|
||||
final normFirst = _clamp(first, kFirstHour, kLastHour - 1);
|
||||
final normLast = _clamp(last, normFirst + 1, kLastHour);
|
||||
// A window of N hours holds at most N+1 whole-hour checkpoints; asking for
|
||||
// more would repeat an hour (see slots()).
|
||||
final normCount = _clamp(
|
||||
count,
|
||||
kMinMealCount,
|
||||
kMaxMealCount < normLast - normFirst + 1
|
||||
? kMaxMealCount
|
||||
: normLast - normFirst + 1,
|
||||
);
|
||||
return MealSchedule(first: normFirst, last: normLast, count: normCount);
|
||||
}
|
||||
|
||||
/// Returns the meal-slot hours, ascending, with both endpoints exact.
|
||||
///
|
||||
/// Meals are spread evenly across the window and rounded to whole hours by
|
||||
/// integer arithmetic: slot *i* is `first + (i*span + d ~/ 2) ~/ d` where
|
||||
/// `span = last - first` and `d = count - 1`. The `d ~/ 2` term is a
|
||||
/// round-half-up bias applied before the division, which is what keeps this
|
||||
/// free of floating point.
|
||||
///
|
||||
/// Both endpoints land exactly on [first] and [last] by construction, so the
|
||||
/// eating window is always honoured even when interior spacing must round.
|
||||
///
|
||||
/// The result is strictly ascending because [normalized] caps [count] at
|
||||
/// `last - first + 1`. Without that cap a narrow window repeats an hour
|
||||
/// (`08-12` with 6 meals would give `8, 9, 10, 10, 11, 12`), and since slot
|
||||
/// hours are used as set members, map keys *and* notification ids, a repeat
|
||||
/// silently drops a checkpoint.
|
||||
List<int> slots() {
|
||||
final schedule = normalized();
|
||||
final span = schedule.last - schedule.first;
|
||||
final divisions = schedule.count - 1;
|
||||
return [
|
||||
for (var index = 0; index < schedule.count; index++)
|
||||
schedule.first + (index * span + divisions ~/ 2) ~/ divisions,
|
||||
];
|
||||
}
|
||||
|
||||
/// The hour at which slot enforcement stops for the day.
|
||||
///
|
||||
/// Clamped to the end of the day: a 23:00 last meal would otherwise put the
|
||||
/// cutoff at 25, making `hour < cutoff` vacuously true so the enforcement
|
||||
/// window never closes and the reminder can never stop firing.
|
||||
int get enforcementEndHour {
|
||||
final end = last + kEnforcementTailHours;
|
||||
return end < _hoursPerDay ? end : _hoursPerDay;
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is MealSchedule &&
|
||||
other.first == first &&
|
||||
other.last == last &&
|
||||
other.count == count;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(first, last, count);
|
||||
|
||||
@override
|
||||
String toString() => 'MealSchedule($first-$last x$count)';
|
||||
}
|
||||
|
||||
/// The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, enforcement
|
||||
/// closing at 22:00. Still what a device uses before the user has chosen
|
||||
/// anything, so upgrading changes no behaviour.
|
||||
const MealSchedule kDefaultSchedule = MealSchedule(
|
||||
first: 8,
|
||||
last: 20,
|
||||
count: 4,
|
||||
);
|
||||
@ -2,7 +2,7 @@ name: diet_guard_app
|
||||
description: "Companion phone app for diet_guard: log meals on the go."
|
||||
publish_to: 'none'
|
||||
|
||||
version: 1.0.30+1
|
||||
version: 1.0.31+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
|
||||
153
app/test/models/meal_schedule_test.dart
Normal file
153
app/test/models/meal_schedule_test.dart
Normal file
@ -0,0 +1,153 @@
|
||||
/// Tests for the pure meal-schedule derivation.
|
||||
///
|
||||
/// The vector table below is duplicated verbatim from
|
||||
/// `diet_guard/tests/test_meal_schedule.py`. KEEP THE TWO IN SYNC: it is the
|
||||
/// only thing that catches a Python/Dart divergence before it reaches a
|
||||
/// device, and a divergence there means one device nags for a checkpoint the
|
||||
/// other never offers -- a slot that can never be satisfied, i.e. a permanent
|
||||
/// lock.
|
||||
library;
|
||||
|
||||
import 'package:diet_guard_app/models/meal_schedule.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
/// (first, last, count, expected slots). Shared with the Python mirror.
|
||||
const List<(int, int, int, List<int>)> scheduleVectors = [
|
||||
// The eating window the user described, at every supported meal count.
|
||||
(8, 20, 2, [8, 20]),
|
||||
(8, 20, 3, [8, 14, 20]),
|
||||
(8, 20, 4, [8, 12, 16, 20]), // today's hardcoded schedule
|
||||
(8, 20, 5, [8, 11, 14, 17, 20]), // the user's stated example
|
||||
(8, 20, 6, [8, 10, 13, 15, 18, 20]),
|
||||
// A window that does not divide evenly: 14 hours across 3 gaps.
|
||||
(7, 21, 4, [7, 12, 16, 21]),
|
||||
(7, 21, 5, [7, 11, 14, 18, 21]),
|
||||
(9, 19, 4, [9, 12, 16, 19]),
|
||||
// Narrow windows: count is capped at the number of whole hours available,
|
||||
// so the slots stay distinct instead of repeating an hour.
|
||||
(8, 12, 6, [8, 9, 10, 11, 12]),
|
||||
(8, 10, 5, [8, 9, 10]),
|
||||
(8, 9, 4, [8, 9]),
|
||||
// Whole-day extremes.
|
||||
(0, 23, 6, [0, 5, 9, 14, 18, 23]),
|
||||
(0, 1, 2, [0, 1]),
|
||||
];
|
||||
|
||||
void main() {
|
||||
group('slots', () {
|
||||
for (final (first, last, count, expected) in scheduleVectors) {
|
||||
test('$first-$last x$count derives $expected', () {
|
||||
expect(
|
||||
MealSchedule(first: first, last: last, count: count).slots(),
|
||||
expected,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test('the default is the historical schedule', () {
|
||||
expect(kDefaultSchedule.slots(), [8, 12, 16, 20]);
|
||||
});
|
||||
|
||||
test('endpoints stay exact when the spacing rounds', () {
|
||||
final slots = const MealSchedule(first: 8, last: 20, count: 6).slots();
|
||||
expect(slots.first, 8);
|
||||
expect(slots.last, 20);
|
||||
});
|
||||
});
|
||||
|
||||
group('normalized', () {
|
||||
const cases = <(MealSchedule, MealSchedule)>[
|
||||
(
|
||||
MealSchedule(first: 8, last: 20, count: 99),
|
||||
MealSchedule(first: 8, last: 20, count: kMaxMealCount),
|
||||
),
|
||||
(
|
||||
MealSchedule(first: 8, last: 20, count: 0),
|
||||
MealSchedule(first: 8, last: 20, count: kMinMealCount),
|
||||
),
|
||||
(
|
||||
MealSchedule(first: -5, last: 20, count: 4),
|
||||
MealSchedule(first: 0, last: 20, count: 4),
|
||||
),
|
||||
(
|
||||
MealSchedule(first: 8, last: 99, count: 4),
|
||||
MealSchedule(first: 8, last: 23, count: 4),
|
||||
),
|
||||
// last <= first is pulled forward to leave a one-hour window.
|
||||
(
|
||||
MealSchedule(first: 12, last: 12, count: 4),
|
||||
MealSchedule(first: 12, last: 13, count: 2),
|
||||
),
|
||||
(
|
||||
MealSchedule(first: 12, last: 3, count: 4),
|
||||
MealSchedule(first: 12, last: 13, count: 2),
|
||||
),
|
||||
// first cannot occupy the final hour, or no window would remain.
|
||||
(
|
||||
MealSchedule(first: 23, last: 23, count: 2),
|
||||
MealSchedule(first: 22, last: 23, count: 2),
|
||||
),
|
||||
];
|
||||
|
||||
for (final (input, expected) in cases) {
|
||||
test('$input clamps to $expected', () {
|
||||
expect(input.normalized(), expected);
|
||||
});
|
||||
}
|
||||
|
||||
test('garbage still yields usable slots', () {
|
||||
expect(
|
||||
const MealSchedule(first: 99, last: -5, count: 999).slots(),
|
||||
[22, 23],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('enforcementEndHour', () {
|
||||
test('the default keeps the historical 22:00 cutoff', () {
|
||||
expect(kDefaultSchedule.enforcementEndHour, 22);
|
||||
});
|
||||
|
||||
test('the tail follows the last meal', () {
|
||||
expect(
|
||||
const MealSchedule(first: 8, last: 18, count: 4).enforcementEndHour,
|
||||
20,
|
||||
);
|
||||
});
|
||||
|
||||
test('is clamped to the end of the day', () {
|
||||
// An unclamped 23 + 2 = 25 would make `hour < cutoff` vacuously true,
|
||||
// so the enforcement window would never close.
|
||||
expect(
|
||||
const MealSchedule(first: 8, last: 23, count: 4).enforcementEndHour,
|
||||
24,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('every input yields ascending slots with exact endpoints', () {
|
||||
// The Dart half of the cross-language parity guarantee; the Python mirror
|
||||
// runs the identical sweep.
|
||||
for (var first = -2; first < 26; first++) {
|
||||
for (var last = -2; last < 26; last++) {
|
||||
for (var count = -2; count < 10; count++) {
|
||||
final schedule = MealSchedule(
|
||||
first: first,
|
||||
last: last,
|
||||
count: count,
|
||||
);
|
||||
final normalized = schedule.normalized();
|
||||
final slots = schedule.slots();
|
||||
|
||||
expect(slots.first, normalized.first);
|
||||
expect(slots.last, normalized.last);
|
||||
expect(slots.length, normalized.count);
|
||||
expect(slots.toSet().length, slots.length);
|
||||
expect(slots, orderedEquals(List<int>.of(slots)..sort()));
|
||||
expect(slots.length, greaterThanOrEqualTo(kMinMealCount));
|
||||
expect(slots.length, lessThanOrEqualTo(kMaxMealCount));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
134
diet_guard/_meal_schedule.py
Normal file
134
diet_guard/_meal_schedule.py
Normal file
@ -0,0 +1,134 @@
|
||||
"""The user's eating window and meal count, and the slot hours they imply.
|
||||
|
||||
A schedule is three numbers -- the first meal hour, the last meal hour, and how
|
||||
many meals fall between them inclusive -- from which the intermediate
|
||||
checkpoints are derived by even division. ``MealSchedule(8, 20, 5)`` yields
|
||||
``(8, 11, 14, 17, 20)``.
|
||||
|
||||
This module is pure: no clock, no filesystem, no configuration lookup. Storage
|
||||
lives in :mod:`diet_guard._meal_schedule_store`, and the slot arithmetic that
|
||||
consumes a schedule lives in :mod:`diet_guard._slots`.
|
||||
|
||||
KEEP IN SYNC WITH ``app/lib/models/meal_schedule.dart``. The two must agree on
|
||||
every input, because a device that derives different slots than its peer nags
|
||||
for checkpoints the other never offers -- and a slot that can never be
|
||||
satisfied is a permanent lock. Two rules make that agreement checkable:
|
||||
|
||||
* **Integer arithmetic only.** No floats and no ``round()`` anywhere in the
|
||||
derivation. Python's ``round`` is banker's rounding (``round(2.5) == 2``)
|
||||
while Dart's is half-away-from-zero (``2.5.round() == 3``), so any float path
|
||||
is a latent cross-language split brain. ``//`` here, ``~/`` there.
|
||||
* **Clamp, don't reject.** Every out-of-range input is normalised to the
|
||||
nearest legal schedule rather than raising, so the two languages cannot
|
||||
disagree about which inputs are errors.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
# A day's meals must fit inside a day, and the pills that render them have to
|
||||
# stay legible on a phone at the widest (all-logged) size -- see
|
||||
# ``app/test/widgets/slot_selector_row_test.dart``.
|
||||
MIN_MEAL_COUNT = 2
|
||||
MAX_MEAL_COUNT = 6
|
||||
|
||||
FIRST_HOUR = 0
|
||||
LAST_HOUR = 23
|
||||
|
||||
# Grace period after the final checkpoint, before the gate stops firing for
|
||||
# the day. Deliberately a constant rather than the slot spacing: it is how
|
||||
# long you have to log a late dinner, which has nothing to do with how many
|
||||
# meals you eat. Tying it to the spacing would stretch the lockout window to
|
||||
# midnight at four meals, contradicting the "don't trap me overnight" intent
|
||||
# this cutoff exists to serve.
|
||||
ENFORCEMENT_TAIL_HOURS = 2
|
||||
|
||||
_HOURS_PER_DAY = 24
|
||||
|
||||
|
||||
def _clamp(value: int, low: int, high: int) -> int:
|
||||
"""Return ``value`` confined to ``[low, high]``."""
|
||||
return max(low, min(high, value))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MealSchedule:
|
||||
"""An eating window and the number of meals inside it.
|
||||
|
||||
Attributes:
|
||||
first: Hour of the first meal, 0-23.
|
||||
last: Hour of the last meal, strictly after ``first``.
|
||||
count: Total meals including both endpoints.
|
||||
"""
|
||||
|
||||
first: int
|
||||
last: int
|
||||
count: int
|
||||
|
||||
def normalized(self) -> MealSchedule:
|
||||
"""Return an equivalent schedule guaranteed to satisfy the invariants.
|
||||
|
||||
Ordering matters: ``first`` is clamped into the day, then ``last`` is
|
||||
clamped to leave at least one hour of window, then ``count`` is clamped
|
||||
to the window's width. That last clamp is the load-bearing one -- see
|
||||
:meth:`slots`.
|
||||
|
||||
Returns:
|
||||
A schedule whose ``slots()`` is strictly ascending.
|
||||
"""
|
||||
first = _clamp(self.first, FIRST_HOUR, LAST_HOUR - 1)
|
||||
last = _clamp(self.last, first + 1, LAST_HOUR)
|
||||
# A window of N hours holds at most N+1 whole-hour checkpoints; asking
|
||||
# for more would repeat an hour (see slots()).
|
||||
count = _clamp(
|
||||
self.count, MIN_MEAL_COUNT, min(MAX_MEAL_COUNT, last - first + 1)
|
||||
)
|
||||
return MealSchedule(first, last, count)
|
||||
|
||||
def slots(self) -> tuple[int, ...]:
|
||||
"""Return the meal-slot hours, ascending, endpoints exact.
|
||||
|
||||
Meals are spread evenly across the window and rounded to whole hours by
|
||||
integer arithmetic: slot *i* is ``first + (i*span + d//2) // d`` where
|
||||
``span = last - first`` and ``d = count - 1``. The ``d//2`` term is a
|
||||
round-half-up bias applied before the division, which is what keeps
|
||||
this float-free.
|
||||
|
||||
Both endpoints land exactly on ``first`` and ``last`` by construction,
|
||||
so the eating window is always honoured even when the interior spacing
|
||||
has to round.
|
||||
|
||||
The result is strictly ascending because :meth:`normalized` caps
|
||||
``count`` at ``last - first + 1``. Without that cap a narrow window
|
||||
repeats an hour (``08-12`` with 6 meals would give
|
||||
``8, 9, 10, 10, 11, 12``), and since slot hours are used as set
|
||||
members, dict keys *and* notification ids, a repeat silently drops a
|
||||
checkpoint.
|
||||
|
||||
Returns:
|
||||
The slot hours, ascending, of length ``normalized().count``.
|
||||
"""
|
||||
schedule = self.normalized()
|
||||
span = schedule.last - schedule.first
|
||||
divisions = schedule.count - 1
|
||||
return tuple(
|
||||
schedule.first + (index * span + divisions // 2) // divisions
|
||||
for index in range(schedule.count)
|
||||
)
|
||||
|
||||
@property
|
||||
def enforcement_end_hour(self) -> int:
|
||||
"""Return the hour at which slot enforcement stops for the day.
|
||||
|
||||
Clamped to the end of the day: a 23:00 last meal would otherwise put
|
||||
the cutoff at 25, making ``hour < cutoff`` vacuously true so the
|
||||
enforcement window never closes and the gate can never stop firing.
|
||||
"""
|
||||
return min(self.last + ENFORCEMENT_TAIL_HOURS, _HOURS_PER_DAY)
|
||||
|
||||
|
||||
# The historical hardcoded schedule: 08:00, 12:00, 16:00, 20:00, with the
|
||||
# enforcement window closing at 22:00. Still what a device uses before the
|
||||
# user has ever chosen anything, so upgrading changes no behaviour.
|
||||
DEFAULT_SCHEDULE = MealSchedule(first=8, last=20, count=4)
|
||||
134
diet_guard/tests/test_meal_schedule.py
Normal file
134
diet_guard/tests/test_meal_schedule.py
Normal file
@ -0,0 +1,134 @@
|
||||
"""Tests for the pure meal-schedule derivation.
|
||||
|
||||
The vector table below is duplicated verbatim in
|
||||
``app/test/models/meal_schedule_test.dart``. KEEP THE TWO IN SYNC: it is the
|
||||
only thing that catches a Python/Dart divergence before it reaches a device,
|
||||
and a divergence there means one device nags for a checkpoint the other never
|
||||
offers -- a slot that can never be satisfied, i.e. a permanent lock.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from diet_guard._meal_schedule import (
|
||||
DEFAULT_SCHEDULE,
|
||||
MAX_MEAL_COUNT,
|
||||
MIN_MEAL_COUNT,
|
||||
MealSchedule,
|
||||
)
|
||||
|
||||
# (first, last, count) -> expected slot hours. Shared with the Dart mirror.
|
||||
SCHEDULE_VECTORS: list[tuple[int, int, int, tuple[int, ...]]] = [
|
||||
# The eating window the user described, at every supported meal count.
|
||||
(8, 20, 2, (8, 20)),
|
||||
(8, 20, 3, (8, 14, 20)),
|
||||
(8, 20, 4, (8, 12, 16, 20)), # today's hardcoded schedule
|
||||
(8, 20, 5, (8, 11, 14, 17, 20)), # the user's stated example
|
||||
(8, 20, 6, (8, 10, 13, 15, 18, 20)),
|
||||
# A window that does not divide evenly: 14 hours across 3 gaps.
|
||||
(7, 21, 4, (7, 12, 16, 21)),
|
||||
(7, 21, 5, (7, 11, 14, 18, 21)),
|
||||
(9, 19, 4, (9, 12, 16, 19)),
|
||||
# Narrow windows: count is capped at the number of whole hours available,
|
||||
# so the slots stay distinct instead of repeating an hour.
|
||||
(8, 12, 6, (8, 9, 10, 11, 12)),
|
||||
(8, 10, 5, (8, 9, 10)),
|
||||
(8, 9, 4, (8, 9)),
|
||||
# Whole-day extremes.
|
||||
(0, 23, 6, (0, 5, 9, 14, 18, 23)),
|
||||
(0, 1, 2, (0, 1)),
|
||||
]
|
||||
|
||||
|
||||
class TestSlots:
|
||||
"""Slot derivation from a schedule."""
|
||||
|
||||
@pytest.mark.parametrize(("first", "last", "count", "expected"), SCHEDULE_VECTORS)
|
||||
def test_matches_shared_vectors(
|
||||
self, first: int, last: int, count: int, expected: tuple[int, ...]
|
||||
) -> None:
|
||||
"""Each shared vector derives its documented slot hours."""
|
||||
assert MealSchedule(first, last, count).slots() == expected
|
||||
|
||||
def test_default_is_the_historical_schedule(self) -> None:
|
||||
"""The default reproduces the hours that used to be hardcoded."""
|
||||
assert DEFAULT_SCHEDULE.slots() == (8, 12, 16, 20)
|
||||
|
||||
def test_endpoints_are_exact_when_spacing_rounds(self) -> None:
|
||||
"""Rounding the interior never drags an endpoint off the window."""
|
||||
slots = MealSchedule(8, 20, 6).slots()
|
||||
assert slots[0] == 8
|
||||
assert slots[-1] == 20
|
||||
|
||||
|
||||
class TestNormalization:
|
||||
"""Out-of-range input is clamped, never rejected."""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("schedule", "expected"),
|
||||
[
|
||||
(MealSchedule(8, 20, 99), MealSchedule(8, 20, MAX_MEAL_COUNT)),
|
||||
(MealSchedule(8, 20, 0), MealSchedule(8, 20, MIN_MEAL_COUNT)),
|
||||
(MealSchedule(-5, 20, 4), MealSchedule(0, 20, 4)),
|
||||
(MealSchedule(8, 99, 4), MealSchedule(8, 23, 4)),
|
||||
# last <= first is pulled forward to leave a one-hour window.
|
||||
(MealSchedule(12, 12, 4), MealSchedule(12, 13, 2)),
|
||||
(MealSchedule(12, 3, 4), MealSchedule(12, 13, 2)),
|
||||
# first cannot occupy the final hour, or no window would remain.
|
||||
(MealSchedule(23, 23, 2), MealSchedule(22, 23, 2)),
|
||||
],
|
||||
)
|
||||
def test_clamps_to_the_nearest_legal_schedule(
|
||||
self, schedule: MealSchedule, expected: MealSchedule
|
||||
) -> None:
|
||||
"""Illegal values are pulled into range rather than raising."""
|
||||
assert schedule.normalized() == expected
|
||||
|
||||
def test_garbage_still_yields_usable_slots(self) -> None:
|
||||
"""Wildly invalid input degrades to a schedule, not an exception."""
|
||||
assert MealSchedule(99, -5, 999).slots() == (22, 23)
|
||||
|
||||
|
||||
class TestEnforcementEndHour:
|
||||
"""The daily cutoff derived from the last meal."""
|
||||
|
||||
def test_default_keeps_the_historical_cutoff(self) -> None:
|
||||
"""The default schedule still stops enforcing at 22:00."""
|
||||
assert DEFAULT_SCHEDULE.enforcement_end_hour == 22
|
||||
|
||||
def test_tail_follows_the_last_meal(self) -> None:
|
||||
"""Moving the last meal moves the cutoff with it."""
|
||||
assert MealSchedule(8, 18, 4).enforcement_end_hour == 20
|
||||
|
||||
def test_clamped_to_the_end_of_the_day(self) -> None:
|
||||
"""A late last meal cannot push the cutoff past midnight.
|
||||
|
||||
An unclamped 23 + 2 = 25 would make ``hour < cutoff`` vacuously true,
|
||||
so the enforcement window would never close.
|
||||
"""
|
||||
assert MealSchedule(8, 23, 4).enforcement_end_hour == 24
|
||||
|
||||
|
||||
class TestExhaustiveInvariants:
|
||||
"""Properties that must hold for every input the UI or sync can produce."""
|
||||
|
||||
def test_every_input_yields_ascending_slots_with_exact_endpoints(self) -> None:
|
||||
"""Sweep the whole input space, including out-of-range values.
|
||||
|
||||
This is the cheap half of the cross-language parity guarantee; the
|
||||
Dart mirror runs the identical sweep.
|
||||
"""
|
||||
for first in range(-2, 26):
|
||||
for last in range(-2, 26):
|
||||
for count in range(-2, 10):
|
||||
schedule = MealSchedule(first, last, count)
|
||||
normalized = schedule.normalized()
|
||||
slots = schedule.slots()
|
||||
|
||||
assert slots[0] == normalized.first
|
||||
assert slots[-1] == normalized.last
|
||||
assert len(slots) == normalized.count
|
||||
assert len(set(slots)) == len(slots)
|
||||
assert list(slots) == sorted(slots)
|
||||
assert MIN_MEAL_COUNT <= len(slots) <= MAX_MEAL_COUNT
|
||||
Loading…
Reference in New Issue
Block a user