Split 10 more test modules under the 250-line cap
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
release-apk / release (APK) (push) Waiting to run

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-08-15 19:22:00 +02:00
parent 4bdd180cb1
commit 5c27769642
21 changed files with 1308 additions and 1077 deletions

View File

@ -19,8 +19,8 @@ churn, not size alone — refactoring pays where code is read and changed often
<!-- BEGIN GENERATED VIOLATIONS -->
- **71 files** currently exceed 250 lines.
- **9,431 lines** over the cap in total (the work left to do); longest file is **897** lines.
- **61 files** currently exceed 250 lines.
- **9,084 lines** over the cap in total (the work left to do); longest file is **897** lines.
ROI = lines x commits in the last year. Work top-down; a long file nobody edits
has near-zero payoff and should not be first.
@ -39,11 +39,11 @@ has near-zero payoff and should not be first.
| 380 | 13 | code | `screen_locker/_phone_verification.py` |
| 759 | 5 | code | `stronglift_replacement/workout_app/test/services/storage_service_test.dart` |
| 415 | 9 | code | `stronglift_replacement/workout_app/lib/services/workout_sync_service.dart` |
| 256 | 13 | code | `screen_locker/tests/test_adb_and_phone.py` |
| 357 | 9 | code | `screen_locker/_manual_workout_dialog.py` |
| 384 | 8 | code | `screen_locker/_shutdown.py` |
| 383 | 8 | code | `stronglift_replacement/workout_app/lib/screens/home_screen.dart` |
_(56 further files over 250 lines not listed — re-run `python3 scripts/refresh_refactor_todo.py` for the current set.)_
_(46 further files over 250 lines not listed — re-run `python3 scripts/refresh_refactor_todo.py` for the current set.)_
<!-- END GENERATED VIOLATIONS -->

View File

