mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-19 13:34:21 +01:00
Ring via PipeWire when ALSA card is busy
Guard _audit against overwriting reports. Todo: 364208fc Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5937e22131
commit
224015cc2e
@ -231,8 +231,15 @@ PC (`events.jsonl` `event`): `fallback_tick` (only on decision change),
|
||||
root ALSA ring got `Device or resource busy` while PipeWire still held the
|
||||
card seconds after a PipeWire ring — at night the card is idle and opens
|
||||
(a silent root `aplay` passed), but a stream left open overnight would
|
||||
keep it busy. **Open:** what the root ring does about a held card is
|
||||
kuhy's call (killing the holder was refused by the auto-mode classifier).
|
||||
keep it busy. **Decided 2026-11-15:** on the *first* busy open (no retries)
|
||||
`ring_alsa.sh` rings through the user's PipeWire (`runuser`, then
|
||||
`python -m wake_alarm._ring_main`); only if that fails does it `fuser -k
|
||||
-TERM` the card's playback nodes once, retry ALSA once and exit non-zero.
|
||||
Fallback before kill, because the holder is PipeWire itself. The fallback's
|
||||
`ring_backend` event says `FAILED` (`started=false`) when PipeWire cannot
|
||||
play, and the unit's non-zero exit is the loud failure; the user-level
|
||||
fallback ring is the last line. Gate: vmbox `ring-alsa-busy-fallback`
|
||||
(10 repetitions) and `ring-alsa-busy-fails-loudly`.
|
||||
- Emulator (`wake_alarm_api36`): exact A+15 check hidden from the system
|
||||
next-alarm, headless `ring_started` on a heads-up ring, boot-path miss
|
||||
(phone off before the alarm) → lockdown through tomorrow, escape hatch.
|
||||
@ -243,8 +250,11 @@ PC (`events.jsonl` `event`): `fallback_tick` (only on decision change),
|
||||
|
||||
## Evidence for Claude
|
||||
|
||||
`python -m wake_alarm._audit [YYYY-MM-DD]` and the 11:05 timer write
|
||||
`python -m wake_alarm._audit [YYYY-MM-DD] [--stdout | --force]` and the 11:05 timer write
|
||||
`~/data/wake-alarm/incidents/<date>.md` (outside the repo: personal data): a merged
|
||||
phone + PC timeline, then expected-vs-observed checks (alarm known, RTC armed, PC up
|
||||
by `A`, ring/fallback, penalty, lockdown, phone pushed within `PHONE_PUSH_STALE_SECONDS`
|
||||
= 24 h by newest dated HLC; n/a when Firebase is unreachable), mismatches and escapes first.
|
||||
An existing report is never overwritten silently: exit 2 `refusing to overwrite <path>`
|
||||
unless `--force`; `--stdout` (alias `--dry-run`) prints and writes nothing, not even
|
||||
`audit_written`.
|
||||
|
||||
@ -75,12 +75,15 @@ cleanup() {
|
||||
trap cleanup EXIT
|
||||
|
||||
install_ring_audio() {
|
||||
# fuser (psmisc): the ring script's last resort frees a held card with it.
|
||||
command -v fuser >/dev/null 2>&1 || sudo pacman -S --needed --noconfirm psmisc
|
||||
# Generated, never committed: the binary hook forbids WAVs in the repo.
|
||||
/usr/bin/python3 -m wake_alarm._ring_wav --write "$TEMP_DIR/wav" >/dev/null
|
||||
sudo install -D -m 0644 "$TEMP_DIR/wav/ring.wav" "$WAV_DIR/ring.wav"
|
||||
sudo install -D -m 0644 "$TEMP_DIR/wav/ring_loop.wav" "$WAV_DIR/ring_loop.wav"
|
||||
sudo install -D -m 0755 "$PC_DIR/ring_alsa.sh" "$RING_SCRIPT_DST"
|
||||
sudo install -m 0644 "$PC_DIR/$ALSA_UNIT" "/etc/systemd/system/$ALSA_UNIT"
|
||||
sed "s/@USER@/$INSTALL_USER/" "$PC_DIR/$ALSA_UNIT" >"$TEMP_DIR/$ALSA_UNIT"
|
||||
sudo install -m 0644 "$TEMP_DIR/$ALSA_UNIT" "/etc/systemd/system/$ALSA_UNIT"
|
||||
sudo systemctl daemon-reload
|
||||
echo " Ring WAVs, $RING_SCRIPT_DST and $ALSA_UNIT installed."
|
||||
}
|
||||
|
||||
@ -9,6 +9,14 @@
|
||||
# speakers' card has, plays the rising WAV once, then loops the full-volume
|
||||
# one until systemd stops the unit (RuntimeMaxSec is the backstop).
|
||||
#
|
||||
# When the card is held (almost always the user's PipeWire), the FIRST busy
|
||||
# open -- no retries -- hands the ring to PipeWire as the user
|
||||
# (wake_alarm._ring_main, via runuser). Killing the holder first would kill
|
||||
# the PipeWire that fallback needs. Only if that fallback also fails: one
|
||||
# `fuser -k -TERM` on the card's playback nodes, one more ALSA try, then exit
|
||||
# non-zero. Needs WAKE_ALARM_USER (set by the unit; install.sh fills it in)
|
||||
# and psmisc's fuser.
|
||||
#
|
||||
# Usage: ring_alsa.sh <rise.wav> <loop.wav>
|
||||
# ============================================================================
|
||||
|
||||
@ -21,6 +29,10 @@ readonly DEVICE="plughw:CARD=${CARD},DEV=0"
|
||||
# Playback controls that may gate the speakers; only those present are set.
|
||||
# Front is the rear line-out jack on this board.
|
||||
readonly CONTROLS=(Master PCM Speaker Headphone Front)
|
||||
# The user whose PipeWire owns the card, and the interpreter that has the
|
||||
# wake_alarm package (system python, same as the user timers).
|
||||
readonly RING_USER="${WAKE_ALARM_USER:-}"
|
||||
readonly PY="${WAKE_ALARM_PYTHON:-/usr/bin/python3}"
|
||||
# A failed aplay (device briefly held elsewhere) must not spin the CPU.
|
||||
readonly RETRY_SECONDS=1
|
||||
|
||||
@ -41,8 +53,59 @@ unmute_all() {
|
||||
done
|
||||
}
|
||||
|
||||
# aplay's stderr says why it failed; only "busy" triggers the fallback.
|
||||
play() {
|
||||
aplay -q -D "$DEVICE" "$1" || sleep "$RETRY_SECONDS"
|
||||
local err
|
||||
err="$(mktemp)"
|
||||
if aplay -q -D "$DEVICE" "$1" 2>"$err"; then
|
||||
rm -f "$err"
|
||||
return 0
|
||||
fi
|
||||
if grep -qi 'busy' "$err"; then
|
||||
rm -f "$err"
|
||||
return 3
|
||||
fi
|
||||
cat "$err" >&2
|
||||
rm -f "$err"
|
||||
sleep "$RETRY_SECONDS"
|
||||
}
|
||||
|
||||
# Ring through the user's PipeWire until systemd's SIGTERM; non-zero if it
|
||||
# cannot play (the fallback itself reports ring_backend FAILED).
|
||||
user_fallback() {
|
||||
[[ -n "$RING_USER" ]] || return 1
|
||||
local uid home
|
||||
uid="$(id -u "$RING_USER")"
|
||||
home="$(getent passwd "$RING_USER" | cut -d: -f6)"
|
||||
echo "fallback-started: card busy, ringing through PipeWire as $RING_USER"
|
||||
runuser -u "$RING_USER" -- env HOME="$home" PATH="$PATH" \
|
||||
XDG_RUNTIME_DIR="/run/user/$uid" \
|
||||
"$PY" -m wake_alarm._ring_main "$1" "$2"
|
||||
}
|
||||
|
||||
# Last resort: free the card from whatever holds it, once.
|
||||
kill_holder() {
|
||||
local node
|
||||
node="$(readlink "/proc/asound/$CARD")" || return 0
|
||||
echo "kill-holder: fuser -k -TERM on ${node}"
|
||||
# shellcheck disable=SC2046 # one argument per playback node, by design
|
||||
fuser -k -TERM $(compgen -G "/dev/snd/pcmC${node#card}D*p") 2>&1 || true
|
||||
sleep "$RETRY_SECONDS"
|
||||
}
|
||||
|
||||
# The card was busy on its first open: PipeWire first, then kill, then fail.
|
||||
# Returns only when the holder was killed and ALSA works again.
|
||||
handle_busy() {
|
||||
local rise="$1" loop="$2"
|
||||
if user_fallback "$rise" "$loop"; then
|
||||
exit 0
|
||||
fi
|
||||
echo "fallback-failed: killing the holder, one more ALSA try" >&2
|
||||
kill_holder
|
||||
aplay -q -D "$DEVICE" "$rise" || {
|
||||
echo "Error: card $CARD still unusable" >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
main() {
|
||||
@ -53,9 +116,11 @@ main() {
|
||||
exit 1
|
||||
}
|
||||
unmute_all
|
||||
play "$rise"
|
||||
local rc=0
|
||||
play "$rise" || rc=$?
|
||||
[[ $rc -ne 3 ]] || handle_busy "$rise" "$loop"
|
||||
while true; do
|
||||
play "$loop"
|
||||
play "$loop" || sleep "$RETRY_SECONDS"
|
||||
done
|
||||
}
|
||||
|
||||
|
||||
@ -8,6 +8,9 @@ Documentation=https://github.com/kuhyx/wake-alarm
|
||||
# graphical session owns the sound: the night lockdown masks lightdm, and
|
||||
# the user is not in `audio`, so only root can reach the card.
|
||||
Type=simple
|
||||
# install.sh replaces @USER@: whose PipeWire the script falls back to when
|
||||
# the card is busy.
|
||||
Environment=WAKE_ALARM_USER=@USER@
|
||||
ExecStart=/usr/local/lib/wake-alarm/ring_alsa.sh /usr/local/share/wake-alarm/ring.wav /usr/local/share/wake-alarm/ring_loop.wav
|
||||
# Backstop for a fallback tick that died without stopping this unit: never
|
||||
# ring longer than the 30-min cap plus a minute.
|
||||
|
||||
@ -57,6 +57,86 @@ case_ring_script_plays() {
|
||||
fi
|
||||
}
|
||||
|
||||
# --- card held busy (PipeWire holds it on the real PC) ----------------------
|
||||
readonly BUSY_REPS=10
|
||||
readonly BUSY_DIR=/tmp/ring-busy
|
||||
readonly EVENTS="$HOME/.local/state/wake_alarm/events.jsonl"
|
||||
|
||||
# Stub wpctl/pw-play: the guest has no user PipeWire. $1 = "ok" or "broken".
|
||||
busy_stubs() {
|
||||
mkdir -p "$BUSY_DIR/bin"
|
||||
printf '#!/bin/sh\nexit 0\n' >"$BUSY_DIR/bin/wpctl"
|
||||
if [[ "$1" == ok ]]; then
|
||||
printf '#!/bin/sh\nexec sleep 30\n' >"$BUSY_DIR/bin/pw-play"
|
||||
else
|
||||
printf '#!/bin/sh\nexit 1\n' >"$BUSY_DIR/bin/pw-play"
|
||||
fi
|
||||
chmod +x "$BUSY_DIR/bin/"*
|
||||
}
|
||||
|
||||
# Hold the Dummy card's only playback substream, ignoring TERM.
|
||||
busy_hold() {
|
||||
sudo modprobe -r snd-dummy >/dev/null 2>&1 || true
|
||||
sudo modprobe snd-dummy pcm_substreams=1
|
||||
setsid bash -c 'trap "" TERM; exec aplay -q -D plughw:CARD=Dummy,DEV=0 /dev/zero -f S16_LE -r 8000 -c 1' \
|
||||
>/dev/null 2>&1 &
|
||||
sleep 1
|
||||
}
|
||||
|
||||
busy_release() {
|
||||
sudo pkill -KILL -x aplay >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
# A ring_backend event in the user's log carrying $1 (started true/false).
|
||||
busy_event() {
|
||||
grep '"event": "ring_backend"' "$EVENTS" 2>/dev/null | grep -q "$1"
|
||||
}
|
||||
|
||||
# Run the ring script against the held card; $1 = seconds to let it run.
|
||||
busy_run() {
|
||||
sudo WAKE_ALARM_CARD=Dummy WAKE_ALARM_USER="$USER" PATH="$BUSY_DIR/bin:$PATH" \
|
||||
timeout "$1" "$RING_SCRIPT" "$RING_WAV_DIR/ring.wav" "$RING_WAV_DIR/ring_loop.wav" 2>&1
|
||||
}
|
||||
|
||||
# The first busy open hands the ring to PipeWire, N times over, with the
|
||||
# holder alive and ignoring TERM (so a kill-first design would fail here).
|
||||
case_ring_busy_fallback() {
|
||||
local name="ring-alsa-busy-fallback" i ok=0 out
|
||||
busy_stubs ok
|
||||
busy_hold
|
||||
for ((i = 1; i <= BUSY_REPS; i++)); do
|
||||
: >"$EVENTS" 2>/dev/null || true
|
||||
out="$(busy_run 4)" || true
|
||||
if grep -q '^fallback-started' <<<"$out" &&
|
||||
! grep -q 'kill-holder' <<<"$out" &&
|
||||
busy_event '"started": true'; then
|
||||
ok=$((ok + 1))
|
||||
fi
|
||||
done
|
||||
busy_release
|
||||
if [[ $ok -eq $BUSY_REPS ]]; then
|
||||
pass "$name"
|
||||
else
|
||||
fail "$name" "$ok of $BUSY_REPS repetitions fell back on the first busy open"
|
||||
fi
|
||||
}
|
||||
|
||||
# Holder present AND fallback broken: never a silent success.
|
||||
case_ring_busy_fails_loudly() {
|
||||
local name="ring-alsa-busy-fails-loudly" out rc=0
|
||||
busy_stubs broken
|
||||
busy_hold
|
||||
: >"$EVENTS" 2>/dev/null || true
|
||||
out="$(busy_run 15)" || rc=$?
|
||||
busy_release
|
||||
if [[ $rc -ne 0 && $rc -ne 124 ]] && grep -q 'kill-holder' <<<"$out" &&
|
||||
busy_event '"started": false'; then
|
||||
pass "$name"
|
||||
else
|
||||
fail "$name" "rc=$rc, expected non-zero exit, kill-holder and a FAILED event"
|
||||
fi
|
||||
}
|
||||
|
||||
case_sudoers() {
|
||||
local name="sudoers-merged"
|
||||
if ! sudo visudo -cf "$SUDOERS" >/dev/null 2>&1; then
|
||||
@ -123,6 +203,8 @@ run_v2_cases() {
|
||||
case_v2_timers
|
||||
case_ring_unit_installed
|
||||
case_ring_script_plays
|
||||
case_ring_busy_fallback
|
||||
case_ring_busy_fails_loudly
|
||||
case_sudoers
|
||||
case_powerkey_dropin
|
||||
case_rtc_arm
|
||||
|
||||
@ -34,7 +34,7 @@ readonly SCRIPT_NAME
|
||||
# dies with "libtk8.6.so: cannot open shared object file" without it. Measured
|
||||
# in the guest, not guessed -- dropping this package is what broke the harness
|
||||
# when the alarm window was deleted.
|
||||
readonly GUEST_PACKAGES="tk alsa-utils"
|
||||
readonly GUEST_PACKAGES="tk alsa-utils psmisc"
|
||||
|
||||
# Printed by guest_cases.sh only when every case passed. See run_cases().
|
||||
readonly GUEST_OK_SENTINEL="ALL-CASES-PASSED"
|
||||
|
||||
@ -2,13 +2,15 @@
|
||||
|
||||
``wake-alarm-audit.timer`` runs it at 11:05; by hand::
|
||||
|
||||
python -m wake_alarm._audit [YYYY-MM-DD] [--dry-run]
|
||||
python -m wake_alarm._audit [YYYY-MM-DD] [--stdout | --force]
|
||||
|
||||
It merges the phone's ``phone_events`` with the PC's named ``events.jsonl``
|
||||
lines, boots and resumes into one timeline, runs the expected-vs-observed
|
||||
checks (``_audit_checks``) and writes ``INCIDENTS_DIR/<date>.md`` with every
|
||||
escape and mismatch first, under ``## Flags``. Read-only everywhere except
|
||||
that one file (and ``audit_written``); ``--dry-run`` prints without writing.
|
||||
that one file (and ``audit_written``). An existing report is never
|
||||
overwritten silently: exit 2 unless ``--force``; ``--stdout`` (alias
|
||||
``--dry-run``) prints and writes nothing.
|
||||
Outside the repo on purpose: the report holds personal data.
|
||||
"""
|
||||
|
||||
@ -166,17 +168,30 @@ def write_report(day: date, text: str) -> str:
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Entry point; exit 1 when the report could not be written."""
|
||||
"""Entry point; exit 1 if unwritable, 2 if a report exists and no flag."""
|
||||
parser = argparse.ArgumentParser(description="Audit one wake-up")
|
||||
parser.add_argument("day", nargs="?", type=date.fromisoformat, default=None)
|
||||
parser.add_argument("--dry-run", action="store_true", help="print, write nothing")
|
||||
parser.add_argument(
|
||||
"--stdout",
|
||||
"--dry-run",
|
||||
dest="stdout",
|
||||
action="store_true",
|
||||
help="print, write nothing",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force", action="store_true", help="overwrite an existing report"
|
||||
)
|
||||
args = parser.parse_args(sys.argv[1:] if argv is None else argv)
|
||||
day = args.day or datetime.now().astimezone().date()
|
||||
existing = INCIDENTS_DIR / f"{day.isoformat()}.md"
|
||||
if existing.exists() and not (args.stdout or args.force):
|
||||
sys.stderr.write(f"refusing to overwrite {existing}; use --stdout or --force\n")
|
||||
return 2
|
||||
evidence, reachable = gather(day)
|
||||
checks = run_checks(evidence)
|
||||
text = render(evidence, checks, reachable=reachable)
|
||||
sys.stdout.write(text)
|
||||
if args.dry_run:
|
||||
if args.stdout:
|
||||
return 0
|
||||
configure_logging(component="audit")
|
||||
try:
|
||||
|
||||
57
wake_alarm/_ring_main.py
Normal file
57
wake_alarm/_ring_main.py
Normal file
@ -0,0 +1,57 @@
|
||||
"""The user-side ring the root ALSA script falls back to.
|
||||
|
||||
``scripts/pc/ring_alsa.sh`` runs ``python -m wake_alarm._ring_main <rise>
|
||||
<loop>`` as the user (``runuser``) the first time the speakers' card is busy:
|
||||
PipeWire holds it, so the ring goes *through* PipeWire instead of fighting
|
||||
it. Plays until SIGTERM (exit 0); exits 1 with ``ring_backend ... FAILED``
|
||||
when PipeWire cannot play, which tells the script to try killing the holder.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
|
||||
from wake_alarm._events import emit
|
||||
from wake_alarm._logging_setup import configure_logging
|
||||
from wake_alarm._ring_player import PipeWireBackend
|
||||
|
||||
_PUMP_SECONDS = 1.0
|
||||
_ARGS = 2 # rise.wav, loop.wav
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""Ring through PipeWire until SIGTERM; 1 when it cannot, 2 on bad usage."""
|
||||
args = sys.argv[1:] if argv is None else argv
|
||||
if len(args) != _ARGS:
|
||||
sys.stderr.write("Usage: _ring_main <rise.wav> <loop.wav>\n")
|
||||
return 2
|
||||
configure_logging(component="ring")
|
||||
backend = PipeWireBackend(Path(args[0]), Path(args[1]))
|
||||
started, detail = backend.start()
|
||||
emit(
|
||||
"ring_backend",
|
||||
f"pipewire for root unit ({'started' if started else 'FAILED'})",
|
||||
backend=backend.name,
|
||||
why="root unit found the card busy",
|
||||
started=started,
|
||||
detail=detail,
|
||||
)
|
||||
if not started:
|
||||
return 1
|
||||
stopping: list[bool] = []
|
||||
signal.signal(signal.SIGTERM, lambda *_: stopping.append(True))
|
||||
try:
|
||||
while not stopping:
|
||||
if not backend.pump():
|
||||
return 1
|
||||
time.sleep(_PUMP_SECONDS)
|
||||
finally:
|
||||
backend.stop()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@ -18,6 +18,7 @@ from wake_alarm._sync import Alarm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
from dataclasses import replace
|
||||
|
||||
DAY = date(2026, 10, 1)
|
||||
@ -151,6 +152,35 @@ class TestCli:
|
||||
assert main(["2026-10-01"]) == 1
|
||||
assert "could not write" in capsys.readouterr().err
|
||||
|
||||
def _existing(self) -> Path:
|
||||
_audit.INCIDENTS_DIR.mkdir(parents=True)
|
||||
path = _audit.INCIDENTS_DIR / "2026-10-01.md"
|
||||
path.write_text("keep me")
|
||||
return path
|
||||
|
||||
def test_refuses_to_overwrite(self, capsys: pytest.CaptureFixture[str]) -> None:
|
||||
path = self._existing()
|
||||
assert main(["2026-10-01"]) == 2
|
||||
err = capsys.readouterr().err
|
||||
assert f"refusing to overwrite {path}; use --stdout or --force" in err
|
||||
assert path.read_text() == "keep me"
|
||||
|
||||
def test_stdout_prints_and_writes_nothing(
|
||||
self, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
path = self._existing()
|
||||
with patch.object(_audit, "emit") as emitted:
|
||||
assert main(["2026-10-01", "--stdout"]) == 0
|
||||
assert "# Wake audit 2026-10-01" in capsys.readouterr().out
|
||||
assert path.read_text() == "keep me"
|
||||
emitted.assert_not_called()
|
||||
|
||||
def test_force_overwrites(self) -> None:
|
||||
path = self._existing()
|
||||
with patch.object(_audit, "configure_logging"):
|
||||
assert main(["2026-10-01", "--force"]) == 0
|
||||
assert path.read_text().startswith("# Wake audit 2026-10-01")
|
||||
|
||||
|
||||
def test_timeline_skips_an_unparsable_phone_stamp() -> None:
|
||||
evidence, _ = gather(DAY)
|
||||
|
||||
91
wake_alarm/tests/test_ring_main.py
Normal file
91
wake_alarm/tests/test_ring_main.py
Normal file
@ -0,0 +1,91 @@
|
||||
"""The user-side ring entry the root ALSA script falls back to."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import signal
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from wake_alarm import _ring_main
|
||||
from wake_alarm._ring_main import main
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import pytest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
WAVS = ["rise.wav", "loop.wav"]
|
||||
|
||||
|
||||
def _backend(*, start: tuple[bool, str] = (True, "ok"), pumps: list[bool]) -> MagicMock:
|
||||
backend = MagicMock()
|
||||
backend.name = "pipewire"
|
||||
backend.start.return_value = start
|
||||
backend.pump.side_effect = pumps
|
||||
return backend
|
||||
|
||||
|
||||
def _run(backend: MagicMock, argv: list[str] | None = None) -> tuple[int, MagicMock]:
|
||||
with (
|
||||
patch.object(_ring_main, "PipeWireBackend", return_value=backend),
|
||||
patch.object(_ring_main, "configure_logging"),
|
||||
patch.object(_ring_main, "emit") as emitted,
|
||||
patch.object(_ring_main.time, "sleep"),
|
||||
):
|
||||
return main(WAVS if argv is None else argv), emitted
|
||||
|
||||
|
||||
def test_start_failure_emits_failed_and_exits_1() -> None:
|
||||
backend = _backend(start=(False, "no pw"), pumps=[])
|
||||
code, emitted = _run(backend)
|
||||
assert code == 1
|
||||
assert "FAILED" in emitted.call_args.args[1]
|
||||
backend.stop.assert_not_called()
|
||||
|
||||
|
||||
def test_pump_failure_exits_1_and_stops() -> None:
|
||||
backend = _backend(pumps=[True, False])
|
||||
code, emitted = _run(backend)
|
||||
assert code == 1
|
||||
assert "started" in emitted.call_args_list[0].args[1]
|
||||
backend.stop.assert_called_once()
|
||||
|
||||
|
||||
def test_sigterm_ends_the_ring_cleanly() -> None:
|
||||
backend = _backend(pumps=[True, True])
|
||||
handler: list[Callable[..., object]] = []
|
||||
|
||||
def capture(sig: int, fn: Callable[..., object]) -> None:
|
||||
assert sig == signal.SIGTERM
|
||||
handler.append(fn)
|
||||
|
||||
def stop_after_first(_: float) -> None:
|
||||
handler[0](signal.SIGTERM, None)
|
||||
|
||||
with (
|
||||
patch.object(_ring_main.signal, "signal", capture),
|
||||
patch.object(_ring_main, "PipeWireBackend", return_value=backend),
|
||||
patch.object(_ring_main, "configure_logging"),
|
||||
patch.object(_ring_main, "emit"),
|
||||
patch.object(_ring_main.time, "sleep", stop_after_first),
|
||||
):
|
||||
assert main(WAVS) == 0
|
||||
backend.stop.assert_called_once()
|
||||
|
||||
|
||||
def test_wrong_usage_exits_2(capsys: pytest.CaptureFixture[str]) -> None:
|
||||
assert main(["only-one"]) == 2
|
||||
assert "Usage" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_paths_reach_the_backend() -> None:
|
||||
backend = _backend(pumps=[False])
|
||||
with (
|
||||
patch.object(_ring_main, "PipeWireBackend", return_value=backend) as cls,
|
||||
patch.object(_ring_main, "configure_logging"),
|
||||
patch.object(_ring_main, "emit"),
|
||||
):
|
||||
main(WAVS)
|
||||
cls.assert_called_once_with(Path("rise.wav"), Path("loop.wav"))
|
||||
Loading…
Reference in New Issue
Block a user