mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-23 21:46:28 +01:00
Two spots blocked the alarm on a timer, guessing when the monitor's HDMI sink would be "ready": - _activate_all_outputs polled _list_real_sinks in a loop with time.sleep, waiting up to 20s for ALARM_AUDIO_SINK to appear. - main() slept DISPLAY_WAKE_WAIT_SECONDS (5s) after waking the display before audio setup. Both are gone. Activation now forces every card's output profile on and activates whatever sink is present at that instant; the beep loop's _play_on_all_sinks already re-lists real sinks every cycle, so a slow monitor is swept in the moment it actually enumerates — a real presence check, never a timed guess. main() wakes the display and proceeds immediately; the monitor powers on in parallel. Removes now-dead constants ALARM_AUDIO_CARD, ALARM_AUDIO_PROFILE, ALARM_AUDIO_SINK_WAIT_SECONDS, ALARM_AUDIO_SINK_POLL_SECONDS, DISPLAY_WAKE_WAIT_SECONDS. Activation returns in ~0.26s (was up to 20s); the test suite drops from ~12s to ~2s (two main() tests were each really sleeping 5s). 100% branch coverage retained. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018SJ6HYXhBmYs3SiGBZv1rF
458 lines
18 KiB
Python
458 lines
18 KiB
Python
"""Tests for pactl sink/card enumeration, activation, and restore."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import subprocess
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
from wake_alarm._alarm import _parse_args
|
|
from wake_alarm._constants import ALARM_AUDIO_SINK
|
|
from wake_alarm._sinks import (
|
|
_activate_all_outputs,
|
|
_AudioState,
|
|
_capture_audio_state,
|
|
_CardInfo,
|
|
_current_default_sink,
|
|
_list_cards,
|
|
_list_real_sinks,
|
|
_pactl_text,
|
|
_parse_cards,
|
|
_parse_profile_line,
|
|
_parse_sinks,
|
|
_restore_audio_state,
|
|
_warn_if_no_real_sink,
|
|
)
|
|
|
|
# A representative `pactl list cards` block covering every parse branch:
|
|
# an HDMI card (off, with an available stereo output profile), an input-only
|
|
# card (no output profile), a card block with no Name line (must be skipped).
|
|
_CARDS_TEXT = """Card #54
|
|
\tName: alsa_card.hdmi
|
|
\tDriver: module-alsa-card.c
|
|
\tProfiles:
|
|
\t\toff: Off (sinks: 0, sources: 0, priority: 0, available: yes)
|
|
\t\toutput:hdmi-stereo: Stereo (sinks: 1, priority: 5900, available: yes)
|
|
\t\toutput:hdmi-surround: Surround (sinks: 1, priority: 600, available: no)
|
|
\t\tbroken (available: yes)
|
|
\tActive Profile: off
|
|
Card #55
|
|
\tName: alsa_card.mic
|
|
\tProfiles:
|
|
\t\toff: Off (sinks: 0, sources: 0, priority: 0, available: yes)
|
|
\tActive Profile: off
|
|
Card #56
|
|
\tProfiles:
|
|
\t\toutput:noname: NoName (available: yes)
|
|
\tActive Profile: off
|
|
"""
|
|
|
|
# A `pactl list sinks` block: a normal sink, plus one whose Volume line has
|
|
# no integer (to cover the "no digit" branch), plus a leading non-Name line.
|
|
_SINKS_TEXT = """Sink #62
|
|
\tState: SUSPENDED
|
|
\tName: alsa_output.analog
|
|
\tMute: no
|
|
\tVolume: front-left: 65536 / 100%
|
|
\tDescription: Built-in Analog
|
|
Sink #63
|
|
\tName: alsa_output.weird
|
|
\tMute: yes
|
|
\tVolume: n/a
|
|
"""
|
|
|
|
|
|
class TestPactlText:
|
|
"""Tests for _pactl_text."""
|
|
|
|
def test_returns_decoded_stdout(self) -> None:
|
|
"""Success → decoded stdout string."""
|
|
proc = MagicMock(stdout=b"hello\n")
|
|
with patch("wake_alarm._sinks.subprocess.run", return_value=proc):
|
|
assert _pactl_text("/usr/bin/pactl", "info") == "hello\n"
|
|
|
|
def test_returns_none_on_error(self) -> None:
|
|
"""OSError/TimeoutExpired → None, no raise."""
|
|
with patch(
|
|
"wake_alarm._sinks.subprocess.run",
|
|
side_effect=subprocess.TimeoutExpired("pactl", 5),
|
|
):
|
|
assert _pactl_text("/usr/bin/pactl", "info") is None
|
|
|
|
|
|
class TestPactlPath:
|
|
"""Tests for _pactl_path."""
|
|
|
|
def test_returns_which_result(self) -> None:
|
|
"""Delegates to shutil.which('pactl')."""
|
|
from wake_alarm._sinks import _pactl_path
|
|
|
|
with patch(
|
|
"wake_alarm._sinks.shutil.which",
|
|
return_value="/usr/bin/pactl",
|
|
):
|
|
assert _pactl_path() == "/usr/bin/pactl"
|
|
|
|
|
|
class TestListRealSinks:
|
|
"""Tests for _list_real_sinks."""
|
|
|
|
def test_filters_auto_null(self) -> None:
|
|
"""auto_null is dropped; real sink names are returned."""
|
|
text = (
|
|
"62\talsa_output.analog\tPipeWire\t-\t-\n4319\tauto_null\tPipeWire\t-\t-\n"
|
|
)
|
|
with patch("wake_alarm._sinks._pactl_text", return_value=text):
|
|
assert _list_real_sinks("/usr/bin/pactl") == ["alsa_output.analog"]
|
|
|
|
def test_returns_empty_on_none(self) -> None:
|
|
"""pactl failure (None text) → empty list."""
|
|
with patch("wake_alarm._sinks._pactl_text", return_value=None):
|
|
assert _list_real_sinks("/usr/bin/pactl") == []
|
|
|
|
|
|
class TestListCards:
|
|
"""Tests for _list_cards."""
|
|
|
|
def test_parses_names(self) -> None:
|
|
"""Returns the card name column of `list short cards`."""
|
|
text = "54\talsa_card.hdmi\talsa\n55\talsa_card.mic\talsa\n"
|
|
with patch("wake_alarm._sinks._pactl_text", return_value=text):
|
|
assert _list_cards("/usr/bin/pactl") == [
|
|
"alsa_card.hdmi",
|
|
"alsa_card.mic",
|
|
]
|
|
|
|
def test_returns_empty_on_none(self) -> None:
|
|
"""pactl failure (None text) → empty list."""
|
|
with patch("wake_alarm._sinks._pactl_text", return_value=None):
|
|
assert _list_cards("/usr/bin/pactl") == []
|
|
|
|
|
|
class TestParseProfileLine:
|
|
"""Tests for _parse_profile_line."""
|
|
|
|
def test_non_output_returns_none(self) -> None:
|
|
"""A non-output profile line → None."""
|
|
assert _parse_profile_line("off: Off (available: yes)") is None
|
|
|
|
def test_unavailable_returns_none(self) -> None:
|
|
"""An output profile marked available: no → None."""
|
|
assert _parse_profile_line("output:x: X (available: no)") is None
|
|
|
|
def test_missing_colon_space_returns_none(self) -> None:
|
|
"""An output line with no ': ' separator → None."""
|
|
assert _parse_profile_line("output:x") is None
|
|
|
|
def test_defaults_priority_zero(self) -> None:
|
|
"""An available output with no priority field → priority 0."""
|
|
assert _parse_profile_line("output:x: X (available: yes)") == ("output:x", 0)
|
|
|
|
def test_parses_priority(self) -> None:
|
|
"""Priority is parsed from the line."""
|
|
assert _parse_profile_line(
|
|
"output:hdmi: HDMI (priority: 5900, available: yes)",
|
|
) == ("output:hdmi", 5900)
|
|
|
|
|
|
class TestParseCards:
|
|
"""Tests for _parse_cards."""
|
|
|
|
def test_parses_and_skips_edge_cases(self) -> None:
|
|
"""Stereo preferred, input-only card empty, unnamed card skipped."""
|
|
cards = _parse_cards(_CARDS_TEXT)
|
|
assert set(cards) == {"alsa_card.hdmi", "alsa_card.mic"}
|
|
assert cards["alsa_card.hdmi"].active_profile == "off"
|
|
assert cards["alsa_card.hdmi"].output_profiles == ["output:hdmi-stereo"]
|
|
assert cards["alsa_card.mic"].output_profiles == []
|
|
|
|
def test_ignores_lines_before_first_card(self) -> None:
|
|
"""Leading noise before the first `Card #` is ignored."""
|
|
assert _parse_cards("junk\nmore junk\n") == {}
|
|
|
|
|
|
class TestParseSinks:
|
|
"""Tests for _parse_sinks."""
|
|
|
|
def test_parses_volume_and_mute(self) -> None:
|
|
"""Captures first raw volume and mute state per sink."""
|
|
volumes, mutes = _parse_sinks(_SINKS_TEXT)
|
|
assert volumes["alsa_output.analog"] == "65536"
|
|
assert mutes == {"alsa_output.analog": False, "alsa_output.weird": True}
|
|
|
|
def test_volume_without_digit_is_skipped(self) -> None:
|
|
"""A Volume line with no integer is not recorded."""
|
|
volumes, _ = _parse_sinks(_SINKS_TEXT)
|
|
assert "alsa_output.weird" not in volumes
|
|
|
|
|
|
class TestCurrentDefaultSink:
|
|
"""Tests for _current_default_sink."""
|
|
|
|
def test_returns_sink_name(self) -> None:
|
|
"""Returns the trimmed default sink name."""
|
|
proc = MagicMock(stdout=b"jbl_sink\n")
|
|
with patch("wake_alarm._sinks.subprocess.run", return_value=proc):
|
|
assert _current_default_sink("/usr/bin/pactl") == "jbl_sink"
|
|
|
|
def test_returns_none_when_empty(self) -> None:
|
|
"""Empty output → None."""
|
|
proc = MagicMock(stdout=b"\n")
|
|
with patch("wake_alarm._sinks.subprocess.run", return_value=proc):
|
|
assert _current_default_sink("/usr/bin/pactl") is None
|
|
|
|
def test_returns_none_on_error(self) -> None:
|
|
"""TimeoutExpired → None, no raise."""
|
|
with patch(
|
|
"wake_alarm._sinks.subprocess.run",
|
|
side_effect=subprocess.TimeoutExpired("pactl", 3),
|
|
):
|
|
assert _current_default_sink("/usr/bin/pactl") is None
|
|
|
|
|
|
class TestCaptureAudioState:
|
|
"""Tests for _capture_audio_state."""
|
|
|
|
def test_captures_profiles_volumes_mutes_default(self) -> None:
|
|
"""Combines card profiles, sink volumes/mutes, and the default sink."""
|
|
with (
|
|
patch(
|
|
"wake_alarm._sinks._pactl_text",
|
|
side_effect=[_CARDS_TEXT, _SINKS_TEXT],
|
|
),
|
|
patch(
|
|
"wake_alarm._sinks._current_default_sink",
|
|
return_value="alsa_output.analog",
|
|
),
|
|
):
|
|
state = _capture_audio_state("/usr/bin/pactl")
|
|
assert state.default_sink == "alsa_output.analog"
|
|
assert state.card_profiles["alsa_card.hdmi"] == "off"
|
|
assert state.sink_volumes["alsa_output.analog"] == "65536"
|
|
assert state.sink_mutes["alsa_output.analog"] is False
|
|
|
|
|
|
class TestActivateAllOutputs:
|
|
"""Tests for _activate_all_outputs."""
|
|
|
|
def test_returns_none_when_pactl_missing(self) -> None:
|
|
"""No pactl on PATH → returns None without touching audio."""
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value=None),
|
|
patch("wake_alarm._sinks.subprocess.run") as mock_run,
|
|
):
|
|
assert _activate_all_outputs() is None
|
|
mock_run.assert_not_called()
|
|
|
|
def _sentinel_state(self) -> _AudioState:
|
|
return _AudioState(
|
|
default_sink="old",
|
|
card_profiles={},
|
|
sink_volumes={},
|
|
sink_mutes={},
|
|
)
|
|
|
|
def test_activates_and_prefers_alarm_sink(self) -> None:
|
|
"""Forces card profiles on, maxes sinks, defaults to ALARM_AUDIO_SINK."""
|
|
state = self._sentinel_state()
|
|
cards = {
|
|
"card_hdmi": _CardInfo(None, ["output:hdmi-stereo"]),
|
|
"card_mic": _CardInfo(None, []),
|
|
}
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value="/usr/bin/pactl"),
|
|
patch("wake_alarm._sinks._capture_audio_state", return_value=state),
|
|
patch("wake_alarm._sinks._pactl_text", return_value=""),
|
|
patch("wake_alarm._sinks._parse_cards", return_value=cards),
|
|
patch(
|
|
"wake_alarm._sinks._list_real_sinks",
|
|
return_value=[ALARM_AUDIO_SINK, "other"],
|
|
),
|
|
patch("wake_alarm._sinks._ensure_sink_audible") as mock_audible,
|
|
patch("wake_alarm._sinks.subprocess.run") as mock_run,
|
|
):
|
|
assert _activate_all_outputs() is state
|
|
cmds = [call.args[0] for call in mock_run.call_args_list]
|
|
assert [
|
|
"/usr/bin/pactl",
|
|
"set-card-profile",
|
|
"card_hdmi",
|
|
"output:hdmi-stereo",
|
|
] in cmds
|
|
# The input-only card (no output profile) is never switched.
|
|
assert not any(c[2] == "card_mic" for c in cmds if c[1] == "set-card-profile")
|
|
assert ["/usr/bin/pactl", "set-default-sink", ALARM_AUDIO_SINK] in cmds
|
|
assert mock_audible.call_count == 2
|
|
|
|
def test_does_not_block_on_sink_enumeration(self) -> None:
|
|
"""Activation checks present sinks once — no polling/sleeping loop.
|
|
|
|
The per-cycle presence check in _play_on_all_sinks is what covers a
|
|
slow monitor sink, so activation must not spin waiting for it.
|
|
"""
|
|
state = self._sentinel_state()
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value="/usr/bin/pactl"),
|
|
patch("wake_alarm._sinks._capture_audio_state", return_value=state),
|
|
patch("wake_alarm._sinks._pactl_text", return_value=""),
|
|
patch("wake_alarm._sinks._parse_cards", return_value={}),
|
|
patch(
|
|
"wake_alarm._sinks._list_real_sinks",
|
|
return_value=[ALARM_AUDIO_SINK],
|
|
) as mock_list,
|
|
patch("wake_alarm._sinks._ensure_sink_audible"),
|
|
patch("wake_alarm._sinks.subprocess.run"),
|
|
):
|
|
assert _activate_all_outputs() is state
|
|
# Enumerated exactly once — no retry/poll loop.
|
|
mock_list.assert_called_once()
|
|
|
|
def test_falls_back_to_first_sink_when_alarm_sink_absent(self) -> None:
|
|
"""ALARM_AUDIO_SINK not present → default is the first present sink."""
|
|
state = self._sentinel_state()
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value="/usr/bin/pactl"),
|
|
patch("wake_alarm._sinks._capture_audio_state", return_value=state),
|
|
patch("wake_alarm._sinks._pactl_text", return_value=""),
|
|
patch("wake_alarm._sinks._parse_cards", return_value={}),
|
|
patch("wake_alarm._sinks._list_real_sinks", return_value=["other"]),
|
|
patch("wake_alarm._sinks._ensure_sink_audible"),
|
|
patch("wake_alarm._sinks.subprocess.run") as mock_run,
|
|
):
|
|
assert _activate_all_outputs() is state
|
|
cmds = [call.args[0] for call in mock_run.call_args_list]
|
|
assert ["/usr/bin/pactl", "set-default-sink", "other"] in cmds
|
|
|
|
def test_returns_state_when_no_sink_present(self) -> None:
|
|
"""No real sink present yet → returns state, no default, no maxing."""
|
|
state = self._sentinel_state()
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value="/usr/bin/pactl"),
|
|
patch("wake_alarm._sinks._capture_audio_state", return_value=state),
|
|
patch("wake_alarm._sinks._pactl_text", return_value=""),
|
|
patch("wake_alarm._sinks._parse_cards", return_value={}),
|
|
patch("wake_alarm._sinks._list_real_sinks", return_value=[]),
|
|
patch("wake_alarm._sinks._ensure_sink_audible") as mock_audible,
|
|
patch("wake_alarm._sinks.subprocess.run") as mock_run,
|
|
):
|
|
assert _activate_all_outputs() is state
|
|
mock_audible.assert_not_called()
|
|
cmds = [call.args[0] for call in mock_run.call_args_list]
|
|
assert not any(c[1] == "set-default-sink" for c in cmds)
|
|
|
|
|
|
class TestRestoreAudioState:
|
|
"""Tests for _restore_audio_state."""
|
|
|
|
def test_none_is_noop(self) -> None:
|
|
"""None state → does nothing, no pactl lookup."""
|
|
with patch("wake_alarm._sinks._pactl_path") as mock_path:
|
|
_restore_audio_state(None)
|
|
mock_path.assert_not_called()
|
|
|
|
def test_no_pactl_returns_silently(self) -> None:
|
|
"""State present but pactl missing → no raise, no run."""
|
|
state = _AudioState(
|
|
default_sink="s",
|
|
card_profiles={},
|
|
sink_volumes={},
|
|
sink_mutes={},
|
|
)
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value=None),
|
|
patch("wake_alarm._sinks.subprocess.run") as mock_run,
|
|
):
|
|
_restore_audio_state(state)
|
|
mock_run.assert_not_called()
|
|
|
|
def test_restores_everything(self) -> None:
|
|
"""Restores card profiles, sink volumes, mutes, and the default sink."""
|
|
state = _AudioState(
|
|
default_sink="analog",
|
|
card_profiles={"card_hdmi": "off"},
|
|
sink_volumes={"analog": "65536"},
|
|
sink_mutes={"analog": True},
|
|
)
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value="/usr/bin/pactl"),
|
|
patch("wake_alarm._sinks.subprocess.run") as mock_run,
|
|
):
|
|
_restore_audio_state(state)
|
|
cmds = [call.args[0] for call in mock_run.call_args_list]
|
|
assert ["/usr/bin/pactl", "set-card-profile", "card_hdmi", "off"] in cmds
|
|
assert ["/usr/bin/pactl", "set-sink-volume", "analog", "65536"] in cmds
|
|
assert ["/usr/bin/pactl", "set-sink-mute", "analog", "1"] in cmds
|
|
assert ["/usr/bin/pactl", "set-default-sink", "analog"] in cmds
|
|
|
|
def test_skips_default_when_none(self) -> None:
|
|
"""default_sink None → no set-default-sink command."""
|
|
state = _AudioState(
|
|
default_sink=None,
|
|
card_profiles={},
|
|
sink_volumes={"analog": "100"},
|
|
sink_mutes={"analog": False},
|
|
)
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value="/usr/bin/pactl"),
|
|
patch("wake_alarm._sinks.subprocess.run") as mock_run,
|
|
):
|
|
_restore_audio_state(state)
|
|
cmds = [call.args[0] for call in mock_run.call_args_list]
|
|
assert not any(c[1] == "set-default-sink" for c in cmds)
|
|
# Unmuted sink restores with "0".
|
|
assert ["/usr/bin/pactl", "set-sink-mute", "analog", "0"] in cmds
|
|
|
|
|
|
class TestWarnIfNoRealSink:
|
|
"""Tests for _warn_if_no_real_sink."""
|
|
|
|
def test_logs_when_pactl_missing(self) -> None:
|
|
"""No pactl on PATH → warns and returns (no sink lookup)."""
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value=None),
|
|
patch("wake_alarm._sinks._list_real_sinks") as mock_list,
|
|
):
|
|
_warn_if_no_real_sink()
|
|
mock_list.assert_not_called()
|
|
|
|
def test_warns_when_no_real_sink(self) -> None:
|
|
"""No real sink → warning is emitted."""
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value="/usr/bin/pactl"),
|
|
patch("wake_alarm._sinks._list_real_sinks", return_value=[]),
|
|
patch("wake_alarm._sinks._logger") as mock_log,
|
|
):
|
|
_warn_if_no_real_sink()
|
|
mock_log.warning.assert_called()
|
|
|
|
def test_info_when_real_sink_present(self) -> None:
|
|
"""A real sink → info log, no warning."""
|
|
with (
|
|
patch("wake_alarm._sinks._pactl_path", return_value="/usr/bin/pactl"),
|
|
patch(
|
|
"wake_alarm._sinks._list_real_sinks",
|
|
return_value=["alsa_output.analog"],
|
|
),
|
|
patch("wake_alarm._sinks._logger") as mock_log,
|
|
):
|
|
_warn_if_no_real_sink()
|
|
mock_log.info.assert_called()
|
|
mock_log.warning.assert_not_called()
|
|
|
|
|
|
class TestParseArgs:
|
|
"""Tests for _parse_args."""
|
|
|
|
def test_default_flags_are_false(self) -> None:
|
|
"""No CLI args means every flag is False."""
|
|
ns = _parse_args([])
|
|
assert ns.demo is False
|
|
assert ns.trigger_now is False
|
|
assert ns.production is False
|
|
|
|
def test_flags_parse(self) -> None:
|
|
"""Each flag flips to True when passed."""
|
|
ns = _parse_args(["--production", "--demo", "--trigger-now"])
|
|
assert ns.production is True
|
|
assert ns.demo is True
|
|
assert ns.trigger_now is True
|