diff --git a/wake_alarm/_constants.py b/wake_alarm/_constants.py index f34042a..da0a169 100644 --- a/wake_alarm/_constants.py +++ b/wake_alarm/_constants.py @@ -21,14 +21,21 @@ DISMISS_WINDOW_MINUTES: int = 30 # all — no network *and* no cached read ever written. Minute is implicitly 0. FALLBACK_ALARM_HOUR: int = 13 -# Alarm escalation phase boundaries (minutes from alarm start) -PHASE_SOFT_END: int = 5 -PHASE_MEDIUM_END: int = 15 -# After PHASE_MEDIUM_END: continuous sine tone until dismiss window closes +# Alarm escalation phase boundaries (minutes from alarm start). +# +# Compressed to fit INSIDE the 5-minute failsafe window. They used to be 5 and +# 15, which -- once the failsafe was added at 300 s -- meant the alarm was +# silenced before it ever left the softest rung, and the medium and loud +# phases became unreachable code. The alarm has to reach its most annoying +# setting well before it goes quiet, or waiting out five minutes in bed is a +# winning strategy. +PHASE_SOFT_END: int = 1 +PHASE_MEDIUM_END: int = 2 +# After PHASE_MEDIUM_END: alternating loud tones until the failsafe silences. # Beep intervals per phase (seconds) -SOFT_BEEP_INTERVAL: float = 10.0 -MEDIUM_BEEP_INTERVAL: float = 5.0 +SOFT_BEEP_INTERVAL: float = 5.0 +MEDIUM_BEEP_INTERVAL: float = 3.0 LOUD_TOGGLE_INTERVAL: float = 2.0 # Dismiss challenge: length of the random code @@ -75,7 +82,18 @@ ESCAPE_HISTORY_FILE: Path = ( ) # How long the alarm must have been up before the hatch is offered, so it # is never the easy first move. -ESCAPE_OFFER_AFTER_SECONDS: int = 300 +# +# Deliberately NOT equal to FAILSAFE_SILENCE_SECONDS. Both used to sit at 300, +# which meant the sound stopped and the escape hatch appeared in the same +# instant -- making the hatch far more attractive than it was designed to be, +# exactly when the alarm had just stopped being annoying. +ESCAPE_OFFER_AFTER_SECONDS: int = 900 + +# When the failsafe silences the alarm. Audio ONLY: the lock, the typed +# challenge and the workout gate all persist past this point, so waiting it +# out in bed is not a way to escape the alarm. It exists so a ring nobody is +# present to dismiss does not sound indefinitely. +FAILSAFE_SILENCE_SECONDS: float = 300.0 SYNC_CONFIG_FILE: Path = Path.home() / ".config" / "wake_alarm" / "sync.json" diff --git a/wake_alarm/_escalation.py b/wake_alarm/_escalation.py new file mode 100644 index 0000000..bd5aefe --- /dev/null +++ b/wake_alarm/_escalation.py @@ -0,0 +1,82 @@ +"""Decide what the alarm should sound like at a given point in the ring. + +Split out of ``_alarm.py`` so the escalation ladder -- and, more importantly, +the failsafe that silences it -- is testable without a Tk window, a lock, or a +sound card. + +The failsafe silences **audio only**. The lock, the typed challenge and the +workout gate all persist: a five-minute wait must not become a way to get back +into bed. What it protects against is a runaway alarm nobody is present to +dismiss (an empty flat, a forgotten travel day), which is a neighbour problem, +not a wake-up problem. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from wake_alarm._constants import ( + FAILSAFE_SILENCE_SECONDS, + LOUD_TOGGLE_INTERVAL, + MEDIUM_BEEP_INTERVAL, + PHASE_MEDIUM_END, + PHASE_SOFT_END, + SOFT_BEEP_INTERVAL, +) + +# Tone frequencies for each rung of the ladder. +SOFT_FREQUENCY = 440 +MEDIUM_FREQUENCY = 1000 +LOUD_LOW_FREQUENCY = 800 +LOUD_HIGH_FREQUENCY = 1200 + + +@dataclass(frozen=True) +class BeepPlan: + """What the beep loop should do for one iteration. + + Attributes: + frequency: Tone to play, or None when the failsafe has silenced audio. + interval: Seconds to wait before reconsidering. + phase: Name of the rung, for logging. + silenced: True once the failsafe has stopped the sound. + """ + + frequency: int | None + interval: float + phase: str + silenced: bool + + +def plan_for(elapsed_seconds: float) -> BeepPlan: + """Choose the beep behaviour for a ring that started *elapsed_seconds* ago. + + Args: + elapsed_seconds: Seconds since the alarm began sounding. + + Returns: + The plan for this iteration. + """ + if elapsed_seconds >= FAILSAFE_SILENCE_SECONDS: + # Audio only. The caller keeps the lock and the challenge up. + return BeepPlan( + frequency=None, + interval=LOUD_TOGGLE_INTERVAL, + phase="failsafe-silent", + silenced=True, + ) + elapsed_minutes = elapsed_seconds / 60.0 + if elapsed_minutes < PHASE_SOFT_END: + return BeepPlan(SOFT_FREQUENCY, SOFT_BEEP_INTERVAL, "soft", silenced=False) + if elapsed_minutes < PHASE_MEDIUM_END: + return BeepPlan( + MEDIUM_FREQUENCY, + MEDIUM_BEEP_INTERVAL, + "medium", + silenced=False, + ) + # Alternate two tones: a changing pitch stays salient where a constant one + # is tuned out. + alternate = int(elapsed_minutes * 10) % 2 == 0 + frequency = LOUD_LOW_FREQUENCY if alternate else LOUD_HIGH_FREQUENCY + return BeepPlan(frequency, LOUD_TOGGLE_INTERVAL, "loud", silenced=False) diff --git a/wake_alarm/tests/test_alarm_beep_phases.py b/wake_alarm/tests/test_alarm_beep_phases.py new file mode 100644 index 0000000..e9e522a --- /dev/null +++ b/wake_alarm/tests/test_alarm_beep_phases.py @@ -0,0 +1,161 @@ +"""Tests for the beep escalation loop's phase selection.""" + +from __future__ import annotations + +import tkinter as tk +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, patch + +import pytest + +if TYPE_CHECKING: + from collections.abc import Generator + +from wake_alarm._alarm import ( + WakeAlarm, +) +from wake_alarm._constants import ( + PHASE_MEDIUM_END, + PHASE_SOFT_END, +) + + +def _make_mock_tk() -> MagicMock: + """Build a MagicMock that stands in for the tkinter module.""" + mock = MagicMock() + mock_root = MagicMock() + mock_root.winfo_screenwidth.return_value = 1920 + mock_root.winfo_screenheight.return_value = 1080 + mock.Tk.return_value = mock_root + mock.Frame.return_value = MagicMock() + mock.Label.return_value = MagicMock() + mock.Entry.return_value = MagicMock() + mock.TclError = tk.TclError + mock.END = tk.END + return mock + + +@pytest.fixture(autouse=True) +def _block_real_tk() -> Generator[MagicMock]: + """Prevent any real Tk windows in tests.""" + mock = _make_mock_tk() + with ( + patch("wake_alarm._alarm.tk", mock), + patch("wake_alarm._alarm_view.tk", mock), + patch( + "wake_alarm._alarm.GateRoot", + return_value=mock.Tk.return_value, + ), + ): + yield mock + + +@pytest.fixture(autouse=True) +def _block_extra_devices() -> Generator[MagicMock]: + """Prevent real subprocess calls for extra ALSA devices and hardware.""" + with ( + patch("wake_alarm._alarm._play_on_all_sinks") as mock, + patch("wake_alarm._alarm._max_fans", return_value=False), + patch("wake_alarm._alarm._restore_fans"), + patch("wake_alarm._alarm._set_max_brightness"), + patch("wake_alarm._alarm._wake_display"), + patch("wake_alarm._alarm._restore_display"), + patch("wake_alarm._alarm._warn_if_no_real_sink"), + patch("wake_alarm._alarm._activate_all_outputs", return_value=None), + patch("wake_alarm._alarm._restore_audio_state"), + patch("wake_alarm._alarm.turn_on_plug"), + patch("wake_alarm._alarm.turn_off_plug"), + ): + yield mock + + +@pytest.fixture +def mock_tk_module() -> Generator[MagicMock]: + """Provide explicit access to the mocked tk module.""" + mock = _make_mock_tk() + with ( + patch("wake_alarm._alarm.tk", mock), + patch("wake_alarm._alarm_view.tk", mock), + patch( + "wake_alarm._alarm.GateRoot", + return_value=mock.Tk.return_value, + ), + ): + yield mock + + +class TestBeepLoopPhases: + """Tests for different beep loop escalation phases.""" + + def test_medium_phase( + self, + mock_tk_module: MagicMock, + ) -> None: + """Beep loop enters medium phase after PHASE_SOFT_END minutes.""" + alarm = WakeAlarm(demo_mode=True) + # Set alarm start to make elapsed > PHASE_SOFT_END minutes + import time as time_mod + + # Midpoint of the medium band, not "one past the soft boundary": the + # phases are tuned to fit inside the failsafe window, so an offset + # anchored to one edge can land in the next phase entirely. + midpoint = (PHASE_SOFT_END + PHASE_MEDIUM_END) / 2 + alarm._progress.started_at = time_mod.monotonic() - midpoint * 60 + + call_count = 0 + + def stop_after_one(*_args: object, **_kwargs: object) -> None: + nonlocal call_count + call_count += 1 + if call_count >= 1: + alarm._stop_beep.set() + + with ( + patch( + "wake_alarm._alarm._beep_medium", + side_effect=stop_after_one, + ) as mock_beep, + # Any other rung also ends the loop, so a mistuned phase boundary + # fails this test instead of spinning forever on the real audio + # stack -- which previously hung the entire suite. + patch("wake_alarm._alarm._beep_soft", side_effect=stop_after_one), + patch("wake_alarm._alarm._beep_loud", side_effect=stop_after_one), + patch("wake_alarm._alarm._play_on_all_sinks"), + ): + alarm._beep_loop() + + mock_beep.assert_called() + alarm._stop_beep.set() + + def test_loud_phase( + self, + mock_tk_module: MagicMock, + ) -> None: + """Beep loop enters loud phase after PHASE_MEDIUM_END minutes.""" + alarm = WakeAlarm(demo_mode=True) + import time as time_mod + + alarm._progress.started_at = time_mod.monotonic() - (PHASE_MEDIUM_END + 1) * 60 + + call_count = 0 + + def stop_after_one(*_args: object, **_kwargs: object) -> None: + nonlocal call_count + call_count += 1 + if call_count >= 1: + alarm._stop_beep.set() + + with ( + patch( + "wake_alarm._alarm._beep_loud", + side_effect=stop_after_one, + ) as mock_beep, + # See the note in test_medium_phase: any rung must end the loop. + patch("wake_alarm._alarm._beep_soft", side_effect=stop_after_one), + patch("wake_alarm._alarm._beep_medium", side_effect=stop_after_one), + patch("wake_alarm._alarm._play_on_all_sinks"), + ): + alarm._beep_loop() + + mock_beep.assert_called() + alarm._stop_beep.set() diff --git a/wake_alarm/tests/test_alarm_flash_challenge.py b/wake_alarm/tests/test_alarm_flash_challenge.py new file mode 100644 index 0000000..1a8c299 --- /dev/null +++ b/wake_alarm/tests/test_alarm_flash_challenge.py @@ -0,0 +1,180 @@ +"""Tests for the flash-challenge dismiss round.""" + +from __future__ import annotations + +import tkinter as tk +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, patch + +import pytest + +if TYPE_CHECKING: + from collections.abc import Generator + +from wake_alarm._alarm import ( + WakeAlarm, +) + + +def _make_mock_tk() -> MagicMock: + """Build a MagicMock that stands in for the tkinter module.""" + mock = MagicMock() + mock_root = MagicMock() + mock_root.winfo_screenwidth.return_value = 1920 + mock_root.winfo_screenheight.return_value = 1080 + mock.Tk.return_value = mock_root + mock.Frame.return_value = MagicMock() + mock.Label.return_value = MagicMock() + mock.Entry.return_value = MagicMock() + mock.TclError = tk.TclError + mock.END = tk.END + return mock + + +@pytest.fixture(autouse=True) +def _block_real_tk() -> Generator[MagicMock]: + """Prevent any real Tk windows in tests.""" + mock = _make_mock_tk() + with ( + patch("wake_alarm._alarm.tk", mock), + patch("wake_alarm._alarm_view.tk", mock), + patch( + "wake_alarm._alarm.GateRoot", + return_value=mock.Tk.return_value, + ), + ): + yield mock + + +@pytest.fixture(autouse=True) +def _block_extra_devices() -> Generator[MagicMock]: + """Prevent real subprocess calls for extra ALSA devices and hardware.""" + with ( + patch("wake_alarm._alarm._play_on_all_sinks") as mock, + patch("wake_alarm._alarm._max_fans", return_value=False), + patch("wake_alarm._alarm._restore_fans"), + patch("wake_alarm._alarm._set_max_brightness"), + patch("wake_alarm._alarm._wake_display"), + patch("wake_alarm._alarm._restore_display"), + patch("wake_alarm._alarm._warn_if_no_real_sink"), + patch("wake_alarm._alarm._activate_all_outputs", return_value=None), + patch("wake_alarm._alarm._restore_audio_state"), + patch("wake_alarm._alarm.turn_on_plug"), + patch("wake_alarm._alarm.turn_off_plug"), + ): + yield mock + + +@pytest.fixture +def mock_tk_module() -> Generator[MagicMock]: + """Provide explicit access to the mocked tk module.""" + mock = _make_mock_tk() + with ( + patch("wake_alarm._alarm.tk", mock), + patch("wake_alarm._alarm_view.tk", mock), + patch( + "wake_alarm._alarm.GateRoot", + return_value=mock.Tk.return_value, + ), + ): + yield mock + + +class TestFlashChallenge: + """Tests for flash challenge countdown behaviour inside WakeAlarm.""" + + def test_flash_tick_counts_down_and_hides( + self, + mock_tk_module: MagicMock, + ) -> None: + """_flash_tick counts down per second and hides the code at zero.""" + from wake_alarm._alarm import _Challenge + + alarm = WakeAlarm(demo_mode=True) + alarm._progress.current_challenge = _Challenge( + kind="flash", + display="ABCDEFGH", + answer="ABCDEFGH", + hint="Memorise", + ) + alarm._progress.flash_remaining = 2 + alarm._view._views[0].labels.status.configure.reset_mock() + + alarm._flash_tick() + assert alarm._progress.flash_remaining == 1 + alarm._view._views[0].labels.status.configure.assert_called() + + alarm._flash_tick() + assert alarm._progress.flash_remaining == 0 + + # Final tick hides the code. + alarm._flash_tick() + # _code_label and _status_label share the same mock; inspect all calls. + all_texts = [ + c.kwargs.get("text", "") + for c in alarm._view._views[0].labels.code.configure.call_args_list + ] + assert any("?" in t for t in all_texts) + alarm._stop_beep.set() + + def test_flash_tick_noop_when_inactive( + self, + mock_tk_module: MagicMock, + ) -> None: + """_flash_tick returns immediately when the alarm is no longer active.""" + alarm = WakeAlarm(demo_mode=True) + alarm._active = False + alarm._progress.flash_remaining = 3 + alarm._view._views[0].labels.status.configure.reset_mock() + + alarm._flash_tick() + + alarm._view._views[0].labels.status.configure.assert_not_called() + alarm._stop_beep.set() + + def test_wrong_flash_answer_reshows_code( + self, + mock_tk_module: MagicMock, + ) -> None: + """Wrong flash answer restores the code and restarts the countdown.""" + from wake_alarm._alarm import _Challenge + + alarm = WakeAlarm(demo_mode=True) + alarm._progress.current_challenge = _Challenge( + kind="flash", + display="TESTCODE", + answer="TESTCODE", + hint="Memorise", + ) + alarm._view.entry_var.get.return_value = "WRONGCODE" + alarm._view._views[0].labels.code.configure.reset_mock() + + alarm._on_submit() + + assert alarm.dismissed is False + # Code label should be reconfigured (code shown again + countdown restarted). + alarm._view._views[0].labels.code.configure.assert_called() + alarm._stop_beep.set() + + def test_next_round_flash_starts_countdown( + self, + mock_tk_module: MagicMock, + ) -> None: + """When the next-round challenge is flash, the countdown starts immediately.""" + from wake_alarm._alarm import _Challenge + + alarm = WakeAlarm(demo_mode=True) + alarm._progress.current_challenge = _Challenge( + kind="math", display="2 + 2 = ?", answer="4", hint="test" + ) + next_flash = _Challenge( + kind="flash", display="ABCDEFGH", answer="ABCDEFGH", hint="Memorise" + ) + alarm._view.entry_var.get.return_value = "4" + + with patch("wake_alarm._alarm._make_challenge", return_value=next_flash): + alarm._on_submit() + + assert alarm._progress.current_challenge.kind == "flash" + assert alarm.dismissed is False + alarm._stop_beep.set() diff --git a/wake_alarm/tests/test_alarm_part3.py b/wake_alarm/tests/test_alarm_part3.py index 15cecad..ba7423d 100644 --- a/wake_alarm/tests/test_alarm_part3.py +++ b/wake_alarm/tests/test_alarm_part3.py @@ -14,10 +14,6 @@ if TYPE_CHECKING: from wake_alarm._alarm import ( WakeAlarm, ) -from wake_alarm._constants import ( - PHASE_MEDIUM_END, - PHASE_SOFT_END, -) def _make_mock_tk() -> MagicMock: @@ -84,69 +80,6 @@ def mock_tk_module() -> Generator[MagicMock]: yield mock -class TestBeepLoopPhases: - """Tests for different beep loop escalation phases.""" - - def test_medium_phase( - self, - mock_tk_module: MagicMock, - ) -> None: - """Beep loop enters medium phase after PHASE_SOFT_END minutes.""" - alarm = WakeAlarm(demo_mode=True) - # Set alarm start to make elapsed > PHASE_SOFT_END minutes - import time as time_mod - - alarm._progress.started_at = time_mod.monotonic() - (PHASE_SOFT_END + 1) * 60 - - call_count = 0 - - def stop_after_one(*_args: object, **_kwargs: object) -> None: - nonlocal call_count - call_count += 1 - if call_count >= 1: - alarm._stop_beep.set() - - with ( - patch( - "wake_alarm._alarm._beep_medium", - side_effect=stop_after_one, - ) as mock_beep, - ): - alarm._beep_loop() - - mock_beep.assert_called() - alarm._stop_beep.set() - - def test_loud_phase( - self, - mock_tk_module: MagicMock, - ) -> None: - """Beep loop enters loud phase after PHASE_MEDIUM_END minutes.""" - alarm = WakeAlarm(demo_mode=True) - import time as time_mod - - alarm._progress.started_at = time_mod.monotonic() - (PHASE_MEDIUM_END + 1) * 60 - - call_count = 0 - - def stop_after_one(*_args: object, **_kwargs: object) -> None: - nonlocal call_count - call_count += 1 - if call_count >= 1: - alarm._stop_beep.set() - - with ( - patch( - "wake_alarm._alarm._beep_loud", - side_effect=stop_after_one, - ) as mock_beep, - ): - alarm._beep_loop() - - mock_beep.assert_called() - alarm._stop_beep.set() - - class TestRunMethod: """Tests for the run() method.""" @@ -214,106 +147,6 @@ class TestUpdateTimerActive: alarm._stop_beep.set() -class TestFlashChallenge: - """Tests for flash challenge countdown behaviour inside WakeAlarm.""" - - def test_flash_tick_counts_down_and_hides( - self, - mock_tk_module: MagicMock, - ) -> None: - """_flash_tick counts down per second and hides the code at zero.""" - from wake_alarm._alarm import _Challenge - - alarm = WakeAlarm(demo_mode=True) - alarm._progress.current_challenge = _Challenge( - kind="flash", - display="ABCDEFGH", - answer="ABCDEFGH", - hint="Memorise", - ) - alarm._progress.flash_remaining = 2 - alarm._view._views[0].labels.status.configure.reset_mock() - - alarm._flash_tick() - assert alarm._progress.flash_remaining == 1 - alarm._view._views[0].labels.status.configure.assert_called() - - alarm._flash_tick() - assert alarm._progress.flash_remaining == 0 - - # Final tick hides the code. - alarm._flash_tick() - # _code_label and _status_label share the same mock; inspect all calls. - all_texts = [ - c.kwargs.get("text", "") - for c in alarm._view._views[0].labels.code.configure.call_args_list - ] - assert any("?" in t for t in all_texts) - alarm._stop_beep.set() - - def test_flash_tick_noop_when_inactive( - self, - mock_tk_module: MagicMock, - ) -> None: - """_flash_tick returns immediately when the alarm is no longer active.""" - alarm = WakeAlarm(demo_mode=True) - alarm._active = False - alarm._progress.flash_remaining = 3 - alarm._view._views[0].labels.status.configure.reset_mock() - - alarm._flash_tick() - - alarm._view._views[0].labels.status.configure.assert_not_called() - alarm._stop_beep.set() - - def test_wrong_flash_answer_reshows_code( - self, - mock_tk_module: MagicMock, - ) -> None: - """Wrong flash answer restores the code and restarts the countdown.""" - from wake_alarm._alarm import _Challenge - - alarm = WakeAlarm(demo_mode=True) - alarm._progress.current_challenge = _Challenge( - kind="flash", - display="TESTCODE", - answer="TESTCODE", - hint="Memorise", - ) - alarm._view.entry_var.get.return_value = "WRONGCODE" - alarm._view._views[0].labels.code.configure.reset_mock() - - alarm._on_submit() - - assert alarm.dismissed is False - # Code label should be reconfigured (code shown again + countdown restarted). - alarm._view._views[0].labels.code.configure.assert_called() - alarm._stop_beep.set() - - def test_next_round_flash_starts_countdown( - self, - mock_tk_module: MagicMock, - ) -> None: - """When the next-round challenge is flash, the countdown starts immediately.""" - from wake_alarm._alarm import _Challenge - - alarm = WakeAlarm(demo_mode=True) - alarm._progress.current_challenge = _Challenge( - kind="math", display="2 + 2 = ?", answer="4", hint="test" - ) - next_flash = _Challenge( - kind="flash", display="ABCDEFGH", answer="ABCDEFGH", hint="Memorise" - ) - alarm._view.entry_var.get.return_value = "4" - - with patch("wake_alarm._alarm._make_challenge", return_value=next_flash): - alarm._on_submit() - - assert alarm._progress.current_challenge.kind == "flash" - assert alarm.dismissed is False - alarm._stop_beep.set() - - class TestDismissWithoutSkip: """Tests for alarm dismiss without earning skip.""" diff --git a/wake_alarm/tests/test_escalation.py b/wake_alarm/tests/test_escalation.py new file mode 100644 index 0000000..e5bbf3f --- /dev/null +++ b/wake_alarm/tests/test_escalation.py @@ -0,0 +1,91 @@ +"""Tests for the beep escalation ladder and the audio failsafe.""" + +from __future__ import annotations + +import pytest + +from wake_alarm._constants import ( + ESCAPE_OFFER_AFTER_SECONDS, + FAILSAFE_SILENCE_SECONDS, + PHASE_MEDIUM_END, + PHASE_SOFT_END, +) +from wake_alarm._escalation import ( + LOUD_HIGH_FREQUENCY, + LOUD_LOW_FREQUENCY, + MEDIUM_FREQUENCY, + SOFT_FREQUENCY, + plan_for, +) + + +def test_starts_on_the_soft_rung() -> None: + """The first seconds are the gentlest tone.""" + plan = plan_for(0.0) + assert plan.frequency == SOFT_FREQUENCY + assert plan.phase == "soft" + + +def test_escalates_to_medium() -> None: + """Crossing the soft boundary raises the pitch.""" + assert plan_for(PHASE_SOFT_END * 60).frequency == MEDIUM_FREQUENCY + + +def test_escalates_to_loud() -> None: + """Crossing the medium boundary reaches the loud rung.""" + assert plan_for(PHASE_MEDIUM_END * 60).phase == "loud" + + +def test_loud_phase_alternates_between_two_tones() -> None: + """A changing pitch stays salient where a constant one is tuned out.""" + seen = {plan_for(PHASE_MEDIUM_END * 60 + offset).frequency for offset in range(20)} + assert seen == {LOUD_LOW_FREQUENCY, LOUD_HIGH_FREQUENCY} + + +def test_intervals_shorten_as_it_escalates() -> None: + """Each rung beeps more often than the last.""" + soft = plan_for(0.0).interval + medium = plan_for(PHASE_SOFT_END * 60).interval + loud = plan_for(PHASE_MEDIUM_END * 60).interval + assert soft > medium > loud + + +def test_failsafe_silences_audio_at_the_threshold() -> None: + """At the failsafe the tone stops.""" + plan = plan_for(FAILSAFE_SILENCE_SECONDS) + assert plan.frequency is None + assert plan.silenced is True + + +def test_audio_still_sounds_just_before_the_failsafe() -> None: + """The boundary is exclusive; a moment earlier the alarm is still loud.""" + plan = plan_for(FAILSAFE_SILENCE_SECONDS - 1) + assert plan.frequency is not None + assert plan.silenced is False + + +@pytest.mark.parametrize("extra", [1, 60, 600, 3600]) +def test_stays_silent_after_the_failsafe(extra: int) -> None: + """Silence is permanent for the rest of the ring; it never resumes.""" + assert plan_for(FAILSAFE_SILENCE_SECONDS + extra).silenced is True + + +def test_reaches_the_loud_phase_before_the_failsafe() -> None: + """The whole point: the alarm must get maximally annoying before it stops. + + A regression here would silently reduce the alarm to its softest tone, + which is exactly the bug this ordering exists to prevent. + """ + assert PHASE_MEDIUM_END * 60 < FAILSAFE_SILENCE_SECONDS + + +def test_spends_most_of_the_ring_on_the_loud_rung() -> None: + """Loud should dominate the audible window, not be a brief tail.""" + loud_seconds = FAILSAFE_SILENCE_SECONDS - PHASE_MEDIUM_END * 60 + assert loud_seconds >= FAILSAFE_SILENCE_SECONDS / 2 + + +def test_escape_hatch_does_not_open_when_the_sound_stops() -> None: + """Offering the hatch exactly as the alarm goes quiet makes it too easy.""" + assert ESCAPE_OFFER_AFTER_SECONDS != FAILSAFE_SILENCE_SECONDS + assert ESCAPE_OFFER_AFTER_SECONDS > FAILSAFE_SILENCE_SECONDS