testsAndMisc/python_pkg/wake_alarm/tests/test_alarm.py
Krzysztof kuhy Rudnicki 0c1e395008 Split modules, fix tests, fix pre-commit batching
- steam_backlog_enforcer: extract _hltb_search.py and _scanning_confidence.py;
  split oversized test files into *_part2/3/4.py
- screen_locker: extract _early_bird.py and _window_setup.py from screen_lock.py;
  fix patch targets in tests (screen_lock.* -> _window_setup.*)
- wake_alarm: use shutil.which('xset') to avoid S607; add TestDisplayHelpers tests
- linux_configuration/usage_report: split into _parsing.py and _types.py;
  add bin/__init__.py (INP001); fix RUF002 (× -> x)
- pre-commit: add require_serial: true to pytest-coverage hook to prevent
  file batching across 24 CPU cores (was causing 12 parallel partial-coverage runs)
2026-05-22 22:48:28 +02:00

375 lines
12 KiB
Python

"""Tests for _alarm.py — wake alarm daemon, UI, and beep logic."""
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 python_pkg.wake_alarm._alarm import (
_beep_loud,
_beep_medium,
_beep_soft,
_generate_code,
_is_alarm_day,
_restore_display,
_should_run_alarm,
_speaker_test_path,
_wake_display,
)
from python_pkg.wake_alarm._constants import (
DISMISS_CODE_LENGTH,
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
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("python_pkg.wake_alarm._alarm.tk", mock):
yield mock
@pytest.fixture
def mock_tk_module() -> Generator[MagicMock]:
"""Provide explicit access to the mocked tk module."""
mock = _make_mock_tk()
with patch("python_pkg.wake_alarm._alarm.tk", mock):
yield mock
# ---------------------------------------------------------------------------
# Unit tests for pure functions
# ---------------------------------------------------------------------------
class TestGenerateCode:
"""Tests for _generate_code."""
def test_correct_length(self) -> None:
"""Generated code has the configured length."""
code = _generate_code()
assert len(code) == DISMISS_CODE_LENGTH
def test_all_digits(self) -> None:
"""Generated code contains only digits."""
code = _generate_code()
assert code.isdigit()
def test_different_codes(self) -> None:
"""Two calls produce different codes (probabilistic, but safe)."""
codes = {_generate_code() for _ in range(50)}
assert len(codes) > 1
class TestIsAlarmDay:
"""Tests for _is_alarm_day."""
def test_monday_is_alarm_day(self) -> None:
"""Monday (weekday=0) is an alarm day."""
from datetime import datetime
# Create a date that is Monday
with patch(
"python_pkg.wake_alarm._alarm.datetime",
) as mock_dt:
mock_now = MagicMock()
mock_now.weekday.return_value = 0 # Monday
mock_dt.now.return_value = mock_now
mock_dt.side_effect = datetime
assert _is_alarm_day() is True
def test_tuesday_is_not_alarm_day(self) -> None:
"""Tuesday (weekday=1) is NOT an alarm day."""
with patch(
"python_pkg.wake_alarm._alarm.datetime",
) as mock_dt:
mock_now = MagicMock()
mock_now.weekday.return_value = 1 # Tuesday
mock_dt.now.return_value = mock_now
assert _is_alarm_day() is False
def test_friday_is_alarm_day(self) -> None:
"""Friday (weekday=4) is an alarm day."""
with patch(
"python_pkg.wake_alarm._alarm.datetime",
) as mock_dt:
mock_now = MagicMock()
mock_now.weekday.return_value = 4 # Friday
mock_dt.now.return_value = mock_now
assert _is_alarm_day() is True
def test_saturday_is_alarm_day(self) -> None:
"""Saturday (weekday=5) is an alarm day."""
with patch(
"python_pkg.wake_alarm._alarm.datetime",
) as mock_dt:
mock_now = MagicMock()
mock_now.weekday.return_value = 5
mock_dt.now.return_value = mock_now
assert _is_alarm_day() is True
def test_sunday_is_alarm_day(self) -> None:
"""Sunday (weekday=6) is an alarm day."""
with patch(
"python_pkg.wake_alarm._alarm.datetime",
) as mock_dt:
mock_now = MagicMock()
mock_now.weekday.return_value = 6
mock_dt.now.return_value = mock_now
assert _is_alarm_day() is True
def test_wednesday_is_not_alarm_day(self) -> None:
"""Wednesday (weekday=2) is NOT an alarm day."""
with patch(
"python_pkg.wake_alarm._alarm.datetime",
) as mock_dt:
mock_now = MagicMock()
mock_now.weekday.return_value = 2
mock_dt.now.return_value = mock_now
assert _is_alarm_day() is False
class TestSpeakerTestPath:
"""Tests for _speaker_test_path."""
def test_returns_path_when_found(self) -> None:
"""Return full path when speaker-test is available."""
with patch(
"python_pkg.wake_alarm._alarm.shutil.which",
return_value="/usr/bin/speaker-test",
):
assert _speaker_test_path() == "/usr/bin/speaker-test"
def test_raises_when_not_found(self) -> None:
"""Raise FileNotFoundError when speaker-test is missing."""
with (
patch(
"python_pkg.wake_alarm._alarm.shutil.which",
return_value=None,
),
pytest.raises(FileNotFoundError, match="speaker-test not found"),
):
_speaker_test_path()
class TestBeepFunctions:
"""Tests for beep helper functions."""
def test_beep_soft_writes_bell(self) -> None:
"""_beep_soft writes terminal bell character."""
with patch("python_pkg.wake_alarm._alarm.sys") as mock_sys:
mock_sys.stdout = MagicMock()
_beep_soft()
mock_sys.stdout.write.assert_called_once_with("\a")
mock_sys.stdout.flush.assert_called_once()
def test_beep_medium_calls_speaker_test(self) -> None:
"""_beep_medium runs speaker-test subprocess."""
with (
patch(
"python_pkg.wake_alarm._alarm._speaker_test_path",
return_value="/usr/bin/speaker-test",
),
patch(
"python_pkg.wake_alarm._alarm.subprocess.run",
) as mock_run,
):
_beep_medium(frequency=800)
mock_run.assert_called_once()
args = mock_run.call_args[0][0]
assert "/usr/bin/speaker-test" in args
assert "800" in args
def test_beep_medium_falls_back_on_error(self) -> None:
"""_beep_medium falls back to soft beep on OSError."""
with (
patch(
"python_pkg.wake_alarm._alarm._speaker_test_path",
return_value="/usr/bin/speaker-test",
),
patch(
"python_pkg.wake_alarm._alarm.subprocess.run",
side_effect=OSError("no speaker-test"),
),
patch(
"python_pkg.wake_alarm._alarm._beep_soft",
) as mock_soft,
):
_beep_medium()
mock_soft.assert_called_once()
def test_beep_medium_falls_back_on_timeout(self) -> None:
"""_beep_medium falls back on TimeoutExpired."""
from subprocess import TimeoutExpired
with (
patch(
"python_pkg.wake_alarm._alarm._speaker_test_path",
return_value="/usr/bin/speaker-test",
),
patch(
"python_pkg.wake_alarm._alarm.subprocess.run",
side_effect=TimeoutExpired("cmd", 3),
),
patch(
"python_pkg.wake_alarm._alarm._beep_soft",
) as mock_soft,
):
_beep_medium()
mock_soft.assert_called_once()
def test_beep_medium_falls_back_on_missing_binary(self) -> None:
"""_beep_medium falls back when speaker-test binary not found."""
with (
patch(
"python_pkg.wake_alarm._alarm._speaker_test_path",
side_effect=FileNotFoundError("not found"),
),
patch(
"python_pkg.wake_alarm._alarm._beep_soft",
) as mock_soft,
):
_beep_medium()
mock_soft.assert_called_once()
def test_beep_loud_calls_speaker_test(self) -> None:
"""_beep_loud runs speaker-test subprocess."""
with (
patch(
"python_pkg.wake_alarm._alarm._speaker_test_path",
return_value="/usr/bin/speaker-test",
),
patch(
"python_pkg.wake_alarm._alarm.subprocess.run",
) as mock_run,
):
_beep_loud(frequency=1200)
mock_run.assert_called_once()
args = mock_run.call_args[0][0]
assert "1200" in args
def test_beep_loud_falls_back_on_error(self) -> None:
"""_beep_loud falls back to soft beep on OSError."""
with (
patch(
"python_pkg.wake_alarm._alarm._speaker_test_path",
return_value="/usr/bin/speaker-test",
),
patch(
"python_pkg.wake_alarm._alarm.subprocess.run",
side_effect=OSError("fail"),
),
patch(
"python_pkg.wake_alarm._alarm._beep_soft",
) as mock_soft,
):
_beep_loud()
mock_soft.assert_called_once()
def test_beep_loud_falls_back_on_missing_binary(self) -> None:
"""_beep_loud falls back when speaker-test binary not found."""
with (
patch(
"python_pkg.wake_alarm._alarm._speaker_test_path",
side_effect=FileNotFoundError("not found"),
),
patch(
"python_pkg.wake_alarm._alarm._beep_soft",
) as mock_soft,
):
_beep_loud()
mock_soft.assert_called_once()
class TestShouldRunAlarm:
"""Tests for _should_run_alarm."""
def test_returns_false_on_non_alarm_day(self) -> None:
"""Return False when today is not an alarm day."""
with patch(
"python_pkg.wake_alarm._alarm._is_alarm_day",
return_value=False,
):
assert _should_run_alarm() is False
def test_returns_false_when_already_dismissed(self) -> None:
"""Return False when alarm was already dismissed today."""
with (
patch(
"python_pkg.wake_alarm._alarm._is_alarm_day",
return_value=True,
),
patch(
"python_pkg.wake_alarm._alarm.was_alarm_dismissed_today",
return_value=True,
),
):
assert _should_run_alarm() is False
def test_returns_true_when_alarm_day_and_not_dismissed(self) -> None:
"""Return True when today is alarm day and not yet dismissed."""
with (
patch(
"python_pkg.wake_alarm._alarm._is_alarm_day",
return_value=True,
),
patch(
"python_pkg.wake_alarm._alarm.was_alarm_dismissed_today",
return_value=False,
),
):
assert _should_run_alarm() is True
class TestDisplayHelpers:
"""Tests for _wake_display and _restore_display when xset is absent."""
def test_wake_display_skips_when_xset_missing(self) -> None:
"""_wake_display does nothing when xset is not on PATH."""
with (
patch(
"python_pkg.wake_alarm._alarm.shutil.which",
return_value=None,
),
patch("python_pkg.wake_alarm._alarm.subprocess.run") as mock_run,
):
_wake_display()
mock_run.assert_not_called()
def test_restore_display_skips_when_xset_missing(self) -> None:
"""_restore_display does nothing when xset is not on PATH."""
with (
patch(
"python_pkg.wake_alarm._alarm.shutil.which",
return_value=None,
),
patch("python_pkg.wake_alarm._alarm.subprocess.run") as mock_run,
):
_restore_display()
mock_run.assert_not_called()