refactor: styles own their ringing tone directly (Pattern C)

Drop the injected AlarmSound Protocol and the wecker.Sound class. Each style
now owns its tone by using pygame directly; the runner owns only the audio
engine lifecycle (mixer init/quit), button sampling, and cleanup. This is the
seam for future styles that handle their own tone — a 'talk' style would just
import pygame and play speech, with no shared interface to extend.

- styles/base.py: AlarmStyle.__init__(set_led, music_file) + start() + update()
- styles/blink.py: start() loads+plays music via pygame.mixer.music
- styles/simple.py: owns its beep — synthesises a square-wave buffer in
  module (stdlib array+math) and plays it via pygame.mixer.Sound
- wecker.py: setup() brings up the mixer only; run_alarm constructs the style
  and guards start() with a clean log+exit on failure

Tests: a shared tests/conftest.py stubs RPi.GPIO/pygame in sys.modules before
any SUT import (order-independent, removes duplicated inline mocking); the
wecker mock_pygame fixture patches one fresh pygame mock into wecker + both
style modules so assertions see the same calls.

README: tone-ownership and plugin-contract updated.
This commit is contained in:
2026-08-02 21:50:00 +02:00
parent 92eba762ce
commit 3a7b6ac7a3
10 changed files with 167 additions and 190 deletions
+12 -13
View File
@@ -1,4 +1,4 @@
from unittest.mock import MagicMock
from unittest.mock import MagicMock, patch
from styles.blink import (
STATE_BLINKING,
@@ -11,20 +11,20 @@ from styles.blink import (
def _make_blink(music_file="music.mp3"):
"""Return (style, sound_mock) for a BlinkStyle ready to start."""
sound = MagicMock()
style = BlinkStyle(lambda on: None, sound, music_file)
return style, sound
"""Return (style, set_led calls) for a BlinkStyle ready to update."""
calls = []
style = BlinkStyle(lambda on: calls.append(on), music_file)
return style, calls
def test_start_plays_music_and_led_off():
calls = []
sound = MagicMock()
style = BlinkStyle(lambda on: calls.append(on), sound, "track.mp3")
style.start()
sound.play_music.assert_called_once_with("track.mp3")
style, calls = _make_blink("track.mp3")
with patch("styles.blink.pygame", MagicMock()) as pg:
style.start()
pg.mixer.music.load.assert_called_with("track.mp3")
pg.mixer.music.set_volume.assert_called_with(1.0)
pg.mixer.music.play.assert_called_with(-1)
assert calls == [False] # LED off while music plays until a press starts the puzzle
assert style.state == 0 # STATE_RINGING until a press
def test_press_starts_puzzle():
@@ -74,8 +74,7 @@ def test_blink_incorrect_retries():
def test_blinking_non_blocking():
calls = []
style, _ = _make_blink()
style, calls = _make_blink()
style.set_led = calls.append
style.state = STATE_BLINKING
style.target_blinks = 2