@ -7,7 +7,6 @@ import json
from typing import TYPE_CHECKING
from unittest.mock import patch
from screen_locker import _compliance_state
from screen_locker._compliance_state import (
has_logged_today,
is_early_bird_pending,
@ -223,51 +222,3 @@ class TestIsSickDayToday:
"""The `today` argument overrides the real date."""
history = SickHistory(sick_days=["2020-05-05"])
assert is_sick_day_today(history, today="2020-05-05") is True
class TestEarlyBirdWindowOpen:
"""The early-bird window's start/end boundaries, including the extension."""
"""Direct tests for the module-private, deliberately independent reimplementation."""
def test_before_window(self) -> None:
"""Before the start hour the window is shut."""
assert (
_compliance_state._early_bird_window_open(extended=False, local_minutes=299)
is False
)
def test_at_start(self) -> None:
"""The start minute itself is inside the window."""
assert (
_compliance_state._early_bird_window_open(extended=False, local_minutes=300)
is True
)
def test_before_end(self) -> None:
"""A minute before the end is still inside the window."""
assert (
_compliance_state._early_bird_window_open(extended=False, local_minutes=509)
is True
)
def test_at_end_exclusive(self) -> None:
"""The end minute is exclusive: the window is already shut."""
assert (
_compliance_state._early_bird_window_open(extended=False, local_minutes=510)
is False
)
def test_extended_before_end(self) -> None:
"""With the extension earned, the window runs later."""
assert (
_compliance_state._early_bird_window_open(extended=True, local_minutes=539)
is True
)
def test_extended_at_end_exclusive(self) -> None:
"""The extended end is exclusive too."""
assert (
_compliance_state._early_bird_window_open(extended=True, local_minutes=540)
is False
)

View File

@ -0,0 +1,53 @@
"""Tests for the pure, read-only predicates in _compliance_state.py."""
from __future__ import annotations
from screen_locker import _compliance_state
class TestEarlyBirdWindowOpen:
"""The early-bird window's start/end boundaries, including the extension."""
"""Direct tests for the module-private, deliberately independent reimplementation."""
def test_before_window(self) -> None:
"""Before the start hour the window is shut."""
assert (
_compliance_state._early_bird_window_open(extended=False, local_minutes=299)
is False
)
def test_at_start(self) -> None:
"""The start minute itself is inside the window."""
assert (
_compliance_state._early_bird_window_open(extended=False, local_minutes=300)
is True
)
def test_before_end(self) -> None:
"""A minute before the end is still inside the window."""
assert (
_compliance_state._early_bird_window_open(extended=False, local_minutes=509)
is True
)
def test_at_end_exclusive(self) -> None:
"""The end minute is exclusive: the window is already shut."""
assert (
_compliance_state._early_bird_window_open(extended=False, local_minutes=510)
is False
)
def test_extended_before_end(self) -> None:
"""With the extension earned, the window runs later."""
assert (
_compliance_state._early_bird_window_open(extended=True, local_minutes=539)
is True
)
def test_extended_at_end_exclusive(self) -> None:
"""The extended end is exclusive too."""
assert (
_compliance_state._early_bird_window_open(extended=True, local_minutes=540)
is False
)

View File

@ -2,9 +2,7 @@
from __future__ import annotations
from datetime import datetime, timezone
import json
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker.tests.conftest import (
@ -147,185 +145,3 @@ class TestIsEarlyBirdTime:
"""Midnight (0 min) is outside the window."""
locker = self._locker(mock_tk, tmp_path, 0)
assert locker._is_early_bird_time() is False
class TestIsEarlyBirdPending:
"""Tests for _is_early_bird_pending method.
early_bird is a same-day pending marker stored in its own HMAC-signed
file (EARLY_BIRD_PENDING_FILE), not in workout_log.json — see
_early_bird.py's module docstring for why.
"""
def test_no_pending_file(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when the pending file does not exist."""
locker = create_locker(mock_tk, tmp_path)
assert locker._is_early_bird_pending() is False
def test_invalid_json(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when the pending file contains invalid JSON."""
locker = create_locker(mock_tk, tmp_path)
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text("{bad json}")
with patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file):
assert locker._is_early_bird_pending() is False
def test_os_error_on_open(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when opening the pending file raises OSError."""
locker = create_locker(mock_tk, tmp_path)
mock_file = MagicMock()
mock_file.exists.return_value = True
mock_file.open.side_effect = OSError("permission denied")
with patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", mock_file):
assert locker._is_early_bird_pending() is False
def test_stale_date(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when the marker is from a previous day."""
locker = create_locker(mock_tk, tmp_path)
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": "2000-01-01", "hmac": "sig"}))
with patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file):
assert locker._is_early_bird_pending() is False
def test_hmac_invalid(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when HMAC verification fails."""
locker = create_locker(mock_tk, tmp_path)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": today, "hmac": "bad"}))
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
patch(
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
),
patch(
"screen_locker._compliance_state.compute_entry_hmac", return_value="sig"
),
):
assert locker._is_early_bird_pending() is False
def test_today_valid_marker(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return True when today's marker is present and HMAC-valid."""
locker = create_locker(mock_tk, tmp_path)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": today, "hmac": "sig"}))
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
patch(
"screen_locker._compliance_state.verify_entry_hmac", return_value=True
),
):
assert locker._is_early_bird_pending() is True
def test_unsigned_accepted_when_key_unavailable(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Unsigned marker is accepted when no HMAC key is configured."""
locker = create_locker(mock_tk, tmp_path)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": today}))
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
patch(
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
),
patch(
"screen_locker._compliance_state.compute_entry_hmac", return_value=None
),
):
assert locker._is_early_bird_pending() is True
class TestSaveEarlyBirdPending:
"""Tests for _save_early_bird_pending method."""
def test_saves_pending_marker(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Saves a date-stamped marker to the pending file, not workout_log.json."""
locker = create_locker(mock_tk, tmp_path)
pending_file = tmp_path / "early_bird_pending.json"
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
patch("screen_locker._early_bird.compute_entry_hmac", return_value=None),
):
locker._save_early_bird_pending()
assert pending_file.exists()
with pending_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert data["date"] == today
assert not locker.log_file.exists()
def test_signs_when_hmac_key_available(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Includes an hmac field when a signature is computed."""
locker = create_locker(mock_tk, tmp_path)
pending_file = tmp_path / "early_bird_pending.json"
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
patch("screen_locker._early_bird.compute_entry_hmac", return_value="sig"),
):
locker._save_early_bird_pending()
data: dict[str, Any] = json.loads(pending_file.read_text())
assert data["hmac"] == "sig"
def test_os_error_on_save(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Warns and does not raise when writing the pending file fails."""
locker = create_locker(mock_tk, tmp_path)
mock_file = MagicMock()
mock_file.open.side_effect = OSError("disk full")
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", mock_file),
patch("screen_locker._early_bird.compute_entry_hmac", return_value=None),
):
locker._save_early_bird_pending()

View File

@ -0,0 +1,197 @@
"""Tests for early bird carrot feature in screen locker."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from typing import TYPE_CHECKING, Any
from unittest.mock import MagicMock, patch
from screen_locker.tests.conftest import (
create_locker,
)
if TYPE_CHECKING:
from pathlib import Path
class TestIsEarlyBirdPending:
"""Tests for _is_early_bird_pending method.
early_bird is a same-day pending marker stored in its own HMAC-signed
file (EARLY_BIRD_PENDING_FILE), not in workout_log.json — see
_early_bird.py's module docstring for why.
"""
def test_no_pending_file(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when the pending file does not exist."""
locker = create_locker(mock_tk, tmp_path)
assert locker._is_early_bird_pending() is False
def test_invalid_json(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when the pending file contains invalid JSON."""
locker = create_locker(mock_tk, tmp_path)
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text("{bad json}")
with patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file):
assert locker._is_early_bird_pending() is False
def test_os_error_on_open(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when opening the pending file raises OSError."""
locker = create_locker(mock_tk, tmp_path)
mock_file = MagicMock()
mock_file.exists.return_value = True
mock_file.open.side_effect = OSError("permission denied")
with patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", mock_file):
assert locker._is_early_bird_pending() is False
def test_stale_date(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when the marker is from a previous day."""
locker = create_locker(mock_tk, tmp_path)
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": "2000-01-01", "hmac": "sig"}))
with patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file):
assert locker._is_early_bird_pending() is False
def test_hmac_invalid(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return False when HMAC verification fails."""
locker = create_locker(mock_tk, tmp_path)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": today, "hmac": "bad"}))
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
patch(
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
),
patch(
"screen_locker._compliance_state.compute_entry_hmac", return_value="sig"
),
):
assert locker._is_early_bird_pending() is False
def test_today_valid_marker(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Return True when today's marker is present and HMAC-valid."""
locker = create_locker(mock_tk, tmp_path)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": today, "hmac": "sig"}))
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
patch(
"screen_locker._compliance_state.verify_entry_hmac", return_value=True
),
):
assert locker._is_early_bird_pending() is True
def test_unsigned_accepted_when_key_unavailable(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Unsigned marker is accepted when no HMAC key is configured."""
locker = create_locker(mock_tk, tmp_path)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
pending_file = tmp_path / "early_bird_pending.json"
pending_file.write_text(json.dumps({"date": today}))
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
patch(
"screen_locker._compliance_state.verify_entry_hmac", return_value=False
),
patch(
"screen_locker._compliance_state.compute_entry_hmac", return_value=None
),
):
assert locker._is_early_bird_pending() is True
class TestSaveEarlyBirdPending:
"""Tests for _save_early_bird_pending method."""
def test_saves_pending_marker(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Saves a date-stamped marker to the pending file, not workout_log.json."""
locker = create_locker(mock_tk, tmp_path)
pending_file = tmp_path / "early_bird_pending.json"
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
patch("screen_locker._early_bird.compute_entry_hmac", return_value=None),
):
locker._save_early_bird_pending()
assert pending_file.exists()
with pending_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert data["date"] == today
assert not locker.log_file.exists()
def test_signs_when_hmac_key_available(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Includes an hmac field when a signature is computed."""
locker = create_locker(mock_tk, tmp_path)
pending_file = tmp_path / "early_bird_pending.json"
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", pending_file),
patch("screen_locker._early_bird.compute_entry_hmac", return_value="sig"),
):
locker._save_early_bird_pending()
data: dict[str, Any] = json.loads(pending_file.read_text())
assert data["hmac"] == "sig"
def test_os_error_on_save(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Warns and does not raise when writing the pending file fails."""
locker = create_locker(mock_tk, tmp_path)
mock_file = MagicMock()
mock_file.open.side_effect = OSError("disk full")
with (
patch("screen_locker._early_bird.EARLY_BIRD_PENDING_FILE", mock_file),
patch("screen_locker._early_bird.compute_entry_hmac", return_value=None),
):
locker._save_early_bird_pending()

View File

@ -5,7 +5,7 @@ from __future__ import annotations
from datetime import datetime, timezone
import json
import tkinter as tk
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
@ -221,123 +221,3 @@ class TestHasLoggedToday:
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
assert locker.has_logged_today() is False
class TestSaveWorkoutLog:
"""Tests for save_workout_log method."""
def test_save_to_new_file(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test saving to a new log file includes HMAC."""
log_file = tmp_path / "workout_log.json"
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
locker.workout_data = {"type": "running"}
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value="abc123",
):
locker.save_workout_log()
assert log_file.exists()
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert today in data
# The log now holds a list of entries per day (multiple workouts/day).
assert data[today][0]["workout_data"]["type"] == "running"
assert data[today][0]["hmac"] == "abc123"
def test_save_to_new_file_no_hmac_key(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test saving without HMAC key produces unsigned entry."""
log_file = tmp_path / "workout_log.json"
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
locker.workout_data = {"type": "running"}
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value=None,
):
locker.save_workout_log()
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert "hmac" not in data[today][0]
def test_save_to_existing_file(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test saving appends to existing log file."""
log_file = tmp_path / "workout_log.json"
log_file.write_text(json.dumps({"2020-01-01": {"old": "data"}}))
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
locker.workout_data = {"type": "strength"}
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value="sig",
):
locker.save_workout_log()
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
assert "2020-01-01" in data
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert today in data
def test_save_with_corrupted_existing_file(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test saving when existing file is corrupted."""
log_file = tmp_path / "workout_log.json"
log_file.write_text("not valid json")
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
locker.workout_data = {"type": "running"}
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value="sig",
):
locker.save_workout_log()
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert today in data
def test_save_with_write_error(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test saving handles write errors gracefully."""
log_file = tmp_path / "nonexistent_dir" / "workout_log.json"
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
locker.workout_data = {"type": "running"}
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value="sig",
):
# Should not raise, just log warning
locker.save_workout_log()

View File

@ -0,0 +1,133 @@
"""Tests for screen_locker initialization, logging, and basic operations."""
from __future__ import annotations
from datetime import datetime, timezone
import json
from typing import TYPE_CHECKING, Any
from unittest.mock import MagicMock, patch
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
class TestSaveWorkoutLog:
"""Tests for save_workout_log method."""
def test_save_to_new_file(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test saving to a new log file includes HMAC."""
log_file = tmp_path / "workout_log.json"
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
locker.workout_data = {"type": "running"}
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value="abc123",
):
locker.save_workout_log()
assert log_file.exists()
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert today in data
# The log now holds a list of entries per day (multiple workouts/day).
assert data[today][0]["workout_data"]["type"] == "running"
assert data[today][0]["hmac"] == "abc123"
def test_save_to_new_file_no_hmac_key(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test saving without HMAC key produces unsigned entry."""
log_file = tmp_path / "workout_log.json"
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
locker.workout_data = {"type": "running"}
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value=None,
):
locker.save_workout_log()
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert "hmac" not in data[today][0]
def test_save_to_existing_file(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test saving appends to existing log file."""
log_file = tmp_path / "workout_log.json"
log_file.write_text(json.dumps({"2020-01-01": {"old": "data"}}))
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
locker.workout_data = {"type": "strength"}
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value="sig",
):
locker.save_workout_log()
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
assert "2020-01-01" in data
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert today in data
def test_save_with_corrupted_existing_file(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test saving when existing file is corrupted."""
log_file = tmp_path / "workout_log.json"
log_file.write_text("not valid json")
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
locker.workout_data = {"type": "running"}
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value="sig",
):
locker.save_workout_log()
with log_file.open() as f:
data: dict[str, Any] = json.load(f)
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
assert today in data
def test_save_with_write_error(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test saving handles write errors gracefully."""
log_file = tmp_path / "nonexistent_dir" / "workout_log.json"
locker = create_locker(mock_tk, tmp_path)
locker.log_file = log_file
locker.workout_data = {"type": "running"}
with patch(
"screen_locker._log_mixin.compute_entry_hmac",
return_value="sig",
):
# Should not raise, just log warning
locker.save_workout_log()

View File

@ -8,7 +8,6 @@ from typing import TYPE_CHECKING
from unittest.mock import patch
from screen_locker import _manual_sync
from screen_locker._log_mixin import RecordResult
from screen_locker._manual_sync import (
ingest_manual_records,
reconstruct_draft,
@ -189,69 +188,6 @@ class TestIngestManualRecords:
assert "hmac" not in stored[_DATE][0]
class TestIngestManualRecordsCallback:
"""Tests for the ``on_ingested`` callback that drives shutdown/debt credit."""
def test_on_ingested_called_with_entry_and_prior_entries(
self, tmp_path: Path
) -> None:
"""On ingested called with entry and prior entries."""
log_file = tmp_path / "workout_log.json"
log_file.write_text(
json.dumps({_DATE: [{"workout_data": {"type": "phone_verified"}}]})
)
record = _manual_record(_TT_DRAFT)
calls: list[tuple[dict, list[dict]]] = []
ingest_manual_records(
log_file,
[record],
today=_DATE,
on_ingested=lambda entry, prior: calls.append((entry, prior)),
)
assert len(calls) == 1
entry, prior = calls[0]
assert entry["type"] == "manual_workout"
assert entry["sync_record_id"] == record[0]
assert prior == [{"workout_data": {"type": "phone_verified"}}]
def test_on_ingested_not_called_when_budget_exhausted(self, tmp_path: Path) -> None:
"""On ingested not called when budget exhausted."""
log_file = tmp_path / "workout_log.json"
record = _manual_record(_TT_DRAFT)
calls: list[tuple[dict, list[dict]]] = []
with patch.object(_manual_sync, "is_budget_exhausted", return_value=True):
ingest_manual_records(
log_file,
[record],
today=_DATE,
on_ingested=lambda entry, prior: calls.append((entry, prior)),
)
assert calls == []
def test_write_chokepoint_collision_is_not_credited_or_returned(
self, tmp_path: Path
) -> None:
"""If the write chokepoint's own workout_id dedup no-ops the write
(``appended=False``), the record must not be reported as ingested or
handed to ``on_ingested`` — crediting a write that never happened
would be a real correctness bug, not just a missed optimization."""
log_file = tmp_path / "workout_log.json"
record = _manual_record(_TT_DRAFT)
calls: list[tuple[dict, list[dict]]] = []
with patch(
"screen_locker._manual_sync.write_signed_entry",
return_value=RecordResult(appended=False, prior_entries=[]),
):
ingested = ingest_manual_records(
log_file,
[record],
today=_DATE,
on_ingested=lambda entry, prior: calls.append((entry, prior)),
)
assert ingested == []
assert calls == []
def _dt(date: str) -> object:
from datetime import datetime, timezone

View File

@ -0,0 +1,122 @@
"""Tests for ingesting synced manual workouts into workout_log.json."""
# pylint: disable=protected-access
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
from screen_locker import _manual_sync
from screen_locker._log_mixin import RecordResult
from screen_locker._manual_sync import (
ingest_manual_records,
)
from screen_locker._manual_workout import (
SPORT_OTHER,
SPORT_TABLE_TENNIS,
ManualWorkoutDraft,
)
from screen_locker.tests.test_manual_sync import _manual_record
if TYPE_CHECKING:
from pathlib import Path
_DATE = "2026-07-13"
_TT_DRAFT = ManualWorkoutDraft(
sport=SPORT_TABLE_TENNIS,
start_time="18:00",
end_time="19:30",
location_name="Solec",
transport_method="bike",
cost="40 PLN",
rpe=6,
went_well="Served consistently and moved feet well",
to_improve="Backhand topspin needs more consistency",
overall_feeling="Felt strong focused and in good rhythm",
matches_won=3,
matches_lost=1,
sets_won=7,
sets_lost=4,
racket="Butterfly",
balls="Nittaku 3-star",
)
_OTHER_DRAFT = ManualWorkoutDraft(
sport=SPORT_OTHER,
start_time="09:00",
end_time="10:00",
location_name="Squash club",
transport_method="car",
cost="30 PLN",
rpe=5,
went_well="Moved well and kept long rallies going",
to_improve="Need to volley earlier off the back wall",
overall_feeling="Tired but satisfied with the effort",
activity_type_other="squash",
activity_details="Full-court squash drills and three practice games total",
equipment="racket, goggles",
)
class TestIngestManualRecordsCallback:
"""Tests for the ``on_ingested`` callback that drives shutdown/debt credit."""
def test_on_ingested_called_with_entry_and_prior_entries(
self, tmp_path: Path
) -> None:
"""On ingested called with entry and prior entries."""
log_file = tmp_path / "workout_log.json"
log_file.write_text(
json.dumps({_DATE: [{"workout_data": {"type": "phone_verified"}}]})
)
record = _manual_record(_TT_DRAFT)
calls: list[tuple[dict, list[dict]]] = []
ingest_manual_records(
log_file,
[record],
today=_DATE,
on_ingested=lambda entry, prior: calls.append((entry, prior)),
)
assert len(calls) == 1
entry, prior = calls[0]
assert entry["type"] == "manual_workout"
assert entry["sync_record_id"] == record[0]
assert prior == [{"workout_data": {"type": "phone_verified"}}]
def test_on_ingested_not_called_when_budget_exhausted(self, tmp_path: Path) -> None:
"""On ingested not called when budget exhausted."""
log_file = tmp_path / "workout_log.json"
record = _manual_record(_TT_DRAFT)
calls: list[tuple[dict, list[dict]]] = []
with patch.object(_manual_sync, "is_budget_exhausted", return_value=True):
ingest_manual_records(
log_file,
[record],
today=_DATE,
on_ingested=lambda entry, prior: calls.append((entry, prior)),
)
assert calls == []
def test_write_chokepoint_collision_is_not_credited_or_returned(
self, tmp_path: Path
) -> None:
"""If the write chokepoint's own workout_id dedup no-ops the write
(``appended=False``), the record must not be reported as ingested or
handed to ``on_ingested`` — crediting a write that never happened
would be a real correctness bug, not just a missed optimization."""
log_file = tmp_path / "workout_log.json"
record = _manual_record(_TT_DRAFT)
calls: list[tuple[dict, list[dict]]] = []
with patch(
"screen_locker._manual_sync.write_signed_entry",
return_value=RecordResult(appended=False, prior_entries=[]),
):
ingested = ingest_manual_records(
log_file,
[record],
today=_DATE,
on_ingested=lambda entry, prior: calls.append((entry, prior)),
)
assert ingested == []
assert calls == []

View File

@ -139,202 +139,3 @@ class TestPullWorkoutAppJsonMultiPath:
with patch.object(locker, "_run_adb", fake):
result = locker._pull_workout_app_json()
assert result is None
class TestVerifyPhoneWorkoutFallthrough:
"""Tests for the ADB→HTTP fall-through in _verify_phone_workout."""
def test_adb_connected_but_pull_empty_falls_through_to_http(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A connected device with no pullable JSON still tries the HTTP scan."""
locker = create_locker(mock_tk, tmp_path)
http_data = {
"date": _today(),
"exercises": ["a"],
"duration_seconds": 4000,
"succeeded": True,
}
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch.object(locker, "_is_phone_connected", return_value=True),
patch.object(locker, "_pull_workout_app_json", return_value=None),
patch.object(locker, "_fetch_http_workout", return_value=http_data),
):
status, _ = locker._verify_phone_workout()
assert status == "verified"
def test_adb_connected_pull_and_http_empty_is_not_verified(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Connected device, no JSON anywhere → not_verified (not no_phone)."""
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch.object(locker, "_is_phone_connected", return_value=True),
patch.object(locker, "_pull_workout_app_json", return_value=None),
patch.object(locker, "_fetch_http_workout", return_value=None),
):
status, _ = locker._verify_phone_workout()
assert status == "not_verified"
def test_adb_pull_success_returns_without_http(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A successful ADB pull validates directly, never touching HTTP."""
locker = create_locker(mock_tk, tmp_path)
data = {
"date": _today(),
"exercises": ["a"],
"duration_seconds": 4000,
"succeeded": False,
}
http = MagicMock()
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch.object(locker, "_is_phone_connected", return_value=True),
patch.object(locker, "_pull_workout_app_json", return_value=data),
patch.object(locker, "_fetch_http_workout", http),
):
status, _ = locker._verify_phone_workout()
assert status == "verified"
http.assert_not_called()
def test_clock_tampered_short_circuits(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A clock-skew failure returns clock_tampered before any phone access."""
locker = create_locker(mock_tk, tmp_path)
with patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(False, "clock skew too large"),
):
status, message = locker._verify_phone_workout()
assert status == "clock_tampered"
assert message == "clock skew too large"
def test_no_device_and_http_empty_is_no_phone(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""No device and no HTTP server → no_phone."""
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch.object(locker, "_is_phone_connected", return_value=False),
patch.object(locker, "_fetch_http_workout", return_value=None),
):
status, _ = locker._verify_phone_workout()
assert status == "no_phone"
def test_synced_data_is_validated_directly_without_adb_or_http(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A successful sync pull short-circuits ADB/HTTP entirely."""
locker = create_locker(mock_tk, tmp_path)
synced_data = {
"date": _today(),
"exercises": ["a"],
"duration_seconds": 4000,
"succeeded": True,
}
adb = MagicMock()
http = MagicMock()
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch(
"screen_locker._phone_verification.pull_synced_workout",
return_value=(synced_data, None),
),
patch.object(locker, "_is_phone_connected", adb),
patch.object(locker, "_fetch_http_workout", http),
):
status, _ = locker._verify_phone_workout()
assert status == "verified"
adb.assert_not_called()
http.assert_not_called()
def test_sync_error_falls_through_to_a_successful_fallback_silently(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A sync error must never block a result the fallback can still find."""
locker = create_locker(mock_tk, tmp_path)
http_data = {
"date": _today(),
"exercises": ["a"],
"duration_seconds": 4000,
"succeeded": True,
}
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch(
"screen_locker._phone_verification.pull_synced_workout",
return_value=(None, "network unreachable"),
),
patch.object(locker, "_is_phone_connected", return_value=False),
patch.object(locker, "_fetch_http_workout", return_value=http_data),
):
status, _ = locker._verify_phone_workout()
assert status == "verified"
def test_sync_error_and_empty_fallback_returns_sync_failed(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Nothing found anywhere AND sync errored → sync_failed, not no_phone."""
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch(
"screen_locker._phone_verification.pull_synced_workout",
return_value=(None, "bad token"),
),
patch.object(locker, "_is_phone_connected", return_value=False),
patch.object(locker, "_fetch_http_workout", return_value=None),
):
status, message = locker._verify_phone_workout()
assert status == "sync_failed"
assert message == "bad token"

View File

@ -0,0 +1,221 @@
"""Tests for multi-path workout-JSON pull and HTTP fall-through (part 3).
Covers the fix for the path mismatch where the app writes
``/sdcard/workout_result.json`` (primary) but the locker only checked the
app-external fallback path. The locker now pulls every candidate path, prefers
the one dated today, and falls through to the HTTP scan when an ADB pull yields
no usable JSON even though a device is connected.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker._constants import WORKOUT_APP_JSON_REMOTES
from screen_locker.tests.conftest import create_locker
from screen_locker.tests.test_phone_verification_part3 import _today
if TYPE_CHECKING:
from pathlib import Path
_PRIMARY, _FALLBACK = WORKOUT_APP_JSON_REMOTES
class TestVerifyPhoneWorkoutFallthrough:
"""Tests for the ADB→HTTP fall-through in _verify_phone_workout."""
def test_adb_connected_but_pull_empty_falls_through_to_http(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A connected device with no pullable JSON still tries the HTTP scan."""
locker = create_locker(mock_tk, tmp_path)
http_data = {
"date": _today(),
"exercises": ["a"],
"duration_seconds": 4000,
"succeeded": True,
}
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch.object(locker, "_is_phone_connected", return_value=True),
patch.object(locker, "_pull_workout_app_json", return_value=None),
patch.object(locker, "_fetch_http_workout", return_value=http_data),
):
status, _ = locker._verify_phone_workout()
assert status == "verified"
def test_adb_connected_pull_and_http_empty_is_not_verified(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Connected device, no JSON anywhere → not_verified (not no_phone)."""
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch.object(locker, "_is_phone_connected", return_value=True),
patch.object(locker, "_pull_workout_app_json", return_value=None),
patch.object(locker, "_fetch_http_workout", return_value=None),
):
status, _ = locker._verify_phone_workout()
assert status == "not_verified"
def test_adb_pull_success_returns_without_http(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A successful ADB pull validates directly, never touching HTTP."""
locker = create_locker(mock_tk, tmp_path)
data = {
"date": _today(),
"exercises": ["a"],
"duration_seconds": 4000,
"succeeded": False,
}
http = MagicMock()
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch.object(locker, "_is_phone_connected", return_value=True),
patch.object(locker, "_pull_workout_app_json", return_value=data),
patch.object(locker, "_fetch_http_workout", http),
):
status, _ = locker._verify_phone_workout()
assert status == "verified"
http.assert_not_called()
def test_clock_tampered_short_circuits(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A clock-skew failure returns clock_tampered before any phone access."""
locker = create_locker(mock_tk, tmp_path)
with patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(False, "clock skew too large"),
):
status, message = locker._verify_phone_workout()
assert status == "clock_tampered"
assert message == "clock skew too large"
def test_no_device_and_http_empty_is_no_phone(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""No device and no HTTP server → no_phone."""
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch.object(locker, "_is_phone_connected", return_value=False),
patch.object(locker, "_fetch_http_workout", return_value=None),
):
status, _ = locker._verify_phone_workout()
assert status == "no_phone"
def test_synced_data_is_validated_directly_without_adb_or_http(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A successful sync pull short-circuits ADB/HTTP entirely."""
locker = create_locker(mock_tk, tmp_path)
synced_data = {
"date": _today(),
"exercises": ["a"],
"duration_seconds": 4000,
"succeeded": True,
}
adb = MagicMock()
http = MagicMock()
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch(
"screen_locker._phone_verification.pull_synced_workout",
return_value=(synced_data, None),
),
patch.object(locker, "_is_phone_connected", adb),
patch.object(locker, "_fetch_http_workout", http),
):
status, _ = locker._verify_phone_workout()
assert status == "verified"
adb.assert_not_called()
http.assert_not_called()
def test_sync_error_falls_through_to_a_successful_fallback_silently(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A sync error must never block a result the fallback can still find."""
locker = create_locker(mock_tk, tmp_path)
http_data = {
"date": _today(),
"exercises": ["a"],
"duration_seconds": 4000,
"succeeded": True,
}
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch(
"screen_locker._phone_verification.pull_synced_workout",
return_value=(None, "network unreachable"),
),
patch.object(locker, "_is_phone_connected", return_value=False),
patch.object(locker, "_fetch_http_workout", return_value=http_data),
):
status, _ = locker._verify_phone_workout()
assert status == "verified"
def test_sync_error_and_empty_fallback_returns_sync_failed(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Nothing found anywhere AND sync errored → sync_failed, not no_phone."""
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker._phone_verification.check_clock_skew",
return_value=(True, ""),
),
patch(
"screen_locker._phone_verification.pull_synced_workout",
return_value=(None, "bad token"),
),
patch.object(locker, "_is_phone_connected", return_value=False),
patch.object(locker, "_fetch_http_workout", return_value=None),
):
status, message = locker._verify_phone_workout()
assert status == "sync_failed"
assert message == "bad token"

View File

@ -4,9 +4,8 @@ from __future__ import annotations
import os
import shutil
import sqlite3
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock
from screen_locker.tests.conftest import create_locker
@ -231,90 +230,3 @@ class TestPullRunnerupDb:
# ---------------------------------------------------------------------------
# _query_todays_run
# ---------------------------------------------------------------------------
class TestQueryTodaysRun:
"""Tests for _query_todays_run (lines 328-355)."""
def _make_db(self, tmp_path: Path) -> str:
"""Create a minimal RunnerUp DB with one activity for today."""
import time
db_path = str(tmp_path / "runnerup.db")
with sqlite3.connect(db_path) as conn:
conn.execute(
"CREATE TABLE activity "
"(start_time REAL, distance REAL, time REAL, type INTEGER, deleted INTEGER)"
)
# Insert a valid activity for today (sport=0, Running).
now_ms = time.time()
conn.execute(
"INSERT INTO activity VALUES (?, ?, ?, ?, ?)",
(now_ms, 6000.0, 2400.0, 0, 0),
)
return db_path
def test_returns_none_for_no_activity_today(self, tmp_path: Path) -> None:
"""Empty DB → None."""
db_path = str(tmp_path / "empty.db")
with sqlite3.connect(db_path) as conn:
conn.execute(
"CREATE TABLE activity "
"(start_time REAL, distance REAL, time REAL, type INTEGER, deleted INTEGER)"
)
# Need a locker instance to call the method.
import tkinter as tk
from unittest.mock import MagicMock
mock_tk = MagicMock()
mock_tk.Tk.return_value = MagicMock()
mock_tk.Tk.return_value.winfo_screenwidth.return_value = 1920
mock_tk.Tk.return_value.winfo_screenheight.return_value = 1080
mock_tk.TclError = tk.TclError
with (
patch("screen_locker.screen_lock.tk", mock_tk),
patch(
"screen_locker.screen_lock.GateRoot",
return_value=mock_tk.Tk.return_value,
),
patch("screen_locker.screen_lock.sys.exit"),
):
locker = create_locker(mock_tk, tmp_path)
result = locker._query_todays_run(db_path)
assert result is None
def test_returns_activity_dict_for_todays_run(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""DB with a today activity → dict with expected keys."""
locker = create_locker(mock_tk, tmp_path)
db_path = self._make_db(tmp_path)
result = locker._query_todays_run(db_path)
assert result is not None
assert "sport" in result
assert result["sport"] == 0
assert result["distance_m"] == 6000.0
def test_returns_none_on_sqlite_error(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Corrupt DB → sqlite3.Error caught; returns None."""
locker = create_locker(mock_tk, tmp_path)
corrupt_db = str(tmp_path / "corrupt.db")
with open(corrupt_db, "w") as f:
f.write("this is not a sqlite database")
result = locker._query_todays_run(corrupt_db)
assert result is None
# ---------------------------------------------------------------------------
# _verify_runnerup_via_db
# ---------------------------------------------------------------------------

View File

@ -0,0 +1,151 @@
"""Tests for RunnerUpVerificationMixin in _runnerup_verification.py."""
from __future__ import annotations
import sqlite3
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
# Minimal valid TCX XML for a 40-minute, 6-km run.
_TCX_RUNNING = """\
<?xml version="1.0" encoding="UTF-8"?>
<TrainingCenterDatabase
xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2">
<Activities>
<Activity Sport="Running">
<Lap>
<TotalTimeSeconds>2400.0</TotalTimeSeconds>
<DistanceMeters>6000.0</DistanceMeters>
</Lap>
</Activity>
</Activities>
</TrainingCenterDatabase>
"""
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
_TCX_GYM = """\
<?xml version="1.0" encoding="UTF-8"?>
<TrainingCenterDatabase
xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2">
<Activities>
<Activity Sport="Gym">
<Lap>
<TotalTimeSeconds>3600.0</TotalTimeSeconds>
<DistanceMeters>0.0</DistanceMeters>
</Lap>
</Activity>
</Activities>
</TrainingCenterDatabase>
"""
# Two laps that together make a valid run.
_TCX_MULTI_LAP = """\
<?xml version="1.0" encoding="UTF-8"?>
<TrainingCenterDatabase
xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2">
<Activities>
<Activity Sport="Running">
<Lap>
<TotalTimeSeconds>1200.0</TotalTimeSeconds>
<DistanceMeters>3000.0</DistanceMeters>
</Lap>
<Lap>
<TotalTimeSeconds>1200.0</TotalTimeSeconds>
<DistanceMeters>3000.0</DistanceMeters>
</Lap>
</Activity>
</Activities>
</TrainingCenterDatabase>
"""
class TestQueryTodaysRun:
"""Tests for _query_todays_run (lines 328-355)."""
def _make_db(self, tmp_path: Path) -> str:
"""Create a minimal RunnerUp DB with one activity for today."""
import time
db_path = str(tmp_path / "runnerup.db")
with sqlite3.connect(db_path) as conn:
conn.execute(
"CREATE TABLE activity "
"(start_time REAL, distance REAL, time REAL, type INTEGER, deleted INTEGER)"
)
# Insert a valid activity for today (sport=0, Running).
now_ms = time.time()
conn.execute(
"INSERT INTO activity VALUES (?, ?, ?, ?, ?)",
(now_ms, 6000.0, 2400.0, 0, 0),
)
return db_path
def test_returns_none_for_no_activity_today(self, tmp_path: Path) -> None:
"""Empty DB → None."""
db_path = str(tmp_path / "empty.db")
with sqlite3.connect(db_path) as conn:
conn.execute(
"CREATE TABLE activity "
"(start_time REAL, distance REAL, time REAL, type INTEGER, deleted INTEGER)"
)
# Need a locker instance to call the method.
import tkinter as tk
from unittest.mock import MagicMock
mock_tk = MagicMock()
mock_tk.Tk.return_value = MagicMock()
mock_tk.Tk.return_value.winfo_screenwidth.return_value = 1920
mock_tk.Tk.return_value.winfo_screenheight.return_value = 1080
mock_tk.TclError = tk.TclError
with (
patch("screen_locker.screen_lock.tk", mock_tk),
patch(
"screen_locker.screen_lock.GateRoot",
return_value=mock_tk.Tk.return_value,
),
patch("screen_locker.screen_lock.sys.exit"),
):
locker = create_locker(mock_tk, tmp_path)
result = locker._query_todays_run(db_path)
assert result is None
def test_returns_activity_dict_for_todays_run(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""DB with a today activity → dict with expected keys."""
locker = create_locker(mock_tk, tmp_path)
db_path = self._make_db(tmp_path)
result = locker._query_todays_run(db_path)
assert result is not None
assert "sport" in result
assert result["sport"] == 0
assert result["distance_m"] == 6000.0
def test_returns_none_on_sqlite_error(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Corrupt DB → sqlite3.Error caught; returns None."""
locker = create_locker(mock_tk, tmp_path)
corrupt_db = str(tmp_path / "corrupt.db")
with open(corrupt_db, "w") as f:
f.write("this is not a sqlite database")
result = locker._query_todays_run(corrupt_db)
assert result is None
# ---------------------------------------------------------------------------
# _verify_runnerup_via_db
# ---------------------------------------------------------------------------

View File

@ -3,7 +3,6 @@
from __future__ import annotations
import json
import subprocess
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
@ -237,80 +236,3 @@ class TestBuildShutdownCmd:
"20",
"8",
]
class TestWriteShutdownConfig:
"""Tests for _write_shutdown_config method."""
def test_returns_false_when_script_missing(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test returns False when adjust script doesn't exist."""
locker = create_locker(mock_tk, tmp_path)
mock_script = MagicMock()
mock_script.exists.return_value = False
with patch(
"screen_locker._shutdown.ADJUST_SHUTDOWN_SCRIPT",
mock_script,
):
result = locker._write_shutdown_config(21, 20, 8)
assert result is False
def test_success_calls_run_shutdown_cmd(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test successful config write delegates to _run_shutdown_cmd."""
locker = create_locker(mock_tk, tmp_path)
mock_script = MagicMock()
mock_script.exists.return_value = True
with (
patch(
"screen_locker._shutdown.ADJUST_SHUTDOWN_SCRIPT",
mock_script,
),
patch.object(locker, "_run_shutdown_cmd", return_value=True) as mock_run,
):
result = locker._write_shutdown_config(21, 20, 8)
assert result is True
mock_run.assert_called_once()
class TestRunShutdownCmd:
"""Tests for _run_shutdown_cmd method."""
def test_success(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test successful command execution."""
locker = create_locker(mock_tk, tmp_path)
mock_result = MagicMock(stdout="OK\n")
with patch(
"screen_locker._shutdown.subprocess.run",
return_value=mock_result,
):
result = locker._run_shutdown_cmd(["cmd"], 21, 20)
assert result is True
def test_returns_false_on_subprocess_error(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test returns False on SubprocessError."""
locker = create_locker(mock_tk, tmp_path)
with patch(
"screen_locker._shutdown.subprocess.run",
side_effect=subprocess.CalledProcessError(1, "cmd"),
):
result = locker._run_shutdown_cmd(["cmd"], 21, 20)
assert result is False

View File

@ -0,0 +1,89 @@
"""Tests for shutdown schedule adjustment coverage gaps (part 3)."""
from __future__ import annotations
import subprocess
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
class TestWriteShutdownConfig:
"""Tests for _write_shutdown_config method."""
def test_returns_false_when_script_missing(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test returns False when adjust script doesn't exist."""
locker = create_locker(mock_tk, tmp_path)
mock_script = MagicMock()
mock_script.exists.return_value = False
with patch(
"screen_locker._shutdown.ADJUST_SHUTDOWN_SCRIPT",
mock_script,
):
result = locker._write_shutdown_config(21, 20, 8)
assert result is False
def test_success_calls_run_shutdown_cmd(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test successful config write delegates to _run_shutdown_cmd."""
locker = create_locker(mock_tk, tmp_path)
mock_script = MagicMock()
mock_script.exists.return_value = True
with (
patch(
"screen_locker._shutdown.ADJUST_SHUTDOWN_SCRIPT",
mock_script,
),
patch.object(locker, "_run_shutdown_cmd", return_value=True) as mock_run,
):
result = locker._write_shutdown_config(21, 20, 8)
assert result is True
mock_run.assert_called_once()
class TestRunShutdownCmd:
"""Tests for _run_shutdown_cmd method."""
def test_success(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test successful command execution."""
locker = create_locker(mock_tk, tmp_path)
mock_result = MagicMock(stdout="OK\n")
with patch(
"screen_locker._shutdown.subprocess.run",
return_value=mock_result,
):
result = locker._run_shutdown_cmd(["cmd"], 21, 20)
assert result is True
def test_returns_false_on_subprocess_error(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Test returns False on SubprocessError."""
locker = create_locker(mock_tk, tmp_path)
with patch(
"screen_locker._shutdown.subprocess.run",
side_effect=subprocess.CalledProcessError(1, "cmd"),
):
result = locker._run_shutdown_cmd(["cmd"], 21, 20)
assert result is False

View File

@ -2,13 +2,12 @@
from __future__ import annotations
from unittest.mock import MagicMock, patch
from typing import TYPE_CHECKING
from screen_locker._compliance_state import AutoUpgradeOpportunity
from screen_locker._status_view_verify import (
PhoneCheckOutcome,
_verify_phone_then_runnerup,
)
if TYPE_CHECKING:
from unittest.mock import MagicMock
from screen_locker.tests._status_view_helpers import (
_day,
_lock_explanation,
@ -205,67 +204,3 @@ class TestSectionShutdown:
texts = _texts(mock_tk)
assert any("Rest of week:" in t for t in texts)
assert any("Next week (speculative):" in t for t in texts)
class TestVerifyPhoneThenRunnerup:
"""The "Check Phone" worker: StrongLifts first, then RunnerUp as fallback."""
def test_stronglifts_verified_short_circuits(self) -> None:
"""A verified phone workout wins and RunnerUp is never consulted."""
verifier = MagicMock()
verifier._verify_phone_workout.return_value = ("verified", "5x5 done")
result = _verify_phone_then_runnerup(verifier)
assert result == PhoneCheckOutcome(
"phone_verified", "verified", "5x5 done", None
)
verifier._verify_runnerup_workout.assert_not_called()
def test_falls_back_to_runnerup_when_phone_not_verified(self) -> None:
"""StrongLifts miss → a verified run credits as runnerup_verified."""
verifier = MagicMock()
verifier._verify_phone_workout.return_value = ("not_verified", "stale")
verifier._verify_runnerup_workout.return_value = ("verified", "9.8 km")
result = _verify_phone_then_runnerup(verifier)
assert result == PhoneCheckOutcome(
"runnerup_verified", "verified", "stale", "9.8 km"
)
def test_neither_source_verified_nor_backfilled(self) -> None:
"""Neither verified today, nothing to backfill → no credit, no fill message."""
verifier = MagicMock()
verifier._verify_phone_workout.return_value = ("not_verified", "stale")
verifier._verify_runnerup_workout.return_value = ("too_short", "3 km")
verifier._scan_and_fill_week_runnerup.return_value = 0
verifier._try_fill_stronglifts_for_week.return_value = 0
with patch(
"screen_locker._status_view_verify.count_weekly_workouts",
return_value=2,
):
result = _verify_phone_then_runnerup(verifier)
assert result == PhoneCheckOutcome(None, "too_short", "stale", "3 km", None)
def test_falls_back_to_week_scan_backfill(self) -> None:
"""Neither verified today, but the week-scan finds something → fill message."""
verifier = MagicMock()
verifier._verify_phone_workout.return_value = ("not_verified", "stale")
verifier._verify_runnerup_workout.return_value = ("not_verified", "no run")
verifier._scan_and_fill_week_runnerup.return_value = 1
verifier._try_fill_stronglifts_for_week.return_value = 0
with patch(
"screen_locker._status_view_verify.count_weekly_workouts",
side_effect=[2, 3],
):
result = _verify_phone_then_runnerup(verifier)
assert result.credited_type is None
assert (
result.week_fill_message == "Auto-filled 1 workout from earlier this week."
)
verifier._adjust_shutdown_time_by.assert_not_called()

View File

@ -0,0 +1,74 @@
"""Tests for the read-only Tkinter status window's rendering (StatusWindow.render)."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from screen_locker._status_view_verify import (
PhoneCheckOutcome,
_verify_phone_then_runnerup,
)
class TestVerifyPhoneThenRunnerup:
"""The "Check Phone" worker: StrongLifts first, then RunnerUp as fallback."""
def test_stronglifts_verified_short_circuits(self) -> None:
"""A verified phone workout wins and RunnerUp is never consulted."""
verifier = MagicMock()
verifier._verify_phone_workout.return_value = ("verified", "5x5 done")
result = _verify_phone_then_runnerup(verifier)
assert result == PhoneCheckOutcome(
"phone_verified", "verified", "5x5 done", None
)
verifier._verify_runnerup_workout.assert_not_called()
def test_falls_back_to_runnerup_when_phone_not_verified(self) -> None:
"""StrongLifts miss → a verified run credits as runnerup_verified."""
verifier = MagicMock()
verifier._verify_phone_workout.return_value = ("not_verified", "stale")
verifier._verify_runnerup_workout.return_value = ("verified", "9.8 km")
result = _verify_phone_then_runnerup(verifier)
assert result == PhoneCheckOutcome(
"runnerup_verified", "verified", "stale", "9.8 km"
)
def test_neither_source_verified_nor_backfilled(self) -> None:
"""Neither verified today, nothing to backfill → no credit, no fill message."""
verifier = MagicMock()
verifier._verify_phone_workout.return_value = ("not_verified", "stale")
verifier._verify_runnerup_workout.return_value = ("too_short", "3 km")
verifier._scan_and_fill_week_runnerup.return_value = 0
verifier._try_fill_stronglifts_for_week.return_value = 0
with patch(
"screen_locker._status_view_verify.count_weekly_workouts",
return_value=2,
):
result = _verify_phone_then_runnerup(verifier)
assert result == PhoneCheckOutcome(None, "too_short", "stale", "3 km", None)
def test_falls_back_to_week_scan_backfill(self) -> None:
"""Neither verified today, but the week-scan finds something → fill message."""
verifier = MagicMock()
verifier._verify_phone_workout.return_value = ("not_verified", "stale")
verifier._verify_runnerup_workout.return_value = ("not_verified", "no run")
verifier._scan_and_fill_week_runnerup.return_value = 1
verifier._try_fill_stronglifts_for_week.return_value = 0
with patch(
"screen_locker._status_view_verify.count_weekly_workouts",
side_effect=[2, 3],
):
result = _verify_phone_then_runnerup(verifier)
assert result.credited_type is None
assert (
result.week_fill_message == "Auto-filled 1 workout from earlier this week."
)
verifier._adjust_shutdown_time_by.assert_not_called()

View File

@ -244,108 +244,3 @@ class TestPollVerifyWorkoutCheck:
"verified",
"Found workout",
)
class TestHandleVerifyWorkoutResult:
"""Tests for _handle_verify_workout_result."""
def test_verified_adjusts_shutdown_and_saves(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On verified: adjust shutdown, save log, show success."""
locker = create_locker(mock_tk, tmp_path)
locker.log_file = tmp_path / "workout_log.json"
object.__setattr__(
locker,
"_adjust_shutdown_time_later",
MagicMock(return_value=True),
)
locker._handle_verify_workout_result("verified", "1 session found")
assert locker.workout_data["type"] == "phone_verified"
assert locker.workout_data["after_sick_day"] == "true"
locker._adjust_shutdown_time_later.assert_called_once()
locker.root.after.assert_called()
def test_verified_without_adjustment(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On verified but adjustment fails: still saves and shows success."""
locker = create_locker(mock_tk, tmp_path)
locker.log_file = tmp_path / "workout_log.json"
object.__setattr__(
locker,
"_adjust_shutdown_time_later",
MagicMock(return_value=False),
)
locker._handle_verify_workout_result("verified", "1 session found")
assert locker.workout_data["type"] == "phone_verified"
locker.root.after.assert_called()
def test_not_verified_shows_retry(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On not_verified: show retry screen."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
"_show_verify_retry",
MagicMock(),
)
locker._handle_verify_workout_result(
"not_verified",
"No workout today",
)
locker._show_verify_retry.assert_called_once_with(
"No workout today",
)
def test_error_shows_retry(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On error: show retry screen."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
"_show_verify_retry",
MagicMock(),
)
locker._handle_verify_workout_result("error", "ADB failed")
locker._show_verify_retry.assert_called_once_with("ADB failed")
class TestShowVerifyRetry:
"""Tests for _show_verify_retry."""
def test_shows_retry_and_close_buttons(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Show TRY AGAIN and Close buttons."""
locker = create_locker(mock_tk, tmp_path)
locker._show_verify_retry("No workout found")
# Verify container was cleared and buttons were packed
locker.container.first.winfo_children.return_value = []

View File

@ -0,0 +1,116 @@
"""Tests for post-sick-day workout verification (--verify-workout)."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
class TestHandleVerifyWorkoutResult:
"""Tests for _handle_verify_workout_result."""
def test_verified_adjusts_shutdown_and_saves(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On verified: adjust shutdown, save log, show success."""
locker = create_locker(mock_tk, tmp_path)
locker.log_file = tmp_path / "workout_log.json"
object.__setattr__(
locker,
"_adjust_shutdown_time_later",
MagicMock(return_value=True),
)
locker._handle_verify_workout_result("verified", "1 session found")
assert locker.workout_data["type"] == "phone_verified"
assert locker.workout_data["after_sick_day"] == "true"
locker._adjust_shutdown_time_later.assert_called_once()
locker.root.after.assert_called()
def test_verified_without_adjustment(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On verified but adjustment fails: still saves and shows success."""
locker = create_locker(mock_tk, tmp_path)
locker.log_file = tmp_path / "workout_log.json"
object.__setattr__(
locker,
"_adjust_shutdown_time_later",
MagicMock(return_value=False),
)
locker._handle_verify_workout_result("verified", "1 session found")
assert locker.workout_data["type"] == "phone_verified"
locker.root.after.assert_called()
def test_not_verified_shows_retry(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On not_verified: show retry screen."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
"_show_verify_retry",
MagicMock(),
)
locker._handle_verify_workout_result(
"not_verified",
"No workout today",
)
locker._show_verify_retry.assert_called_once_with(
"No workout today",
)
def test_error_shows_retry(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""On error: show retry screen."""
locker = create_locker(mock_tk, tmp_path)
object.__setattr__(
locker,
"_show_verify_retry",
MagicMock(),
)
locker._handle_verify_workout_result("error", "ADB failed")
locker._show_verify_retry.assert_called_once_with("ADB failed")
class TestShowVerifyRetry:
"""Tests for _show_verify_retry."""
def test_shows_retry_and_close_buttons(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Show TRY AGAIN and Close buttons."""
locker = create_locker(mock_tk, tmp_path)
locker._show_verify_retry("No workout found")
# Verify container was cleared and buttons were packed
locker.container.first.winfo_children.return_value = []

View File

@ -5,13 +5,13 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker._temperature import TemperatureCheck
from screen_locker.screen_lock import ScreenLocker
from screen_locker.tests.conftest import create_locker, create_locker_relaxed_day
if TYPE_CHECKING:
from pathlib import Path
from screen_locker.screen_lock import ScreenLocker
# ---------------------------------------------------------------------------
# _check_today_state_exits: return True/False branches
# ---------------------------------------------------------------------------
@ -33,6 +33,7 @@ class TestCheckTodayStateExits:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Early bird upgrade success returns true."""
locker = self._make_locker(mock_tk, tmp_path)
with (
patch.object(locker, "_is_early_bird_pending", return_value=True),
@ -48,6 +49,7 @@ class TestCheckTodayStateExits:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Early bird upgrade fail returns false."""
locker = self._make_locker(mock_tk, tmp_path)
with (
patch.object(locker, "_is_early_bird_pending", return_value=True),
@ -63,6 +65,7 @@ class TestCheckTodayStateExits:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Early bird window active returns true."""
locker = self._make_locker(mock_tk, tmp_path)
with (
patch.object(locker, "_is_early_bird_pending", return_value=True),
@ -77,6 +80,7 @@ class TestCheckTodayStateExits:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Sick day auto upgrade returns true."""
locker = self._make_locker(mock_tk, tmp_path)
with (
patch.object(locker, "_is_early_bird_pending", return_value=False),
@ -112,6 +116,7 @@ class TestCheckTodayStateExits:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Workout skip today returns true."""
locker = self._make_locker(mock_tk, tmp_path)
with (
patch.object(locker, "_is_early_bird_pending", return_value=False),
@ -131,6 +136,7 @@ class TestCheckTodayStateExits:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Early bird time returns true."""
locker = self._make_locker(mock_tk, tmp_path)
with (
patch.object(locker, "_is_early_bird_pending", return_value=False),
@ -152,6 +158,7 @@ class TestCheckTodayStateExits:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""No exit conditions returns false."""
locker = self._make_locker(mock_tk, tmp_path)
with (
patch.object(locker, "_is_early_bird_pending", return_value=False),
@ -176,6 +183,7 @@ class TestCheckNonVerifyExitsScheduledSkip:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Scheduled skip return reached."""
locker = create_locker(mock_tk, tmp_path)
with patch.object(locker, "_is_scheduled_skip_today", return_value=True):
locker._check_non_verify_exits()
@ -191,6 +199,7 @@ class TestRelaxedDayCloseAndRun:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Relaxed day close and run use root directly."""
locker = create_locker_relaxed_day(mock_tk, tmp_path)
assert locker._lock is None
@ -205,115 +214,3 @@ class TestRelaxedDayCloseAndRun:
# _check_non_verify_exits: heat-skip branch (reached after weekly minimum
# is not met — the only remaining same-day skip is genuine extreme heat)
# ---------------------------------------------------------------------------
class TestHeatSkipBranch:
def test_not_too_hot_no_dialog_shown(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
with (
patch(
"screen_locker._startup_checks.has_weekly_minimum", return_value=False
),
patch(
"screen_locker._startup_checks.fetch_current_temp_with_status",
return_value=TemperatureCheck(temp_celsius=20.0, timed_out=False),
) as mock_hot,
patch.object(ScreenLocker, "_show_heat_skip_dialog") as mock_dialog,
):
create_locker(mock_tk, tmp_path, has_logged=False)
mock_hot.assert_called_once()
mock_dialog.assert_not_called()
mock_sys_exit.assert_not_called()
def test_too_hot_and_user_confirms_skip(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
with (
patch(
"screen_locker._startup_checks.has_weekly_minimum", return_value=False
),
patch(
"screen_locker._startup_checks.fetch_current_temp_with_status",
return_value=TemperatureCheck(temp_celsius=35.0, timed_out=False),
),
patch.object(ScreenLocker, "_show_heat_skip_dialog", return_value=True),
patch.object(ScreenLocker, "_save_heat_skip_log") as mock_save,
):
create_locker(mock_tk, tmp_path, has_logged=False)
mock_save.assert_called_once_with(35.0)
mock_sys_exit.assert_called_once_with(0)
def test_too_hot_but_user_declines_skip(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
with (
patch(
"screen_locker._startup_checks.has_weekly_minimum", return_value=False
),
patch(
"screen_locker._startup_checks.fetch_current_temp_with_status",
return_value=TemperatureCheck(temp_celsius=35.0, timed_out=False),
),
patch.object(ScreenLocker, "_show_heat_skip_dialog", return_value=False),
patch.object(ScreenLocker, "_save_heat_skip_log") as mock_save,
):
create_locker(mock_tk, tmp_path, has_logged=False)
mock_save.assert_not_called()
mock_sys_exit.assert_not_called()
def test_fetch_timed_out_defaults_to_lock_no_dialog(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A timed-out temperature check must fail closed, not skip the lock."""
with (
patch(
"screen_locker._startup_checks.has_weekly_minimum", return_value=False
),
patch(
"screen_locker._startup_checks.fetch_current_temp_with_status",
return_value=TemperatureCheck(temp_celsius=None, timed_out=True),
),
patch.object(ScreenLocker, "_show_heat_skip_dialog") as mock_dialog,
):
create_locker(mock_tk, tmp_path, has_logged=False)
mock_dialog.assert_not_called()
mock_sys_exit.assert_not_called()
def test_fetch_failed_defaults_to_lock_no_dialog(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A failed (non-timeout) temperature check must also fail closed."""
with (
patch(
"screen_locker._startup_checks.has_weekly_minimum", return_value=False
),
patch(
"screen_locker._startup_checks.fetch_current_temp_with_status",
return_value=TemperatureCheck(temp_celsius=None, timed_out=False),
),
patch.object(ScreenLocker, "_show_heat_skip_dialog") as mock_dialog,
):
create_locker(mock_tk, tmp_path, has_logged=False)
mock_dialog.assert_not_called()
mock_sys_exit.assert_not_called()

View File

@ -0,0 +1,130 @@
"""Tests for _check_today_state_exits and scheduled-skip branches."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from screen_locker._temperature import TemperatureCheck
from screen_locker.screen_lock import ScreenLocker
from screen_locker.tests.conftest import create_locker
if TYPE_CHECKING:
from pathlib import Path
class TestHeatSkipBranch:
"""HeatSkipBranch."""
def test_not_too_hot_no_dialog_shown(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Not too hot no dialog shown."""
with (
patch(
"screen_locker._startup_checks.has_weekly_minimum", return_value=False
),
patch(
"screen_locker._startup_checks.fetch_current_temp_with_status",
return_value=TemperatureCheck(temp_celsius=20.0, timed_out=False),
) as mock_hot,
patch.object(ScreenLocker, "_show_heat_skip_dialog") as mock_dialog,
):
create_locker(mock_tk, tmp_path, has_logged=False)
mock_hot.assert_called_once()
mock_dialog.assert_not_called()
mock_sys_exit.assert_not_called()
def test_too_hot_and_user_confirms_skip(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Too hot and user confirms skip."""
with (
patch(
"screen_locker._startup_checks.has_weekly_minimum", return_value=False
),
patch(
"screen_locker._startup_checks.fetch_current_temp_with_status",
return_value=TemperatureCheck(temp_celsius=35.0, timed_out=False),
),
patch.object(ScreenLocker, "_show_heat_skip_dialog", return_value=True),
patch.object(ScreenLocker, "_save_heat_skip_log") as mock_save,
):
create_locker(mock_tk, tmp_path, has_logged=False)
mock_save.assert_called_once_with(35.0)
mock_sys_exit.assert_called_once_with(0)
def test_too_hot_but_user_declines_skip(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Too hot but user declines skip."""
with (
patch(
"screen_locker._startup_checks.has_weekly_minimum", return_value=False
),
patch(
"screen_locker._startup_checks.fetch_current_temp_with_status",
return_value=TemperatureCheck(temp_celsius=35.0, timed_out=False),
),
patch.object(ScreenLocker, "_show_heat_skip_dialog", return_value=False),
patch.object(ScreenLocker, "_save_heat_skip_log") as mock_save,
):
create_locker(mock_tk, tmp_path, has_logged=False)
mock_save.assert_not_called()
mock_sys_exit.assert_not_called()
def test_fetch_timed_out_defaults_to_lock_no_dialog(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A timed-out temperature check must fail closed, not skip the lock."""
with (
patch(
"screen_locker._startup_checks.has_weekly_minimum", return_value=False
),
patch(
"screen_locker._startup_checks.fetch_current_temp_with_status",
return_value=TemperatureCheck(temp_celsius=None, timed_out=True),
),
patch.object(ScreenLocker, "_show_heat_skip_dialog") as mock_dialog,
):
create_locker(mock_tk, tmp_path, has_logged=False)
mock_dialog.assert_not_called()
mock_sys_exit.assert_not_called()
def test_fetch_failed_defaults_to_lock_no_dialog(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""A failed (non-timeout) temperature check must also fail closed."""
with (
patch(
"screen_locker._startup_checks.has_weekly_minimum", return_value=False
),
patch(
"screen_locker._startup_checks.fetch_current_temp_with_status",
return_value=TemperatureCheck(temp_celsius=None, timed_out=False),
),
patch.object(ScreenLocker, "_show_heat_skip_dialog") as mock_dialog,
):
create_locker(mock_tk, tmp_path, has_logged=False)
mock_dialog.assert_not_called()
mock_sys_exit.assert_not_called()