mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-29 21:34:11 +01:00
Compare commits
No commits in common. "5c27769642443420a6a6c72523c115f64b151733" and "4b4695e23ace999142f78745cc94e8b40a2dda9a" have entirely different histories.
5c27769642
...
4b4695e23a
@ -17,36 +17,8 @@ churn, not size alone — refactoring pays where code is read and changed often
|
|||||||
|
|
||||||
## Scope in this repo
|
## Scope in this repo
|
||||||
|
|
||||||
<!-- BEGIN GENERATED VIOLATIONS -->
|
- **71 files** currently exceed 250 lines (of 220 eligible files).
|
||||||
|
- **26,768 lines** sit in violation; 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.
|
|
||||||
|
|
||||||
| lines | commits/yr | kind | file |
|
|
||||||
| ----: | ---------: | :--- | :--- |
|
|
||||||
| 771 | 12 | code | `stronglift_replacement/workout_app/lib/screens/settings_screen.dart` |
|
|
||||||
| 781 | 10 | code | `stronglift_replacement/workout_app/lib/services/storage_service.dart` |
|
|
||||||
| 897 | 8 | code | `stronglift_replacement/workout_app/lib/screens/history_screen.dart` |
|
|
||||||
| 323 | 22 | code | `screen_locker/tests/conftest.py` |
|
|
||||||
| 480 | 12 | code | `stronglift_replacement/workout_app/test/screens/settings_screen_test.dart` |
|
|
||||||
| 633 | 9 | code | `stronglift_replacement/workout_app/lib/screens/workout_screen.dart` |
|
|
||||||
| 343 | 16 | code | `screen_locker/tests/test_init_and_log.py` |
|
|
||||||
| 740 | 7 | code | `stronglift_replacement/workout_app/test/services/workout_sync_service_test.dart` |
|
|
||||||
| 370 | 14 | code | `screen_locker/_ui_flows.py` |
|
|
||||||
| 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` |
|
|
||||||
| 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` |
|
|
||||||
|
|
||||||
_(46 further files over 250 lines not listed — re-run `python3 scripts/refresh_refactor_todo.py` for the current set.)_
|
|
||||||
|
|
||||||
<!-- END GENERATED VIOLATIONS -->
|
|
||||||
|
|
||||||
|
|
||||||
Exempt (do NOT split these):
|
Exempt (do NOT split these):
|
||||||
|
|
||||||
@ -56,6 +28,30 @@ Exempt (do NOT split these):
|
|||||||
- data files — `.json`, `.yaml`, `.csv`, wordlists and other data-ish `.txt`
|
- data files — `.json`, `.yaml`, `.csv`, wordlists and other data-ish `.txt`
|
||||||
(mean line length under 25 chars)
|
(mean line length under 25 chars)
|
||||||
|
|
||||||
|
## Violations, highest ROI first
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
| lines | commits/yr | kind | file |
|
||||||
|
| ----: | ---------: | :--- | :-------------------------------------------------------------------------------- |
|
||||||
|
| 390 | 48 | code | `screen_locker/screen_lock.py` |
|
||||||
|
| 771 | 12 | code | `stronglift_replacement/workout_app/lib/screens/settings_screen.dart` |
|
||||||
|
| 897 | 8 | code | `stronglift_replacement/workout_app/lib/screens/history_screen.dart` |
|
||||||
|
| 752 | 9 | code | `stronglift_replacement/workout_app/lib/services/storage_service.dart` |
|
||||||
|
| 319 | 21 | code | `screen_locker/tests/conftest.py` |
|
||||||
|
| 480 | 12 | code | `stronglift_replacement/workout_app/test/screens/settings_screen_test.dart` |
|
||||||
|
| 633 | 9 | code | `stronglift_replacement/workout_app/lib/screens/workout_screen.dart` |
|
||||||
|
| 343 | 16 | code | `screen_locker/tests/test_init_and_log.py` |
|
||||||
|
| 370 | 14 | code | `screen_locker/_ui_flows.py` |
|
||||||
|
| 377 | 12 | code | `screen_locker/_phone_verification.py` |
|
||||||
|
| 590 | 6 | code | `stronglift_replacement/workout_app/test/services/workout_sync_service_test.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` |
|
||||||
|
| 714 | 4 | code | `stronglift_replacement/workout_app/test/services/storage_service_test.dart` |
|
||||||
|
|
||||||
|
_(56 further files over 250 lines not listed — re-run the survey for the full set.)_
|
||||||
|
|
||||||
## How to split
|
## How to split
|
||||||
|
|
||||||
|
|||||||
@ -151,3 +151,106 @@ class TestAdbShell:
|
|||||||
["shell", "su", "-c", "ls /data"],
|
["shell", "su", "-c", "ls /data"],
|
||||||
)
|
)
|
||||||
assert success is True
|
assert success is True
|
||||||
|
|
||||||
|
|
||||||
|
class TestIsPhoneConnected:
|
||||||
|
"""Tests for _is_phone_connected method."""
|
||||||
|
|
||||||
|
def test_phone_connected(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test phone detected as connected."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
object.__setattr__(
|
||||||
|
locker,
|
||||||
|
"_run_adb",
|
||||||
|
MagicMock(
|
||||||
|
return_value=(
|
||||||
|
True,
|
||||||
|
"List of devices attached\nABC123\tdevice\n\n",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert locker._is_phone_connected() is True
|
||||||
|
|
||||||
|
def test_phone_not_connected(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test no phone connected."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
object.__setattr__(
|
||||||
|
locker,
|
||||||
|
"_run_adb",
|
||||||
|
MagicMock(
|
||||||
|
return_value=(True, "List of devices attached\n\n"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
object.__setattr__(
|
||||||
|
locker,
|
||||||
|
"_try_wireless_reconnect",
|
||||||
|
MagicMock(
|
||||||
|
return_value=False,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert locker._is_phone_connected() is False
|
||||||
|
|
||||||
|
def test_phone_offline(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test phone connected but offline."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
object.__setattr__(
|
||||||
|
locker,
|
||||||
|
"_run_adb",
|
||||||
|
MagicMock(
|
||||||
|
return_value=(
|
||||||
|
True,
|
||||||
|
"List of devices attached\nABC123\toffline\n\n",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
object.__setattr__(
|
||||||
|
locker,
|
||||||
|
"_try_wireless_reconnect",
|
||||||
|
MagicMock(
|
||||||
|
return_value=False,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert locker._is_phone_connected() is False
|
||||||
|
|
||||||
|
def test_adb_command_fails(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test ADB command failure."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
object.__setattr__(
|
||||||
|
locker,
|
||||||
|
"_run_adb",
|
||||||
|
MagicMock(
|
||||||
|
return_value=(False, ""),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
object.__setattr__(
|
||||||
|
locker,
|
||||||
|
"_try_wireless_reconnect",
|
||||||
|
MagicMock(
|
||||||
|
return_value=False,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert locker._is_phone_connected() is False
|
||||||
|
|||||||
@ -1,115 +0,0 @@
|
|||||||
"""Tests for ADB commands, phone connection, and database operations."""
|
|
||||||
# pylint: disable=protected-access,unused-argument
|
|
||||||
|
|
||||||
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 TestIsPhoneConnected:
|
|
||||||
"""Tests for _is_phone_connected method."""
|
|
||||||
|
|
||||||
def test_phone_connected(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test phone detected as connected."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
object.__setattr__(
|
|
||||||
locker,
|
|
||||||
"_run_adb",
|
|
||||||
MagicMock(
|
|
||||||
return_value=(
|
|
||||||
True,
|
|
||||||
"List of devices attached\nABC123\tdevice\n\n",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
assert locker._is_phone_connected() is True
|
|
||||||
|
|
||||||
def test_phone_not_connected(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test no phone connected."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
object.__setattr__(
|
|
||||||
locker,
|
|
||||||
"_run_adb",
|
|
||||||
MagicMock(
|
|
||||||
return_value=(True, "List of devices attached\n\n"),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
object.__setattr__(
|
|
||||||
locker,
|
|
||||||
"_try_wireless_reconnect",
|
|
||||||
MagicMock(
|
|
||||||
return_value=False,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
assert locker._is_phone_connected() is False
|
|
||||||
|
|
||||||
def test_phone_offline(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test phone connected but offline."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
object.__setattr__(
|
|
||||||
locker,
|
|
||||||
"_run_adb",
|
|
||||||
MagicMock(
|
|
||||||
return_value=(
|
|
||||||
True,
|
|
||||||
"List of devices attached\nABC123\toffline\n\n",
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
object.__setattr__(
|
|
||||||
locker,
|
|
||||||
"_try_wireless_reconnect",
|
|
||||||
MagicMock(
|
|
||||||
return_value=False,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
assert locker._is_phone_connected() is False
|
|
||||||
|
|
||||||
def test_adb_command_fails(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test ADB command failure."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
object.__setattr__(
|
|
||||||
locker,
|
|
||||||
"_run_adb",
|
|
||||||
MagicMock(
|
|
||||||
return_value=(False, ""),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
object.__setattr__(
|
|
||||||
locker,
|
|
||||||
"_try_wireless_reconnect",
|
|
||||||
MagicMock(
|
|
||||||
return_value=False,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
assert locker._is_phone_connected() is False
|
|
||||||
@ -7,7 +7,10 @@ import json
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from screen_locker import _compliance_state
|
||||||
from screen_locker._compliance_state import (
|
from screen_locker._compliance_state import (
|
||||||
|
AutoUpgradeOpportunity,
|
||||||
|
describe_auto_upgrade_opportunity,
|
||||||
has_logged_today,
|
has_logged_today,
|
||||||
is_early_bird_pending,
|
is_early_bird_pending,
|
||||||
is_scheduled_skip_today,
|
is_scheduled_skip_today,
|
||||||
@ -27,29 +30,24 @@ class TestIsScheduledSkipToday:
|
|||||||
"""Mirrors test_scheduled_skip.py's coverage, for the standalone function."""
|
"""Mirrors test_scheduled_skip.py's coverage, for the standalone function."""
|
||||||
|
|
||||||
def test_missing_file(self, tmp_path: Path) -> None:
|
def test_missing_file(self, tmp_path: Path) -> None:
|
||||||
"""A missing skips file means today is not a scheduled skip."""
|
|
||||||
assert is_scheduled_skip_today(tmp_path / "skips.json") is False
|
assert is_scheduled_skip_today(tmp_path / "skips.json") is False
|
||||||
|
|
||||||
def test_today_listed(self, tmp_path: Path) -> None:
|
def test_today_listed(self, tmp_path: Path) -> None:
|
||||||
"""Today's date in the skips list makes it a scheduled skip."""
|
|
||||||
skip_file = tmp_path / "skips.json"
|
skip_file = tmp_path / "skips.json"
|
||||||
skip_file.write_text(json.dumps([_today()]))
|
skip_file.write_text(json.dumps([_today()]))
|
||||||
assert is_scheduled_skip_today(skip_file) is True
|
assert is_scheduled_skip_today(skip_file) is True
|
||||||
|
|
||||||
def test_today_not_listed(self, tmp_path: Path) -> None:
|
def test_today_not_listed(self, tmp_path: Path) -> None:
|
||||||
"""A list without today is not a scheduled skip."""
|
|
||||||
skip_file = tmp_path / "skips.json"
|
skip_file = tmp_path / "skips.json"
|
||||||
skip_file.write_text(json.dumps(["1999-01-01"]))
|
skip_file.write_text(json.dumps(["1999-01-01"]))
|
||||||
assert is_scheduled_skip_today(skip_file) is False
|
assert is_scheduled_skip_today(skip_file) is False
|
||||||
|
|
||||||
def test_corrupt_json(self, tmp_path: Path) -> None:
|
def test_corrupt_json(self, tmp_path: Path) -> None:
|
||||||
"""Unparsable JSON fails closed: not a skip."""
|
|
||||||
skip_file = tmp_path / "skips.json"
|
skip_file = tmp_path / "skips.json"
|
||||||
skip_file.write_text("{bad}")
|
skip_file.write_text("{bad}")
|
||||||
assert is_scheduled_skip_today(skip_file) is False
|
assert is_scheduled_skip_today(skip_file) is False
|
||||||
|
|
||||||
def test_explicit_today_override(self, tmp_path: Path) -> None:
|
def test_explicit_today_override(self, tmp_path: Path) -> None:
|
||||||
"""The `today` argument overrides the real date."""
|
|
||||||
skip_file = tmp_path / "skips.json"
|
skip_file = tmp_path / "skips.json"
|
||||||
skip_file.write_text(json.dumps(["2020-05-05"]))
|
skip_file.write_text(json.dumps(["2020-05-05"]))
|
||||||
assert is_scheduled_skip_today(skip_file, today="2020-05-05") is True
|
assert is_scheduled_skip_today(skip_file, today="2020-05-05") is True
|
||||||
@ -59,23 +57,19 @@ class TestHasLoggedToday:
|
|||||||
"""Mirrors test_init_and_log.py's HMAC branches, for the standalone function."""
|
"""Mirrors test_init_and_log.py's HMAC branches, for the standalone function."""
|
||||||
|
|
||||||
def test_missing_file(self, tmp_path: Path) -> None:
|
def test_missing_file(self, tmp_path: Path) -> None:
|
||||||
"""A missing log means nothing was logged today."""
|
|
||||||
assert has_logged_today(tmp_path / "log.json") is False
|
assert has_logged_today(tmp_path / "log.json") is False
|
||||||
|
|
||||||
def test_corrupt_json(self, tmp_path: Path) -> None:
|
def test_corrupt_json(self, tmp_path: Path) -> None:
|
||||||
"""Unparsable JSON fails closed: nothing logged."""
|
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
log_file.write_text("{bad}")
|
log_file.write_text("{bad}")
|
||||||
assert has_logged_today(log_file) is False
|
assert has_logged_today(log_file) is False
|
||||||
|
|
||||||
def test_no_entry_for_today(self, tmp_path: Path) -> None:
|
def test_no_entry_for_today(self, tmp_path: Path) -> None:
|
||||||
"""An entry for another day does not count as today's."""
|
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
log_file.write_text(json.dumps({"1999-01-01": {}}))
|
log_file.write_text(json.dumps({"1999-01-01": {}}))
|
||||||
assert has_logged_today(log_file) is False
|
assert has_logged_today(log_file) is False
|
||||||
|
|
||||||
def test_valid_hmac(self, tmp_path: Path) -> None:
|
def test_valid_hmac(self, tmp_path: Path) -> None:
|
||||||
"""A correctly signed entry for today counts."""
|
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
log_file.write_text(json.dumps({_today(): {"hmac": "sig"}}))
|
log_file.write_text(json.dumps({_today(): {"hmac": "sig"}}))
|
||||||
with patch(
|
with patch(
|
||||||
@ -84,7 +78,6 @@ class TestHasLoggedToday:
|
|||||||
assert has_logged_today(log_file) is True
|
assert has_logged_today(log_file) is True
|
||||||
|
|
||||||
def test_unsigned_accepted_when_key_unavailable(self, tmp_path: Path) -> None:
|
def test_unsigned_accepted_when_key_unavailable(self, tmp_path: Path) -> None:
|
||||||
"""With no HMAC key on the machine, an unsigned entry is accepted."""
|
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
log_file.write_text(json.dumps({_today(): {}}))
|
log_file.write_text(json.dumps({_today(): {}}))
|
||||||
with (
|
with (
|
||||||
@ -98,7 +91,6 @@ class TestHasLoggedToday:
|
|||||||
assert has_logged_today(log_file) is True
|
assert has_logged_today(log_file) is True
|
||||||
|
|
||||||
def test_rejected_when_key_available(self, tmp_path: Path) -> None:
|
def test_rejected_when_key_available(self, tmp_path: Path) -> None:
|
||||||
"""With a key available, an unsigned entry is rejected as tampering."""
|
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
log_file.write_text(json.dumps({_today(): {}}))
|
log_file.write_text(json.dumps({_today(): {}}))
|
||||||
with (
|
with (
|
||||||
@ -112,7 +104,6 @@ class TestHasLoggedToday:
|
|||||||
assert has_logged_today(log_file) is False
|
assert has_logged_today(log_file) is False
|
||||||
|
|
||||||
def test_rejected_when_signed_but_invalid(self, tmp_path: Path) -> None:
|
def test_rejected_when_signed_but_invalid(self, tmp_path: Path) -> None:
|
||||||
"""A signature that does not verify is rejected."""
|
|
||||||
log_file = tmp_path / "log.json"
|
log_file = tmp_path / "log.json"
|
||||||
log_file.write_text(json.dumps({_today(): {"hmac": "tampered"}}))
|
log_file.write_text(json.dumps({_today(): {"hmac": "tampered"}}))
|
||||||
with (
|
with (
|
||||||
@ -130,29 +121,24 @@ class TestIsEarlyBirdPending:
|
|||||||
"""Mirrors test_early_bird.py's HMAC branches, for the standalone function."""
|
"""Mirrors test_early_bird.py's HMAC branches, for the standalone function."""
|
||||||
|
|
||||||
def test_missing_file(self, tmp_path: Path) -> None:
|
def test_missing_file(self, tmp_path: Path) -> None:
|
||||||
"""A missing pending file means no early bird is pending."""
|
|
||||||
assert is_early_bird_pending(tmp_path / "pending.json") is False
|
assert is_early_bird_pending(tmp_path / "pending.json") is False
|
||||||
|
|
||||||
def test_corrupt_json(self, tmp_path: Path) -> None:
|
def test_corrupt_json(self, tmp_path: Path) -> None:
|
||||||
"""Unparsable JSON fails closed: nothing pending."""
|
|
||||||
pending_file = tmp_path / "pending.json"
|
pending_file = tmp_path / "pending.json"
|
||||||
pending_file.write_text("{bad}")
|
pending_file.write_text("{bad}")
|
||||||
assert is_early_bird_pending(pending_file) is False
|
assert is_early_bird_pending(pending_file) is False
|
||||||
|
|
||||||
def test_not_a_dict(self, tmp_path: Path) -> None:
|
def test_not_a_dict(self, tmp_path: Path) -> None:
|
||||||
"""A JSON list where a dict is expected fails closed."""
|
|
||||||
pending_file = tmp_path / "pending.json"
|
pending_file = tmp_path / "pending.json"
|
||||||
pending_file.write_text(json.dumps(["not", "a", "dict"]))
|
pending_file.write_text(json.dumps(["not", "a", "dict"]))
|
||||||
assert is_early_bird_pending(pending_file) is False
|
assert is_early_bird_pending(pending_file) is False
|
||||||
|
|
||||||
def test_stale_date(self, tmp_path: Path) -> None:
|
def test_stale_date(self, tmp_path: Path) -> None:
|
||||||
"""A pending record from an earlier day no longer applies."""
|
|
||||||
pending_file = tmp_path / "pending.json"
|
pending_file = tmp_path / "pending.json"
|
||||||
pending_file.write_text(json.dumps({"date": "2000-01-01", "hmac": "sig"}))
|
pending_file.write_text(json.dumps({"date": "2000-01-01", "hmac": "sig"}))
|
||||||
assert is_early_bird_pending(pending_file) is False
|
assert is_early_bird_pending(pending_file) is False
|
||||||
|
|
||||||
def test_valid_hmac(self, tmp_path: Path) -> None:
|
def test_valid_hmac(self, tmp_path: Path) -> None:
|
||||||
"""A correctly signed pending record for today counts."""
|
|
||||||
pending_file = tmp_path / "pending.json"
|
pending_file = tmp_path / "pending.json"
|
||||||
pending_file.write_text(json.dumps({"date": _today(), "hmac": "sig"}))
|
pending_file.write_text(json.dumps({"date": _today(), "hmac": "sig"}))
|
||||||
with patch(
|
with patch(
|
||||||
@ -161,7 +147,6 @@ class TestIsEarlyBirdPending:
|
|||||||
assert is_early_bird_pending(pending_file) is True
|
assert is_early_bird_pending(pending_file) is True
|
||||||
|
|
||||||
def test_unsigned_accepted_when_key_unavailable(self, tmp_path: Path) -> None:
|
def test_unsigned_accepted_when_key_unavailable(self, tmp_path: Path) -> None:
|
||||||
"""With no HMAC key, an unsigned pending record is accepted."""
|
|
||||||
pending_file = tmp_path / "pending.json"
|
pending_file = tmp_path / "pending.json"
|
||||||
pending_file.write_text(json.dumps({"date": _today()}))
|
pending_file.write_text(json.dumps({"date": _today()}))
|
||||||
with (
|
with (
|
||||||
@ -175,7 +160,6 @@ class TestIsEarlyBirdPending:
|
|||||||
assert is_early_bird_pending(pending_file) is True
|
assert is_early_bird_pending(pending_file) is True
|
||||||
|
|
||||||
def test_rejected_when_key_available(self, tmp_path: Path) -> None:
|
def test_rejected_when_key_available(self, tmp_path: Path) -> None:
|
||||||
"""With a key available, an unsigned pending record is rejected."""
|
|
||||||
pending_file = tmp_path / "pending.json"
|
pending_file = tmp_path / "pending.json"
|
||||||
pending_file.write_text(json.dumps({"date": _today()}))
|
pending_file.write_text(json.dumps({"date": _today()}))
|
||||||
with (
|
with (
|
||||||
@ -189,7 +173,6 @@ class TestIsEarlyBirdPending:
|
|||||||
assert is_early_bird_pending(pending_file) is False
|
assert is_early_bird_pending(pending_file) is False
|
||||||
|
|
||||||
def test_rejected_when_signed_but_invalid(self, tmp_path: Path) -> None:
|
def test_rejected_when_signed_but_invalid(self, tmp_path: Path) -> None:
|
||||||
"""A pending record whose signature fails to verify is rejected."""
|
|
||||||
pending_file = tmp_path / "pending.json"
|
pending_file = tmp_path / "pending.json"
|
||||||
pending_file.write_text(json.dumps({"date": _today(), "hmac": "bad"}))
|
pending_file.write_text(json.dumps({"date": _today(), "hmac": "bad"}))
|
||||||
with (
|
with (
|
||||||
@ -204,21 +187,89 @@ class TestIsEarlyBirdPending:
|
|||||||
|
|
||||||
|
|
||||||
class TestIsSickDayToday:
|
class TestIsSickDayToday:
|
||||||
"""Reading today's sick-day status out of the sick history."""
|
|
||||||
|
|
||||||
"""Thin wrapper around _sick_tracker.is_sick_day."""
|
"""Thin wrapper around _sick_tracker.is_sick_day."""
|
||||||
|
|
||||||
def test_true_when_listed(self) -> None:
|
def test_true_when_listed(self) -> None:
|
||||||
"""Today present in the history is a sick day."""
|
|
||||||
history = SickHistory(sick_days=[_today()])
|
history = SickHistory(sick_days=[_today()])
|
||||||
assert is_sick_day_today(history) is True
|
assert is_sick_day_today(history) is True
|
||||||
|
|
||||||
def test_false_when_not_listed(self) -> None:
|
def test_false_when_not_listed(self) -> None:
|
||||||
"""Today absent from the history is not a sick day."""
|
|
||||||
history = SickHistory(sick_days=["1999-01-01"])
|
history = SickHistory(sick_days=["1999-01-01"])
|
||||||
assert is_sick_day_today(history) is False
|
assert is_sick_day_today(history) is False
|
||||||
|
|
||||||
def test_explicit_today_override(self) -> None:
|
def test_explicit_today_override(self) -> None:
|
||||||
"""The `today` argument overrides the real date."""
|
|
||||||
history = SickHistory(sick_days=["2020-05-05"])
|
history = SickHistory(sick_days=["2020-05-05"])
|
||||||
assert is_sick_day_today(history, today="2020-05-05") is True
|
assert is_sick_day_today(history, today="2020-05-05") is True
|
||||||
|
|
||||||
|
|
||||||
|
class TestEarlyBirdWindowOpen:
|
||||||
|
"""Direct tests for the module-private, deliberately independent reimplementation."""
|
||||||
|
|
||||||
|
def test_before_window(self) -> None:
|
||||||
|
assert (
|
||||||
|
_compliance_state._early_bird_window_open(extended=False, local_minutes=299)
|
||||||
|
is False
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_at_start(self) -> None:
|
||||||
|
assert (
|
||||||
|
_compliance_state._early_bird_window_open(extended=False, local_minutes=300)
|
||||||
|
is True
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_before_end(self) -> None:
|
||||||
|
assert (
|
||||||
|
_compliance_state._early_bird_window_open(extended=False, local_minutes=509)
|
||||||
|
is True
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_at_end_exclusive(self) -> None:
|
||||||
|
assert (
|
||||||
|
_compliance_state._early_bird_window_open(extended=False, local_minutes=510)
|
||||||
|
is False
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_extended_before_end(self) -> None:
|
||||||
|
assert (
|
||||||
|
_compliance_state._early_bird_window_open(extended=True, local_minutes=539)
|
||||||
|
is True
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_extended_at_end_exclusive(self) -> None:
|
||||||
|
assert (
|
||||||
|
_compliance_state._early_bird_window_open(extended=True, local_minutes=540)
|
||||||
|
is False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestDescribeAutoUpgradeOpportunity:
|
||||||
|
"""The 3 possible outcomes: expired early-bird, sick day, or none."""
|
||||||
|
|
||||||
|
def test_expired_early_bird(self) -> None:
|
||||||
|
result = describe_auto_upgrade_opportunity(
|
||||||
|
early_bird_pending=True, early_bird_window_open=False, is_sick_day=False
|
||||||
|
)
|
||||||
|
assert result == AutoUpgradeOpportunity(
|
||||||
|
would_attempt=True, via="early_bird_expired", reason=result.reason
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_sick_day(self) -> None:
|
||||||
|
result = describe_auto_upgrade_opportunity(
|
||||||
|
early_bird_pending=False, early_bird_window_open=False, is_sick_day=True
|
||||||
|
)
|
||||||
|
assert result.would_attempt is True
|
||||||
|
assert result.via == "sick_day"
|
||||||
|
|
||||||
|
def test_sick_day_takes_second_priority_when_pending_still_open(self) -> None:
|
||||||
|
"""pending+open doesn't count as expired, so sick_day is still checked."""
|
||||||
|
result = describe_auto_upgrade_opportunity(
|
||||||
|
early_bird_pending=True, early_bird_window_open=True, is_sick_day=True
|
||||||
|
)
|
||||||
|
assert result.via == "sick_day"
|
||||||
|
|
||||||
|
def test_none(self) -> None:
|
||||||
|
result = describe_auto_upgrade_opportunity(
|
||||||
|
early_bird_pending=False, early_bird_window_open=False, is_sick_day=False
|
||||||
|
)
|
||||||
|
assert result.would_attempt is False
|
||||||
|
assert result.via == "none"
|
||||||
|
|||||||
@ -1,44 +0,0 @@
|
|||||||
"""Tests for the pure, read-only predicates in _compliance_state.py."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from screen_locker._compliance_state import (
|
|
||||||
AutoUpgradeOpportunity,
|
|
||||||
describe_auto_upgrade_opportunity,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestDescribeAutoUpgradeOpportunity:
|
|
||||||
"""The 3 possible outcomes: expired early-bird, sick day, or none."""
|
|
||||||
|
|
||||||
def test_expired_early_bird(self) -> None:
|
|
||||||
"""Expired early bird."""
|
|
||||||
result = describe_auto_upgrade_opportunity(
|
|
||||||
early_bird_pending=True, early_bird_window_open=False, is_sick_day=False
|
|
||||||
)
|
|
||||||
assert result == AutoUpgradeOpportunity(
|
|
||||||
would_attempt=True, via="early_bird_expired", reason=result.reason
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_sick_day(self) -> None:
|
|
||||||
"""Sick day."""
|
|
||||||
result = describe_auto_upgrade_opportunity(
|
|
||||||
early_bird_pending=False, early_bird_window_open=False, is_sick_day=True
|
|
||||||
)
|
|
||||||
assert result.would_attempt is True
|
|
||||||
assert result.via == "sick_day"
|
|
||||||
|
|
||||||
def test_sick_day_takes_second_priority_when_pending_still_open(self) -> None:
|
|
||||||
"""pending+open doesn't count as expired, so sick_day is still checked."""
|
|
||||||
result = describe_auto_upgrade_opportunity(
|
|
||||||
early_bird_pending=True, early_bird_window_open=True, is_sick_day=True
|
|
||||||
)
|
|
||||||
assert result.via == "sick_day"
|
|
||||||
|
|
||||||
def test_none(self) -> None:
|
|
||||||
"""None."""
|
|
||||||
result = describe_auto_upgrade_opportunity(
|
|
||||||
early_bird_pending=False, early_bird_window_open=False, is_sick_day=False
|
|
||||||
)
|
|
||||||
assert result.would_attempt is False
|
|
||||||
assert result.via == "none"
|
|
||||||
@ -1,53 +0,0 @@
|
|||||||
"""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
|
|
||||||
)
|
|
||||||
@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import TYPE_CHECKING
|
from datetime import datetime, timezone
|
||||||
|
import json
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from screen_locker.tests.conftest import (
|
from screen_locker.tests.conftest import (
|
||||||
@ -145,3 +147,185 @@ class TestIsEarlyBirdTime:
|
|||||||
"""Midnight (0 min) is outside the window."""
|
"""Midnight (0 min) is outside the window."""
|
||||||
locker = self._locker(mock_tk, tmp_path, 0)
|
locker = self._locker(mock_tk, tmp_path, 0)
|
||||||
assert locker._is_early_bird_time() is False
|
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()
|
||||||
|
|||||||
@ -1,197 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@ -11,7 +11,10 @@ from screen_locker._extra_benefits import (
|
|||||||
_load_state,
|
_load_state,
|
||||||
_save_state,
|
_save_state,
|
||||||
current_streak,
|
current_streak,
|
||||||
|
has_extended_early_bird,
|
||||||
|
preview_bonus_if_week_ended_now,
|
||||||
process_week_transition,
|
process_week_transition,
|
||||||
|
weekly_shutdown_bonus_hours,
|
||||||
)
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
@ -235,3 +238,74 @@ class TestCurrentStreak:
|
|||||||
f = tmp_path / "state.json"
|
f = tmp_path / "state.json"
|
||||||
f.write_text(json.dumps({"consecutive_5plus_weeks": 5}))
|
f.write_text(json.dumps({"consecutive_5plus_weeks": 5}))
|
||||||
assert current_streak(f) == 5
|
assert current_streak(f) == 5
|
||||||
|
|
||||||
|
|
||||||
|
class TestWeeklyShutdownBonusHours:
|
||||||
|
"""Tests for weekly_shutdown_bonus_hours."""
|
||||||
|
|
||||||
|
def test_returns_zero_when_missing(self, tmp_path: Path) -> None:
|
||||||
|
"""No state file → 0."""
|
||||||
|
f = tmp_path / "state.json"
|
||||||
|
assert weekly_shutdown_bonus_hours(f) == 0
|
||||||
|
|
||||||
|
def test_returns_current_week_bonus(self, tmp_path: Path) -> None:
|
||||||
|
"""Returns the banked bonus for the current ISO week."""
|
||||||
|
now = datetime.now(tz=timezone.utc).astimezone()
|
||||||
|
year, week, _ = now.isocalendar()
|
||||||
|
current_week = f"{year}-W{week:02d}"
|
||||||
|
f = tmp_path / "state.json"
|
||||||
|
f.write_text(json.dumps({"weekly_shutdown_bonus_hours": {current_week: 3}}))
|
||||||
|
assert weekly_shutdown_bonus_hours(f) == 3
|
||||||
|
|
||||||
|
def test_ignores_other_weeks(self, tmp_path: Path) -> None:
|
||||||
|
"""A bonus banked for a different ISO week is not returned."""
|
||||||
|
f = tmp_path / "state.json"
|
||||||
|
f.write_text(json.dumps({"weekly_shutdown_bonus_hours": {"2020-W01": 5}}))
|
||||||
|
assert weekly_shutdown_bonus_hours(f) == 0
|
||||||
|
|
||||||
|
|
||||||
|
class TestPreviewBonusIfWeekEndedNow:
|
||||||
|
"""Tests for preview_bonus_if_week_ended_now — pure threshold math."""
|
||||||
|
|
||||||
|
def test_below_threshold_returns_zero(self) -> None:
|
||||||
|
"""< 5 workouts: no streak increment, no bonus (line 67 branch)."""
|
||||||
|
assert preview_bonus_if_week_ended_now(3, current_streak=2) == (0, 0)
|
||||||
|
|
||||||
|
def test_at_threshold_awards_streak_and_bonus(self) -> None:
|
||||||
|
"""Exactly 5 workouts: streak+1, bonus = count - 4."""
|
||||||
|
assert preview_bonus_if_week_ended_now(5, current_streak=0) == (1, 1)
|
||||||
|
|
||||||
|
def test_above_threshold_awards_larger_bonus(self) -> None:
|
||||||
|
"""7 workouts: bonus = 7 - 4 = 3."""
|
||||||
|
assert preview_bonus_if_week_ended_now(7, current_streak=0) == (1, 3)
|
||||||
|
|
||||||
|
def test_milestone_streak_adds_extra_hour(self) -> None:
|
||||||
|
"""Streak reaching a multiple of 4 adds +1h on top of the base bonus."""
|
||||||
|
assert preview_bonus_if_week_ended_now(5, current_streak=3) == (4, 2)
|
||||||
|
|
||||||
|
|
||||||
|
class TestHasExtendedEarlyBird:
|
||||||
|
"""Tests for has_extended_early_bird."""
|
||||||
|
|
||||||
|
def test_returns_false_when_current_week_not_in_list(self, tmp_path: Path) -> None:
|
||||||
|
"""Current ISO week absent from list → False."""
|
||||||
|
f = tmp_path / "state.json"
|
||||||
|
f.write_text(json.dumps({"extended_early_bird_iso_weeks": ["2020-W01"]}))
|
||||||
|
assert has_extended_early_bird(f) is False
|
||||||
|
|
||||||
|
def test_returns_true_when_current_week_is_in_list(self, tmp_path: Path) -> None:
|
||||||
|
"""Current ISO week present in list → True."""
|
||||||
|
now = datetime.now(tz=timezone.utc).astimezone()
|
||||||
|
year, week, _ = now.isocalendar()
|
||||||
|
current_week = f"{year}-W{week:02d}"
|
||||||
|
f = tmp_path / "state.json"
|
||||||
|
f.write_text(json.dumps({"extended_early_bird_iso_weeks": [current_week]}))
|
||||||
|
assert has_extended_early_bird(f) is True
|
||||||
|
|
||||||
|
def test_explicit_today_override(self, tmp_path: Path) -> None:
|
||||||
|
"""An explicit `today` is used instead of the real wall clock."""
|
||||||
|
f = tmp_path / "state.json"
|
||||||
|
f.write_text(json.dumps({"extended_early_bird_iso_weeks": ["2024-W01"]}))
|
||||||
|
fixed_today = datetime(2024, 1, 5, tzinfo=timezone.utc)
|
||||||
|
assert has_extended_early_bird(f, today=fixed_today) is True
|
||||||
|
assert has_extended_early_bird(f) is False
|
||||||
|
|||||||
@ -1,87 +0,0 @@
|
|||||||
"""Tests for _extra_benefits module (streak, shutdown bonus, EB extension)."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
import json
|
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
|
|
||||||
from screen_locker._extra_benefits import (
|
|
||||||
has_extended_early_bird,
|
|
||||||
preview_bonus_if_week_ended_now,
|
|
||||||
weekly_shutdown_bonus_hours,
|
|
||||||
)
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
|
|
||||||
class TestWeeklyShutdownBonusHours:
|
|
||||||
"""Tests for weekly_shutdown_bonus_hours."""
|
|
||||||
|
|
||||||
def test_returns_zero_when_missing(self, tmp_path: Path) -> None:
|
|
||||||
"""No state file → 0."""
|
|
||||||
f = tmp_path / "state.json"
|
|
||||||
assert weekly_shutdown_bonus_hours(f) == 0
|
|
||||||
|
|
||||||
def test_returns_current_week_bonus(self, tmp_path: Path) -> None:
|
|
||||||
"""Returns the banked bonus for the current ISO week."""
|
|
||||||
now = datetime.now(tz=timezone.utc).astimezone()
|
|
||||||
year, week, _ = now.isocalendar()
|
|
||||||
current_week = f"{year}-W{week:02d}"
|
|
||||||
f = tmp_path / "state.json"
|
|
||||||
f.write_text(json.dumps({"weekly_shutdown_bonus_hours": {current_week: 3}}))
|
|
||||||
assert weekly_shutdown_bonus_hours(f) == 3
|
|
||||||
|
|
||||||
def test_ignores_other_weeks(self, tmp_path: Path) -> None:
|
|
||||||
"""A bonus banked for a different ISO week is not returned."""
|
|
||||||
f = tmp_path / "state.json"
|
|
||||||
f.write_text(json.dumps({"weekly_shutdown_bonus_hours": {"2020-W01": 5}}))
|
|
||||||
assert weekly_shutdown_bonus_hours(f) == 0
|
|
||||||
|
|
||||||
|
|
||||||
class TestPreviewBonusIfWeekEndedNow:
|
|
||||||
"""Tests for preview_bonus_if_week_ended_now — pure threshold math."""
|
|
||||||
|
|
||||||
def test_below_threshold_returns_zero(self) -> None:
|
|
||||||
"""< 5 workouts: no streak increment, no bonus (line 67 branch)."""
|
|
||||||
assert preview_bonus_if_week_ended_now(3, current_streak=2) == (0, 0)
|
|
||||||
|
|
||||||
def test_at_threshold_awards_streak_and_bonus(self) -> None:
|
|
||||||
"""Exactly 5 workouts: streak+1, bonus = count - 4."""
|
|
||||||
assert preview_bonus_if_week_ended_now(5, current_streak=0) == (1, 1)
|
|
||||||
|
|
||||||
def test_above_threshold_awards_larger_bonus(self) -> None:
|
|
||||||
"""7 workouts: bonus = 7 - 4 = 3."""
|
|
||||||
assert preview_bonus_if_week_ended_now(7, current_streak=0) == (1, 3)
|
|
||||||
|
|
||||||
def test_milestone_streak_adds_extra_hour(self) -> None:
|
|
||||||
"""Streak reaching a multiple of 4 adds +1h on top of the base bonus."""
|
|
||||||
assert preview_bonus_if_week_ended_now(5, current_streak=3) == (4, 2)
|
|
||||||
|
|
||||||
|
|
||||||
class TestHasExtendedEarlyBird:
|
|
||||||
"""Tests for has_extended_early_bird."""
|
|
||||||
|
|
||||||
def test_returns_false_when_current_week_not_in_list(self, tmp_path: Path) -> None:
|
|
||||||
"""Current ISO week absent from list → False."""
|
|
||||||
f = tmp_path / "state.json"
|
|
||||||
f.write_text(json.dumps({"extended_early_bird_iso_weeks": ["2020-W01"]}))
|
|
||||||
assert has_extended_early_bird(f) is False
|
|
||||||
|
|
||||||
def test_returns_true_when_current_week_is_in_list(self, tmp_path: Path) -> None:
|
|
||||||
"""Current ISO week present in list → True."""
|
|
||||||
now = datetime.now(tz=timezone.utc).astimezone()
|
|
||||||
year, week, _ = now.isocalendar()
|
|
||||||
current_week = f"{year}-W{week:02d}"
|
|
||||||
f = tmp_path / "state.json"
|
|
||||||
f.write_text(json.dumps({"extended_early_bird_iso_weeks": [current_week]}))
|
|
||||||
assert has_extended_early_bird(f) is True
|
|
||||||
|
|
||||||
def test_explicit_today_override(self, tmp_path: Path) -> None:
|
|
||||||
"""An explicit `today` is used instead of the real wall clock."""
|
|
||||||
f = tmp_path / "state.json"
|
|
||||||
f.write_text(json.dumps({"extended_early_bird_iso_weeks": ["2024-W01"]}))
|
|
||||||
fixed_today = datetime(2024, 1, 5, tzinfo=timezone.utc)
|
|
||||||
assert has_extended_early_bird(f, today=fixed_today) is True
|
|
||||||
assert has_extended_early_bird(f) is False
|
|
||||||
@ -5,7 +5,7 @@ from __future__ import annotations
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
import json
|
import json
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING, Any
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@ -221,3 +221,123 @@ class TestHasLoggedToday:
|
|||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker.log_file = log_file
|
locker.log_file = log_file
|
||||||
assert locker.has_logged_today() is False
|
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()
|
||||||
|
|||||||
@ -1,133 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@ -6,18 +6,24 @@ from __future__ import annotations
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
import json
|
import json
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
from crdt_sync import GitHubSyncError, RepoNotFoundError
|
||||||
|
|
||||||
|
from screen_locker import _manual_push
|
||||||
from screen_locker._manual_push import (
|
from screen_locker._manual_push import (
|
||||||
|
PushResult,
|
||||||
_decode_log,
|
_decode_log,
|
||||||
_encode_log,
|
_encode_log,
|
||||||
_entry_wall_ms,
|
_entry_wall_ms,
|
||||||
|
push_pc_workouts,
|
||||||
records_from_workout_log,
|
records_from_workout_log,
|
||||||
)
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
_MANUAL = {
|
_MANUAL = {
|
||||||
"type": "manual_workout",
|
"type": "manual_workout",
|
||||||
@ -47,7 +53,6 @@ class TestEncodeDecodeLog:
|
|||||||
"""The crdt log blob round-trips."""
|
"""The crdt log blob round-trips."""
|
||||||
|
|
||||||
def test_round_trips(self, tmp_path: Path) -> None:
|
def test_round_trips(self, tmp_path: Path) -> None:
|
||||||
"""Round trips."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
_write_log(
|
_write_log(
|
||||||
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
||||||
@ -60,7 +65,6 @@ class TestEntryWallMs:
|
|||||||
"""The HLC clock is derived from the entry's own timestamp — stably."""
|
"""The HLC clock is derived from the entry's own timestamp — stably."""
|
||||||
|
|
||||||
def test_uses_the_entry_timestamp(self) -> None:
|
def test_uses_the_entry_timestamp(self) -> None:
|
||||||
"""Uses the entry timestamp."""
|
|
||||||
expected = int(
|
expected = int(
|
||||||
datetime(2026, 7, 13, 12, tzinfo=timezone.utc).timestamp() * 1000
|
datetime(2026, 7, 13, 12, tzinfo=timezone.utc).timestamp() * 1000
|
||||||
)
|
)
|
||||||
@ -68,12 +72,10 @@ class TestEntryWallMs:
|
|||||||
assert ms == expected
|
assert ms == expected
|
||||||
|
|
||||||
def test_unparsable_timestamp_falls_back_to_midnight(self) -> None:
|
def test_unparsable_timestamp_falls_back_to_midnight(self) -> None:
|
||||||
"""Unparsable timestamp falls back to midnight."""
|
|
||||||
ms = _entry_wall_ms({"timestamp": "not-a-time"}, "2026-07-13")
|
ms = _entry_wall_ms({"timestamp": "not-a-time"}, "2026-07-13")
|
||||||
assert ms == _entry_wall_ms({"timestamp": "2026-07-13T00:00:00+00:00"}, "x")
|
assert ms == _entry_wall_ms({"timestamp": "2026-07-13T00:00:00+00:00"}, "x")
|
||||||
|
|
||||||
def test_missing_timestamp_falls_back_to_midnight(self) -> None:
|
def test_missing_timestamp_falls_back_to_midnight(self) -> None:
|
||||||
"""Missing timestamp falls back to midnight."""
|
|
||||||
expected = int(datetime(2026, 7, 13, tzinfo=timezone.utc).timestamp() * 1000)
|
expected = int(datetime(2026, 7, 13, tzinfo=timezone.utc).timestamp() * 1000)
|
||||||
assert _entry_wall_ms({}, "2026-07-13") == expected
|
assert _entry_wall_ms({}, "2026-07-13") == expected
|
||||||
|
|
||||||
@ -86,7 +88,6 @@ class TestRecordsFromWorkoutLog:
|
|||||||
"""workout_log.json is the single source of truth for what gets pushed."""
|
"""workout_log.json is the single source of truth for what gets pushed."""
|
||||||
|
|
||||||
def test_derives_a_record_per_counted_workout(self, tmp_path: Path) -> None:
|
def test_derives_a_record_per_counted_workout(self, tmp_path: Path) -> None:
|
||||||
"""Derives a record per counted workout."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
_write_log(
|
_write_log(
|
||||||
log_file,
|
log_file,
|
||||||
@ -105,7 +106,6 @@ class TestRecordsFromWorkoutLog:
|
|||||||
assert set(log) == {"manual:2026-07-13T18:00", "runnerup_verified:2026-07-13"}
|
assert set(log) == {"manual:2026-07-13T18:00", "runnerup_verified:2026-07-13"}
|
||||||
|
|
||||||
def test_payload_carries_kind_and_date(self, tmp_path: Path) -> None:
|
def test_payload_carries_kind_and_date(self, tmp_path: Path) -> None:
|
||||||
"""Payload carries kind and date."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
_write_log(
|
_write_log(
|
||||||
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
||||||
@ -128,7 +128,6 @@ class TestRecordsFromWorkoutLog:
|
|||||||
assert "manual:2026-07-13T18:00" in records_from_workout_log(log_file)
|
assert "manual:2026-07-13T18:00" in records_from_workout_log(log_file)
|
||||||
|
|
||||||
def test_uncounted_types_are_not_pushed(self, tmp_path: Path) -> None:
|
def test_uncounted_types_are_not_pushed(self, tmp_path: Path) -> None:
|
||||||
"""Uncounted types are not pushed."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
_write_log(
|
_write_log(
|
||||||
log_file,
|
log_file,
|
||||||
@ -137,7 +136,6 @@ class TestRecordsFromWorkoutLog:
|
|||||||
assert records_from_workout_log(log_file) == {}
|
assert records_from_workout_log(log_file) == {}
|
||||||
|
|
||||||
def test_non_dict_workout_data_is_skipped(self, tmp_path: Path) -> None:
|
def test_non_dict_workout_data_is_skipped(self, tmp_path: Path) -> None:
|
||||||
"""Non dict workout data is skipped."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
_write_log(
|
_write_log(
|
||||||
log_file,
|
log_file,
|
||||||
@ -167,3 +165,130 @@ class TestRecordsFromWorkoutLog:
|
|||||||
assert _encode_log(records_from_workout_log(log_file)) == _encode_log(
|
assert _encode_log(records_from_workout_log(log_file)) == _encode_log(
|
||||||
records_from_workout_log(log_file)
|
records_from_workout_log(log_file)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestPushPcWorkouts:
|
||||||
|
"""Every outcome is reported — never a silent no-op."""
|
||||||
|
|
||||||
|
def test_no_token_reports_why(self, tmp_path: Path) -> None:
|
||||||
|
log_file = tmp_path / "workout_log.json"
|
||||||
|
_write_log(
|
||||||
|
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
||||||
|
)
|
||||||
|
with patch.object(_manual_push, "read_sync_token", return_value=None):
|
||||||
|
result = push_pc_workouts(log_file)
|
||||||
|
assert result == PushResult(pushed=False, record_count=0, reason=result.reason)
|
||||||
|
assert "no sync token" in result.reason
|
||||||
|
|
||||||
|
def test_empty_log_reports_why(self, tmp_path: Path) -> None:
|
||||||
|
log_file = tmp_path / "workout_log.json"
|
||||||
|
_write_log(log_file, {})
|
||||||
|
with patch.object(_manual_push, "read_sync_token", return_value="t"):
|
||||||
|
result = push_pc_workouts(log_file)
|
||||||
|
assert result.pushed is False
|
||||||
|
assert result.record_count == 0
|
||||||
|
assert "no counted workouts" in result.reason
|
||||||
|
|
||||||
|
def test_sync_error_reports_why(self, tmp_path: Path) -> None:
|
||||||
|
log_file = tmp_path / "workout_log.json"
|
||||||
|
_write_log(
|
||||||
|
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
||||||
|
)
|
||||||
|
with (
|
||||||
|
patch.object(_manual_push, "read_sync_token", return_value="t"),
|
||||||
|
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
|
||||||
|
patch.object(
|
||||||
|
_manual_push, "sync_log", side_effect=GitHubSyncError("403 forbidden")
|
||||||
|
),
|
||||||
|
):
|
||||||
|
result = push_pc_workouts(log_file)
|
||||||
|
assert result.pushed is False
|
||||||
|
assert result.record_count == 1
|
||||||
|
assert "403 forbidden" in result.reason
|
||||||
|
|
||||||
|
def test_network_error_is_not_blamed_on_the_token(
|
||||||
|
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
"""A network failure must not be reported as a permissions problem.
|
||||||
|
|
||||||
|
Regression guard for 2026-07-20: the morning routine runs seconds after
|
||||||
|
boot/resume, so its pushes failed with the network still down — and the
|
||||||
|
log asserted "a 403 here means the token lacks contents:write", which
|
||||||
|
sent an investigation chasing a permissions bug that did not exist.
|
||||||
|
"""
|
||||||
|
log_file = tmp_path / "workout_log.json"
|
||||||
|
_write_log(
|
||||||
|
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
||||||
|
)
|
||||||
|
with (
|
||||||
|
patch.object(_manual_push, "read_sync_token", return_value="t"),
|
||||||
|
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
|
||||||
|
patch.object(
|
||||||
|
_manual_push,
|
||||||
|
"sync_log",
|
||||||
|
side_effect=GitHubSyncError("network error reading x"),
|
||||||
|
),
|
||||||
|
caplog.at_level("WARNING"),
|
||||||
|
):
|
||||||
|
result = push_pc_workouts(log_file)
|
||||||
|
assert result.pushed is False
|
||||||
|
assert "network error reading x" in caplog.text
|
||||||
|
assert "contents:write" not in caplog.text
|
||||||
|
|
||||||
|
def test_repo_not_found_still_points_at_the_token(
|
||||||
|
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
"""The permission hint survives for the error that actually implies it."""
|
||||||
|
log_file = tmp_path / "workout_log.json"
|
||||||
|
_write_log(
|
||||||
|
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
||||||
|
)
|
||||||
|
with (
|
||||||
|
patch.object(_manual_push, "read_sync_token", return_value="t"),
|
||||||
|
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
|
||||||
|
patch.object(
|
||||||
|
_manual_push,
|
||||||
|
"sync_log",
|
||||||
|
side_effect=RepoNotFoundError("no access"),
|
||||||
|
),
|
||||||
|
caplog.at_level("WARNING"),
|
||||||
|
):
|
||||||
|
result = push_pc_workouts(log_file)
|
||||||
|
assert result.pushed is False
|
||||||
|
assert "contents:write" in caplog.text
|
||||||
|
|
||||||
|
def test_successful_push_reports_count(self, tmp_path: Path) -> None:
|
||||||
|
log_file = tmp_path / "workout_log.json"
|
||||||
|
_write_log(
|
||||||
|
log_file,
|
||||||
|
{
|
||||||
|
"2026-07-13": [
|
||||||
|
_entry(_MANUAL, "2026-07-13T07:25:12+00:00"),
|
||||||
|
_entry(_RUN, "2026-07-13T23:10:00+00:00"),
|
||||||
|
]
|
||||||
|
},
|
||||||
|
)
|
||||||
|
fake_sync = MagicMock()
|
||||||
|
with (
|
||||||
|
patch.object(_manual_push, "read_sync_token", return_value="t"),
|
||||||
|
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
|
||||||
|
patch.object(_manual_push, "sync_log", fake_sync),
|
||||||
|
):
|
||||||
|
result = push_pc_workouts(log_file)
|
||||||
|
assert result == PushResult(pushed=True, record_count=2, reason="pushed")
|
||||||
|
assert fake_sync.call_count == 1
|
||||||
|
|
||||||
|
def test_pushes_runs_not_just_manuals(self, tmp_path: Path) -> None:
|
||||||
|
"""Regression: the phone must converge on the PC's runs too."""
|
||||||
|
log_file = tmp_path / "workout_log.json"
|
||||||
|
_write_log(
|
||||||
|
log_file, {"2026-07-12": [_entry(_RUN, "2026-07-12T10:00:00+00:00")]}
|
||||||
|
)
|
||||||
|
with (
|
||||||
|
patch.object(_manual_push, "read_sync_token", return_value="t"),
|
||||||
|
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
|
||||||
|
patch.object(_manual_push, "sync_log", MagicMock()) as fake_sync,
|
||||||
|
):
|
||||||
|
push_pc_workouts(log_file)
|
||||||
|
pushed = fake_sync.call_args.kwargs["local_log"]
|
||||||
|
assert "runnerup_verified:2026-07-12" in pushed
|
||||||
|
|||||||
@ -1,168 +0,0 @@
|
|||||||
"""Tests for push_pc_workouts.
|
|
||||||
|
|
||||||
Split out of test_manual_push.py for the 250-line cap; the shared _entry /
|
|
||||||
_write_log helpers stay in that module and are imported here.
|
|
||||||
"""
|
|
||||||
# pylint: disable=protected-access
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
from unittest.mock import MagicMock, patch
|
|
||||||
|
|
||||||
from crdt_sync import GitHubSyncError, RepoNotFoundError
|
|
||||||
|
|
||||||
from screen_locker import _manual_push
|
|
||||||
from screen_locker._manual_push import (
|
|
||||||
PushResult,
|
|
||||||
push_pc_workouts,
|
|
||||||
)
|
|
||||||
from screen_locker.tests.test_manual_push import _entry, _write_log
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
_MANUAL = {
|
|
||||||
"type": "manual_workout",
|
|
||||||
"source": "table tennis at Solec",
|
|
||||||
"start_time": "18:00",
|
|
||||||
"rpe": 6,
|
|
||||||
}
|
|
||||||
_RUN = {
|
|
||||||
"type": "runnerup_verified",
|
|
||||||
"source": "Running: 9.8 km in 55 min",
|
|
||||||
"distance_km": 9.8,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class TestPushPcWorkouts:
|
|
||||||
"""Every outcome is reported — never a silent no-op."""
|
|
||||||
|
|
||||||
def test_no_token_reports_why(self, tmp_path: Path) -> None:
|
|
||||||
"""No token reports why."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
|
||||||
_write_log(
|
|
||||||
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
|
||||||
)
|
|
||||||
with patch.object(_manual_push, "read_sync_token", return_value=None):
|
|
||||||
result = push_pc_workouts(log_file)
|
|
||||||
assert result == PushResult(pushed=False, record_count=0, reason=result.reason)
|
|
||||||
assert "no sync token" in result.reason
|
|
||||||
|
|
||||||
def test_empty_log_reports_why(self, tmp_path: Path) -> None:
|
|
||||||
"""Empty log reports why."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
|
||||||
_write_log(log_file, {})
|
|
||||||
with patch.object(_manual_push, "read_sync_token", return_value="t"):
|
|
||||||
result = push_pc_workouts(log_file)
|
|
||||||
assert result.pushed is False
|
|
||||||
assert result.record_count == 0
|
|
||||||
assert "no counted workouts" in result.reason
|
|
||||||
|
|
||||||
def test_sync_error_reports_why(self, tmp_path: Path) -> None:
|
|
||||||
"""Sync error reports why."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
|
||||||
_write_log(
|
|
||||||
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
|
||||||
)
|
|
||||||
with (
|
|
||||||
patch.object(_manual_push, "read_sync_token", return_value="t"),
|
|
||||||
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
|
|
||||||
patch.object(
|
|
||||||
_manual_push, "sync_log", side_effect=GitHubSyncError("403 forbidden")
|
|
||||||
),
|
|
||||||
):
|
|
||||||
result = push_pc_workouts(log_file)
|
|
||||||
assert result.pushed is False
|
|
||||||
assert result.record_count == 1
|
|
||||||
assert "403 forbidden" in result.reason
|
|
||||||
|
|
||||||
def test_network_error_is_not_blamed_on_the_token(
|
|
||||||
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
|
||||||
) -> None:
|
|
||||||
"""A network failure must not be reported as a permissions problem.
|
|
||||||
|
|
||||||
Regression guard for 2026-07-20: the morning routine runs seconds after
|
|
||||||
boot/resume, so its pushes failed with the network still down — and the
|
|
||||||
log asserted "a 403 here means the token lacks contents:write", which
|
|
||||||
sent an investigation chasing a permissions bug that did not exist.
|
|
||||||
"""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
|
||||||
_write_log(
|
|
||||||
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
|
||||||
)
|
|
||||||
with (
|
|
||||||
patch.object(_manual_push, "read_sync_token", return_value="t"),
|
|
||||||
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
|
|
||||||
patch.object(
|
|
||||||
_manual_push,
|
|
||||||
"sync_log",
|
|
||||||
side_effect=GitHubSyncError("network error reading x"),
|
|
||||||
),
|
|
||||||
caplog.at_level("WARNING"),
|
|
||||||
):
|
|
||||||
result = push_pc_workouts(log_file)
|
|
||||||
assert result.pushed is False
|
|
||||||
assert "network error reading x" in caplog.text
|
|
||||||
assert "contents:write" not in caplog.text
|
|
||||||
|
|
||||||
def test_repo_not_found_still_points_at_the_token(
|
|
||||||
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
|
||||||
) -> None:
|
|
||||||
"""The permission hint survives for the error that actually implies it."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
|
||||||
_write_log(
|
|
||||||
log_file, {"2026-07-13": [_entry(_RUN, "2026-07-13T10:00:00+00:00")]}
|
|
||||||
)
|
|
||||||
with (
|
|
||||||
patch.object(_manual_push, "read_sync_token", return_value="t"),
|
|
||||||
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
|
|
||||||
patch.object(
|
|
||||||
_manual_push,
|
|
||||||
"sync_log",
|
|
||||||
side_effect=RepoNotFoundError("no access"),
|
|
||||||
),
|
|
||||||
caplog.at_level("WARNING"),
|
|
||||||
):
|
|
||||||
result = push_pc_workouts(log_file)
|
|
||||||
assert result.pushed is False
|
|
||||||
assert "contents:write" in caplog.text
|
|
||||||
|
|
||||||
def test_successful_push_reports_count(self, tmp_path: Path) -> None:
|
|
||||||
"""Successful push reports count."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
|
||||||
_write_log(
|
|
||||||
log_file,
|
|
||||||
{
|
|
||||||
"2026-07-13": [
|
|
||||||
_entry(_MANUAL, "2026-07-13T07:25:12+00:00"),
|
|
||||||
_entry(_RUN, "2026-07-13T23:10:00+00:00"),
|
|
||||||
]
|
|
||||||
},
|
|
||||||
)
|
|
||||||
fake_sync = MagicMock()
|
|
||||||
with (
|
|
||||||
patch.object(_manual_push, "read_sync_token", return_value="t"),
|
|
||||||
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
|
|
||||||
patch.object(_manual_push, "sync_log", fake_sync),
|
|
||||||
):
|
|
||||||
result = push_pc_workouts(log_file)
|
|
||||||
assert result == PushResult(pushed=True, record_count=2, reason="pushed")
|
|
||||||
assert fake_sync.call_count == 1
|
|
||||||
|
|
||||||
def test_pushes_runs_not_just_manuals(self, tmp_path: Path) -> None:
|
|
||||||
"""Regression: the phone must converge on the PC's runs too."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
|
||||||
_write_log(
|
|
||||||
log_file, {"2026-07-12": [_entry(_RUN, "2026-07-12T10:00:00+00:00")]}
|
|
||||||
)
|
|
||||||
with (
|
|
||||||
patch.object(_manual_push, "read_sync_token", return_value="t"),
|
|
||||||
patch.object(_manual_push, "GitHubSyncClient", MagicMock()),
|
|
||||||
patch.object(_manual_push, "sync_log", MagicMock()) as fake_sync,
|
|
||||||
):
|
|
||||||
push_pc_workouts(log_file)
|
|
||||||
pushed = fake_sync.call_args.kwargs["local_log"]
|
|
||||||
assert "runnerup_verified:2026-07-12" in pushed
|
|
||||||
@ -8,6 +8,7 @@ from typing import TYPE_CHECKING
|
|||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from screen_locker import _manual_sync
|
from screen_locker import _manual_sync
|
||||||
|
from screen_locker._log_mixin import RecordResult
|
||||||
from screen_locker._manual_sync import (
|
from screen_locker._manual_sync import (
|
||||||
ingest_manual_records,
|
ingest_manual_records,
|
||||||
reconstruct_draft,
|
reconstruct_draft,
|
||||||
@ -68,10 +69,7 @@ def _manual_record(draft: ManualWorkoutDraft, date: str = _DATE) -> tuple[str, d
|
|||||||
|
|
||||||
|
|
||||||
class TestReconstructDraft:
|
class TestReconstructDraft:
|
||||||
"""ReconstructDraft."""
|
|
||||||
|
|
||||||
def test_rebuilds_a_table_tennis_draft(self) -> None:
|
def test_rebuilds_a_table_tennis_draft(self) -> None:
|
||||||
"""Rebuilds a table tennis draft."""
|
|
||||||
_, payload = _manual_record(_TT_DRAFT)
|
_, payload = _manual_record(_TT_DRAFT)
|
||||||
draft = reconstruct_draft(payload)
|
draft = reconstruct_draft(payload)
|
||||||
assert draft is not None
|
assert draft is not None
|
||||||
@ -79,30 +77,24 @@ class TestReconstructDraft:
|
|||||||
assert draft.racket == "Butterfly"
|
assert draft.racket == "Butterfly"
|
||||||
|
|
||||||
def test_rebuilds_an_other_sport_draft(self) -> None:
|
def test_rebuilds_an_other_sport_draft(self) -> None:
|
||||||
"""Rebuilds an other sport draft."""
|
|
||||||
_, payload = _manual_record(_OTHER_DRAFT)
|
_, payload = _manual_record(_OTHER_DRAFT)
|
||||||
draft = reconstruct_draft(payload)
|
draft = reconstruct_draft(payload)
|
||||||
assert draft is not None
|
assert draft is not None
|
||||||
assert draft.activity_type_other == "squash"
|
assert draft.activity_type_other == "squash"
|
||||||
|
|
||||||
def test_returns_none_when_a_required_field_is_missing(self) -> None:
|
def test_returns_none_when_a_required_field_is_missing(self) -> None:
|
||||||
"""Returns none when a required field is missing."""
|
|
||||||
_, payload = _manual_record(_TT_DRAFT)
|
_, payload = _manual_record(_TT_DRAFT)
|
||||||
del payload["start_time"]
|
del payload["start_time"]
|
||||||
assert reconstruct_draft(payload) is None
|
assert reconstruct_draft(payload) is None
|
||||||
|
|
||||||
def test_returns_none_on_a_mistyped_field(self) -> None:
|
def test_returns_none_on_a_mistyped_field(self) -> None:
|
||||||
"""Returns none on a mistyped field."""
|
|
||||||
_, payload = _manual_record(_TT_DRAFT)
|
_, payload = _manual_record(_TT_DRAFT)
|
||||||
payload["rpe"] = None
|
payload["rpe"] = None
|
||||||
assert reconstruct_draft(payload) is None
|
assert reconstruct_draft(payload) is None
|
||||||
|
|
||||||
|
|
||||||
class TestIngestManualRecords:
|
class TestIngestManualRecords:
|
||||||
"""IngestManualRecords."""
|
|
||||||
|
|
||||||
def test_ingests_a_valid_record(self, tmp_path: Path) -> None:
|
def test_ingests_a_valid_record(self, tmp_path: Path) -> None:
|
||||||
"""Ingests a valid record."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
record = _manual_record(_TT_DRAFT)
|
record = _manual_record(_TT_DRAFT)
|
||||||
ingested = ingest_manual_records(log_file, [record], today=_DATE)
|
ingested = ingest_manual_records(log_file, [record], today=_DATE)
|
||||||
@ -115,7 +107,6 @@ class TestIngestManualRecords:
|
|||||||
assert count_weekly_workouts(log_file, today=_dt(_DATE)) == 1
|
assert count_weekly_workouts(log_file, today=_dt(_DATE)) == 1
|
||||||
|
|
||||||
def test_is_idempotent(self, tmp_path: Path) -> None:
|
def test_is_idempotent(self, tmp_path: Path) -> None:
|
||||||
"""Is idempotent."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
record = _manual_record(_TT_DRAFT)
|
record = _manual_record(_TT_DRAFT)
|
||||||
ingest_manual_records(log_file, [record], today=_DATE)
|
ingest_manual_records(log_file, [record], today=_DATE)
|
||||||
@ -123,7 +114,6 @@ class TestIngestManualRecords:
|
|||||||
assert again == []
|
assert again == []
|
||||||
|
|
||||||
def test_skips_a_non_manual_payload(self, tmp_path: Path) -> None:
|
def test_skips_a_non_manual_payload(self, tmp_path: Path) -> None:
|
||||||
"""Skips a non manual payload."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
assert (
|
assert (
|
||||||
ingest_manual_records(log_file, [("s", {"succeeded": True})], today=_DATE)
|
ingest_manual_records(log_file, [("s", {"succeeded": True})], today=_DATE)
|
||||||
@ -131,7 +121,6 @@ class TestIngestManualRecords:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def test_skips_a_record_without_a_date(self, tmp_path: Path) -> None:
|
def test_skips_a_record_without_a_date(self, tmp_path: Path) -> None:
|
||||||
"""Skips a record without a date."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
_, payload = _manual_record(_TT_DRAFT)
|
_, payload = _manual_record(_TT_DRAFT)
|
||||||
del payload["date"]
|
del payload["date"]
|
||||||
@ -156,21 +145,18 @@ class TestIngestManualRecords:
|
|||||||
assert stored[_DATE][1]["workout_data"]["type"] == "manual_workout"
|
assert stored[_DATE][1]["workout_data"]["type"] == "manual_workout"
|
||||||
|
|
||||||
def test_skips_a_malformed_payload(self, tmp_path: Path) -> None:
|
def test_skips_a_malformed_payload(self, tmp_path: Path) -> None:
|
||||||
"""Skips a malformed payload."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
_, payload = _manual_record(_TT_DRAFT)
|
_, payload = _manual_record(_TT_DRAFT)
|
||||||
payload["rpe"] = None # reconstruct_draft -> None
|
payload["rpe"] = None # reconstruct_draft -> None
|
||||||
assert ingest_manual_records(log_file, [("m", payload)], today=_DATE) == []
|
assert ingest_manual_records(log_file, [("m", payload)], today=_DATE) == []
|
||||||
|
|
||||||
def test_skips_an_invalid_draft(self, tmp_path: Path) -> None:
|
def test_skips_an_invalid_draft(self, tmp_path: Path) -> None:
|
||||||
"""Skips an invalid draft."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
_, payload = _manual_record(_TT_DRAFT)
|
_, payload = _manual_record(_TT_DRAFT)
|
||||||
payload["location_name"] = " " # fails validate_manual_workout
|
payload["location_name"] = " " # fails validate_manual_workout
|
||||||
assert ingest_manual_records(log_file, [("m", payload)], today=_DATE) == []
|
assert ingest_manual_records(log_file, [("m", payload)], today=_DATE) == []
|
||||||
|
|
||||||
def test_skips_when_budget_exhausted(self, tmp_path: Path) -> None:
|
def test_skips_when_budget_exhausted(self, tmp_path: Path) -> None:
|
||||||
"""Skips when budget exhausted."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
record = _manual_record(_TT_DRAFT)
|
record = _manual_record(_TT_DRAFT)
|
||||||
with patch.object(_manual_sync, "is_budget_exhausted", return_value=True):
|
with patch.object(_manual_sync, "is_budget_exhausted", return_value=True):
|
||||||
@ -179,7 +165,6 @@ class TestIngestManualRecords:
|
|||||||
def test_writes_unsigned_entry_when_hmac_key_unavailable(
|
def test_writes_unsigned_entry_when_hmac_key_unavailable(
|
||||||
self, tmp_path: Path
|
self, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Writes unsigned entry when HMAC key unavailable."""
|
|
||||||
log_file = tmp_path / "workout_log.json"
|
log_file = tmp_path / "workout_log.json"
|
||||||
record = _manual_record(_TT_DRAFT)
|
record = _manual_record(_TT_DRAFT)
|
||||||
with patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None):
|
with patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None):
|
||||||
@ -188,6 +173,87 @@ class TestIngestManualRecords:
|
|||||||
assert "hmac" not in stored[_DATE][0]
|
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:
|
||||||
|
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:
|
||||||
|
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 == []
|
||||||
|
|
||||||
|
|
||||||
|
class TestIngestHelpers:
|
||||||
|
def test_already_ingested_finds_id_in_per_day_lists(self) -> None:
|
||||||
|
"""_already_ingested takes normalized ``{date: [entry, ...]}`` and
|
||||||
|
scans every entry across all days for a matching sync record id."""
|
||||||
|
logs = {
|
||||||
|
"a": [],
|
||||||
|
"b": [
|
||||||
|
{"workout_data": {"type": "manual_workout"}},
|
||||||
|
{"workout_data": {"sync_record_id": "x"}},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
assert _manual_sync._already_ingested(logs, "x") is True
|
||||||
|
assert _manual_sync._already_ingested(logs, "y") is False
|
||||||
|
|
||||||
|
def test_already_ingested_ignores_non_dict_workout_data(self) -> None:
|
||||||
|
"""An entry whose workout_data isn't a dict is skipped, not matched."""
|
||||||
|
logs = {"b": [{"workout_data": "not-a-dict"}]}
|
||||||
|
assert _manual_sync._already_ingested(logs, "x") is False
|
||||||
|
|
||||||
|
|
||||||
def _dt(date: str) -> object:
|
def _dt(date: str) -> object:
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
|||||||
@ -1,69 +0,0 @@
|
|||||||
"""Tests for ingesting synced manual workouts into workout_log.json."""
|
|
||||||
# pylint: disable=protected-access
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from screen_locker import _manual_sync
|
|
||||||
from screen_locker._manual_workout import (
|
|
||||||
SPORT_OTHER,
|
|
||||||
SPORT_TABLE_TENNIS,
|
|
||||||
ManualWorkoutDraft,
|
|
||||||
)
|
|
||||||
|
|
||||||
_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 TestIngestHelpers:
|
|
||||||
"""The normalization/dedup helpers behind ingest_manual_records."""
|
|
||||||
|
|
||||||
def test_already_ingested_finds_id_in_per_day_lists(self) -> None:
|
|
||||||
"""_already_ingested takes normalized ``{date: [entry, ...]}`` and
|
|
||||||
scans every entry across all days for a matching sync record id."""
|
|
||||||
logs = {
|
|
||||||
"a": [],
|
|
||||||
"b": [
|
|
||||||
{"workout_data": {"type": "manual_workout"}},
|
|
||||||
{"workout_data": {"sync_record_id": "x"}},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
assert _manual_sync._already_ingested(logs, "x") is True
|
|
||||||
assert _manual_sync._already_ingested(logs, "y") is False
|
|
||||||
|
|
||||||
def test_already_ingested_ignores_non_dict_workout_data(self) -> None:
|
|
||||||
"""An entry whose workout_data isn't a dict is skipped, not matched."""
|
|
||||||
logs = {"b": [{"workout_data": "not-a-dict"}]}
|
|
||||||
assert _manual_sync._already_ingested(logs, "x") is False
|
|
||||||
@ -1,122 +0,0 @@
|
|||||||
"""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 == []
|
|
||||||
@ -164,3 +164,105 @@ class TestGetLocalSubnetPrefix:
|
|||||||
):
|
):
|
||||||
result = locker._get_local_subnet_prefix()
|
result = locker._get_local_subnet_prefix()
|
||||||
assert result is None
|
assert result is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestTryWirelessReconnect:
|
||||||
|
"""Tests for _try_wireless_reconnect method."""
|
||||||
|
|
||||||
|
def test_returns_false_when_no_prefix(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test returns False when subnet prefix can't be determined."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
with patch.object(locker, "_get_local_subnet_prefix", return_value=None):
|
||||||
|
result = locker._try_wireless_reconnect()
|
||||||
|
assert result is False
|
||||||
|
|
||||||
|
def test_returns_true_when_probe_succeeds(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test returns True when a probe finds the phone."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
with (
|
||||||
|
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
||||||
|
patch.object(locker, "_try_adb_connect", return_value=True),
|
||||||
|
patch.object(locker, "_has_adb_device", return_value=True),
|
||||||
|
patch(
|
||||||
|
"screen_locker._phone_verification.socket.create_connection",
|
||||||
|
) as mock_conn,
|
||||||
|
):
|
||||||
|
mock_sock = MagicMock()
|
||||||
|
mock_sock.__enter__ = MagicMock(return_value=mock_sock)
|
||||||
|
mock_sock.__exit__ = MagicMock(return_value=False)
|
||||||
|
mock_conn.return_value = mock_sock
|
||||||
|
result = locker._try_wireless_reconnect()
|
||||||
|
assert result is True
|
||||||
|
|
||||||
|
def test_returns_false_when_no_probe_succeeds(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test returns False when no probe finds the phone."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
with (
|
||||||
|
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
||||||
|
patch(
|
||||||
|
"screen_locker._phone_verification.socket.create_connection",
|
||||||
|
side_effect=OSError("refused"),
|
||||||
|
),
|
||||||
|
):
|
||||||
|
result = locker._try_wireless_reconnect()
|
||||||
|
assert result is False
|
||||||
|
|
||||||
|
def test_probe_connect_succeeds_but_no_device(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test probe passes socket but adb_connect succeeds without device."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
with (
|
||||||
|
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
||||||
|
patch.object(locker, "_try_adb_connect", return_value=True),
|
||||||
|
patch.object(locker, "_has_adb_device", return_value=False),
|
||||||
|
patch(
|
||||||
|
"screen_locker._phone_verification.socket.create_connection",
|
||||||
|
) as mock_conn,
|
||||||
|
):
|
||||||
|
mock_sock = MagicMock()
|
||||||
|
mock_sock.__enter__ = MagicMock(return_value=mock_sock)
|
||||||
|
mock_sock.__exit__ = MagicMock(return_value=False)
|
||||||
|
mock_conn.return_value = mock_sock
|
||||||
|
result = locker._try_wireless_reconnect()
|
||||||
|
assert result is False
|
||||||
|
|
||||||
|
def test_probe_adb_connect_fails(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test probe where socket connects but adb connect fails."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
with (
|
||||||
|
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
||||||
|
patch.object(locker, "_try_adb_connect", return_value=False),
|
||||||
|
patch(
|
||||||
|
"screen_locker._phone_verification.socket.create_connection",
|
||||||
|
) as mock_conn,
|
||||||
|
):
|
||||||
|
mock_sock = MagicMock()
|
||||||
|
mock_sock.__enter__ = MagicMock(return_value=mock_sock)
|
||||||
|
mock_sock.__exit__ = MagicMock(return_value=False)
|
||||||
|
mock_conn.return_value = mock_sock
|
||||||
|
result = locker._try_wireless_reconnect()
|
||||||
|
assert result is False
|
||||||
|
|||||||
@ -139,3 +139,202 @@ class TestPullWorkoutAppJsonMultiPath:
|
|||||||
with patch.object(locker, "_run_adb", fake):
|
with patch.object(locker, "_run_adb", fake):
|
||||||
result = locker._pull_workout_app_json()
|
result = locker._pull_workout_app_json()
|
||||||
assert result is None
|
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"
|
||||||
|
|||||||
@ -41,7 +41,6 @@ class TestValidateJsonData:
|
|||||||
def test_stale_when_not_today(
|
def test_stale_when_not_today(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Stale when not today."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
status, message = locker._validate_json_data(
|
status, message = locker._validate_json_data(
|
||||||
{"date": "2000-01-01", "exercises": ["x"], "duration_seconds": 4000}
|
{"date": "2000-01-01", "exercises": ["x"], "duration_seconds": 4000}
|
||||||
@ -52,7 +51,6 @@ class TestValidateJsonData:
|
|||||||
def test_no_exercises_when_empty(
|
def test_no_exercises_when_empty(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""No exercises when empty."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
status, message = locker._validate_json_data(
|
status, message = locker._validate_json_data(
|
||||||
{"date": _today(), "exercises": [], "duration_seconds": 4000}
|
{"date": _today(), "exercises": [], "duration_seconds": 4000}
|
||||||
@ -63,7 +61,6 @@ class TestValidateJsonData:
|
|||||||
def test_too_short_under_minimum(
|
def test_too_short_under_minimum(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Too short under minimum."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
# Derive from the ACCEPT bar, not the advertised one: a duration
|
# Derive from the ACCEPT bar, not the advertised one: a duration
|
||||||
# merely under 40 may still clear the hidden leeway and verify.
|
# merely under 40 may still clear the hidden leeway and verify.
|
||||||
@ -79,7 +76,6 @@ class TestValidateJsonData:
|
|||||||
def test_verified_all_succeeded(
|
def test_verified_all_succeeded(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Verified all succeeded."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
status, message = locker._validate_json_data(
|
status, message = locker._validate_json_data(
|
||||||
{
|
{
|
||||||
@ -95,7 +91,6 @@ class TestValidateJsonData:
|
|||||||
def test_verified_partial_when_not_succeeded(
|
def test_verified_partial_when_not_succeeded(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Verified partial when not succeeded."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
status, message = locker._validate_json_data(
|
status, message = locker._validate_json_data(
|
||||||
{
|
{
|
||||||
@ -115,7 +110,6 @@ class TestScanForHttpServer:
|
|||||||
def test_returns_none_without_prefix(
|
def test_returns_none_without_prefix(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Returns none without prefix."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
with patch.object(locker, "_get_local_subnet_prefix", return_value=None):
|
with patch.object(locker, "_get_local_subnet_prefix", return_value=None):
|
||||||
assert locker._scan_for_http_server() is None
|
assert locker._scan_for_http_server() is None
|
||||||
@ -123,7 +117,6 @@ class TestScanForHttpServer:
|
|||||||
def test_returns_url_when_probe_connects(
|
def test_returns_url_when_probe_connects(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Returns URL when probe connects."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
with (
|
with (
|
||||||
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
||||||
@ -140,7 +133,6 @@ class TestScanForHttpServer:
|
|||||||
def test_returns_none_when_all_probes_refused(
|
def test_returns_none_when_all_probes_refused(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Returns none when all probes refused."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
with (
|
with (
|
||||||
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
||||||
@ -213,3 +205,75 @@ class TestVerifyPhoneWorkoutSyncStaleness:
|
|||||||
status, message = locker._verify_phone_workout()
|
status, message = locker._verify_phone_workout()
|
||||||
assert status == "stale"
|
assert status == "stale"
|
||||||
assert "2000-01-01" in message
|
assert "2000-01-01" in message
|
||||||
|
|
||||||
|
|
||||||
|
class TestFetchHttpWorkout:
|
||||||
|
"""Tests for _fetch_http_workout over the local HTTP server."""
|
||||||
|
|
||||||
|
def test_returns_none_when_scan_finds_nothing(
|
||||||
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
with patch.object(locker, "_scan_for_http_server", return_value=None):
|
||||||
|
assert locker._fetch_http_workout() is None
|
||||||
|
|
||||||
|
def test_returns_json_on_http_200(
|
||||||
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
resp = MagicMock()
|
||||||
|
resp.status = 200
|
||||||
|
resp.read.return_value = b'{"date": "2026-06-12", "exercises": ["a"]}'
|
||||||
|
conn = MagicMock()
|
||||||
|
conn.getresponse.return_value = resp
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
locker,
|
||||||
|
"_scan_for_http_server",
|
||||||
|
return_value="http://192.168.1.5:8765/workout",
|
||||||
|
),
|
||||||
|
patch(
|
||||||
|
"screen_locker._phone_verification._HTTPConnection",
|
||||||
|
return_value=conn,
|
||||||
|
),
|
||||||
|
):
|
||||||
|
result = locker._fetch_http_workout()
|
||||||
|
assert result == {"date": "2026-06-12", "exercises": ["a"]}
|
||||||
|
|
||||||
|
def test_returns_none_on_non_ok_status(
|
||||||
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
resp = MagicMock()
|
||||||
|
resp.status = 404
|
||||||
|
conn = MagicMock()
|
||||||
|
conn.getresponse.return_value = resp
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
locker,
|
||||||
|
"_scan_for_http_server",
|
||||||
|
return_value="http://192.168.1.5:8765/workout",
|
||||||
|
),
|
||||||
|
patch(
|
||||||
|
"screen_locker._phone_verification._HTTPConnection",
|
||||||
|
return_value=conn,
|
||||||
|
),
|
||||||
|
):
|
||||||
|
assert locker._fetch_http_workout() is None
|
||||||
|
|
||||||
|
def test_returns_none_on_connection_error(
|
||||||
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
locker,
|
||||||
|
"_scan_for_http_server",
|
||||||
|
return_value="http://192.168.1.5:8765/workout",
|
||||||
|
),
|
||||||
|
patch(
|
||||||
|
"screen_locker._phone_verification._HTTPConnection",
|
||||||
|
side_effect=OSError("unreachable"),
|
||||||
|
),
|
||||||
|
):
|
||||||
|
assert locker._fetch_http_workout() is None
|
||||||
|
|||||||
@ -1,113 +0,0 @@
|
|||||||
"""Tests for phone verification coverage gaps (part 2)."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
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 TestTryWirelessReconnect:
|
|
||||||
"""Tests for _try_wireless_reconnect method."""
|
|
||||||
|
|
||||||
def test_returns_false_when_no_prefix(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test returns False when subnet prefix can't be determined."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
with patch.object(locker, "_get_local_subnet_prefix", return_value=None):
|
|
||||||
result = locker._try_wireless_reconnect()
|
|
||||||
assert result is False
|
|
||||||
|
|
||||||
def test_returns_true_when_probe_succeeds(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test returns True when a probe finds the phone."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
with (
|
|
||||||
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
|
||||||
patch.object(locker, "_try_adb_connect", return_value=True),
|
|
||||||
patch.object(locker, "_has_adb_device", return_value=True),
|
|
||||||
patch(
|
|
||||||
"screen_locker._phone_verification.socket.create_connection",
|
|
||||||
) as mock_conn,
|
|
||||||
):
|
|
||||||
mock_sock = MagicMock()
|
|
||||||
mock_sock.__enter__ = MagicMock(return_value=mock_sock)
|
|
||||||
mock_sock.__exit__ = MagicMock(return_value=False)
|
|
||||||
mock_conn.return_value = mock_sock
|
|
||||||
result = locker._try_wireless_reconnect()
|
|
||||||
assert result is True
|
|
||||||
|
|
||||||
def test_returns_false_when_no_probe_succeeds(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test returns False when no probe finds the phone."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
with (
|
|
||||||
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
|
||||||
patch(
|
|
||||||
"screen_locker._phone_verification.socket.create_connection",
|
|
||||||
side_effect=OSError("refused"),
|
|
||||||
),
|
|
||||||
):
|
|
||||||
result = locker._try_wireless_reconnect()
|
|
||||||
assert result is False
|
|
||||||
|
|
||||||
def test_probe_connect_succeeds_but_no_device(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test probe passes socket but adb_connect succeeds without device."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
with (
|
|
||||||
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
|
||||||
patch.object(locker, "_try_adb_connect", return_value=True),
|
|
||||||
patch.object(locker, "_has_adb_device", return_value=False),
|
|
||||||
patch(
|
|
||||||
"screen_locker._phone_verification.socket.create_connection",
|
|
||||||
) as mock_conn,
|
|
||||||
):
|
|
||||||
mock_sock = MagicMock()
|
|
||||||
mock_sock.__enter__ = MagicMock(return_value=mock_sock)
|
|
||||||
mock_sock.__exit__ = MagicMock(return_value=False)
|
|
||||||
mock_conn.return_value = mock_sock
|
|
||||||
result = locker._try_wireless_reconnect()
|
|
||||||
assert result is False
|
|
||||||
|
|
||||||
def test_probe_adb_connect_fails(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test probe where socket connects but adb connect fails."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
with (
|
|
||||||
patch.object(locker, "_get_local_subnet_prefix", return_value="192.168.1"),
|
|
||||||
patch.object(locker, "_try_adb_connect", return_value=False),
|
|
||||||
patch(
|
|
||||||
"screen_locker._phone_verification.socket.create_connection",
|
|
||||||
) as mock_conn,
|
|
||||||
):
|
|
||||||
mock_sock = MagicMock()
|
|
||||||
mock_sock.__enter__ = MagicMock(return_value=mock_sock)
|
|
||||||
mock_sock.__exit__ = MagicMock(return_value=False)
|
|
||||||
mock_conn.return_value = mock_sock
|
|
||||||
result = locker._try_wireless_reconnect()
|
|
||||||
assert result is False
|
|
||||||
@ -1,93 +0,0 @@
|
|||||||
"""Tests for JSON workout validation and HTTP fallback (part 4).
|
|
||||||
|
|
||||||
Replaces the obsolete StrongLifts-DB-based ``test_phone_check_unlock.py``.
|
|
||||||
Covers ``_validate_json_data`` (all status branches) and the HTTP fallback
|
|
||||||
``_scan_for_http_server`` / ``_fetch_http_workout`` used when ADB is
|
|
||||||
unavailable. Network is fully mocked — no test touches a real socket.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
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 TestFetchHttpWorkout:
|
|
||||||
"""Tests for _fetch_http_workout over the local HTTP server."""
|
|
||||||
|
|
||||||
def test_returns_none_when_scan_finds_nothing(
|
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
||||||
) -> None:
|
|
||||||
"""Returns none when scan finds nothing."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
with patch.object(locker, "_scan_for_http_server", return_value=None):
|
|
||||||
assert locker._fetch_http_workout() is None
|
|
||||||
|
|
||||||
def test_returns_json_on_http_200(
|
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
||||||
) -> None:
|
|
||||||
"""Returns JSON on HTTP 200."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
resp = MagicMock()
|
|
||||||
resp.status = 200
|
|
||||||
resp.read.return_value = b'{"date": "2026-06-12", "exercises": ["a"]}'
|
|
||||||
conn = MagicMock()
|
|
||||||
conn.getresponse.return_value = resp
|
|
||||||
with (
|
|
||||||
patch.object(
|
|
||||||
locker,
|
|
||||||
"_scan_for_http_server",
|
|
||||||
return_value="http://192.168.1.5:8765/workout",
|
|
||||||
),
|
|
||||||
patch(
|
|
||||||
"screen_locker._phone_verification._HTTPConnection",
|
|
||||||
return_value=conn,
|
|
||||||
),
|
|
||||||
):
|
|
||||||
result = locker._fetch_http_workout()
|
|
||||||
assert result == {"date": "2026-06-12", "exercises": ["a"]}
|
|
||||||
|
|
||||||
def test_returns_none_on_non_ok_status(
|
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
||||||
) -> None:
|
|
||||||
"""Returns none on non ok status."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
resp = MagicMock()
|
|
||||||
resp.status = 404
|
|
||||||
conn = MagicMock()
|
|
||||||
conn.getresponse.return_value = resp
|
|
||||||
with (
|
|
||||||
patch.object(
|
|
||||||
locker,
|
|
||||||
"_scan_for_http_server",
|
|
||||||
return_value="http://192.168.1.5:8765/workout",
|
|
||||||
),
|
|
||||||
patch(
|
|
||||||
"screen_locker._phone_verification._HTTPConnection",
|
|
||||||
return_value=conn,
|
|
||||||
),
|
|
||||||
):
|
|
||||||
assert locker._fetch_http_workout() is None
|
|
||||||
|
|
||||||
def test_returns_none_on_connection_error(
|
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
||||||
) -> None:
|
|
||||||
"""Returns none on connection error."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
with (
|
|
||||||
patch.object(
|
|
||||||
locker,
|
|
||||||
"_scan_for_http_server",
|
|
||||||
return_value="http://192.168.1.5:8765/workout",
|
|
||||||
),
|
|
||||||
patch(
|
|
||||||
"screen_locker._phone_verification._HTTPConnection",
|
|
||||||
side_effect=OSError("unreachable"),
|
|
||||||
),
|
|
||||||
):
|
|
||||||
assert locker._fetch_http_workout() is None
|
|
||||||
@ -1,221 +0,0 @@
|
|||||||
"""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"
|
|
||||||
@ -4,8 +4,9 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
|
import sqlite3
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from screen_locker.tests.conftest import create_locker
|
from screen_locker.tests.conftest import create_locker
|
||||||
|
|
||||||
@ -230,3 +231,90 @@ class TestPullRunnerupDb:
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# _query_todays_run
|
# _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
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|||||||
@ -1,151 +0,0 @@
|
|||||||
"""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
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
@ -211,3 +212,74 @@ class TestAdjustShutdownTimeLater:
|
|||||||
side_effect=OSError("fail"),
|
side_effect=OSError("fail"),
|
||||||
):
|
):
|
||||||
assert locker._adjust_shutdown_time_later() is False
|
assert locker._adjust_shutdown_time_later() is False
|
||||||
|
|
||||||
|
|
||||||
|
class TestSickModeUsedToday:
|
||||||
|
"""Tests for _sick_mode_used_today method."""
|
||||||
|
|
||||||
|
def test_returns_false_when_no_file(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test returns False when state file doesn't exist."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
mock_file = MagicMock()
|
||||||
|
mock_file.exists.return_value = False
|
||||||
|
with patch(
|
||||||
|
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||||
|
mock_file,
|
||||||
|
):
|
||||||
|
assert locker._sick_mode_used_today() is False
|
||||||
|
|
||||||
|
def test_returns_true_when_used_today(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test returns True when state matches today."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
state_file = tmp_path / "state.json"
|
||||||
|
with patch(
|
||||||
|
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||||
|
state_file,
|
||||||
|
):
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||||
|
state_file.write_text(json.dumps({"date": today}))
|
||||||
|
assert locker._sick_mode_used_today() is True
|
||||||
|
|
||||||
|
def test_returns_false_when_different_date(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test returns False when state is from different date."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
state_file = tmp_path / "state.json"
|
||||||
|
with patch(
|
||||||
|
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||||
|
state_file,
|
||||||
|
):
|
||||||
|
state_file.write_text(json.dumps({"date": "2020-01-01"}))
|
||||||
|
assert locker._sick_mode_used_today() is False
|
||||||
|
|
||||||
|
def test_returns_false_on_json_error(
|
||||||
|
self,
|
||||||
|
mock_tk: MagicMock,
|
||||||
|
mock_sys_exit: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
) -> None:
|
||||||
|
"""Test returns False on JSONDecodeError."""
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
state_file = tmp_path / "state.json"
|
||||||
|
with patch(
|
||||||
|
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
||||||
|
state_file,
|
||||||
|
):
|
||||||
|
state_file.write_text("not json{{{")
|
||||||
|
assert locker._sick_mode_used_today() is False
|
||||||
|
|||||||
@ -3,6 +3,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import subprocess
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
@ -236,3 +237,80 @@ class TestBuildShutdownCmd:
|
|||||||
"20",
|
"20",
|
||||||
"8",
|
"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
|
||||||
|
|||||||
@ -1,83 +0,0 @@
|
|||||||
"""Tests for shutdown schedule adjustment coverage gaps (part 2)."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
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 TestSickModeUsedToday:
|
|
||||||
"""Tests for _sick_mode_used_today method."""
|
|
||||||
|
|
||||||
def test_returns_false_when_no_file(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test returns False when state file doesn't exist."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
mock_file = MagicMock()
|
|
||||||
mock_file.exists.return_value = False
|
|
||||||
with patch(
|
|
||||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
|
||||||
mock_file,
|
|
||||||
):
|
|
||||||
assert locker._sick_mode_used_today() is False
|
|
||||||
|
|
||||||
def test_returns_true_when_used_today(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test returns True when state matches today."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
state_file = tmp_path / "state.json"
|
|
||||||
with patch(
|
|
||||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
|
||||||
state_file,
|
|
||||||
):
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
|
||||||
state_file.write_text(json.dumps({"date": today}))
|
|
||||||
assert locker._sick_mode_used_today() is True
|
|
||||||
|
|
||||||
def test_returns_false_when_different_date(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test returns False when state is from different date."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
state_file = tmp_path / "state.json"
|
|
||||||
with patch(
|
|
||||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
|
||||||
state_file,
|
|
||||||
):
|
|
||||||
state_file.write_text(json.dumps({"date": "2020-01-01"}))
|
|
||||||
assert locker._sick_mode_used_today() is False
|
|
||||||
|
|
||||||
def test_returns_false_on_json_error(
|
|
||||||
self,
|
|
||||||
mock_tk: MagicMock,
|
|
||||||
mock_sys_exit: MagicMock,
|
|
||||||
tmp_path: Path,
|
|
||||||
) -> None:
|
|
||||||
"""Test returns False on JSONDecodeError."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
state_file = tmp_path / "state.json"
|
|
||||||
with patch(
|
|
||||||
"screen_locker._shutdown.SICK_DAY_STATE_FILE",
|
|
||||||
state_file,
|
|
||||||
):
|
|
||||||
state_file.write_text("not json{{{")
|
|
||||||
assert locker._sick_mode_used_today() is False
|
|
||||||
@ -1,89 +0,0 @@
|
|||||||
"""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
|
|
||||||
@ -25,7 +25,6 @@ class TestShowRetryAndSickBudget:
|
|||||||
def test_shows_sick_button_when_budget_available(
|
def test_shows_sick_button_when_budget_available(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Shows sick button when budget available."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
with patch.object(_sick_tracker, "load_history", return_value=SickHistory()):
|
with patch.object(_sick_tracker, "load_history", return_value=SickHistory()):
|
||||||
locker._show_retry_and_sick("nope")
|
locker._show_retry_and_sick("nope")
|
||||||
@ -41,7 +40,6 @@ class TestShowRetryAndSickBudget:
|
|||||||
def test_hides_sick_button_when_budget_exhausted(
|
def test_hides_sick_button_when_budget_exhausted(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Hides sick button when budget exhausted."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
full = SickHistory(sick_days=["2026-05-09"] * 99)
|
full = SickHistory(sick_days=["2026-05-09"] * 99)
|
||||||
with (
|
with (
|
||||||
@ -61,7 +59,6 @@ class TestProceedToSickCountdownLoadsHistory:
|
|||||||
def test_loads_history_when_cache_missing(
|
def test_loads_history_when_cache_missing(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Loads history when cache missing."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
object.__setattr__(locker, "clear_container", MagicMock())
|
object.__setattr__(locker, "clear_container", MagicMock())
|
||||||
object.__setattr__(
|
object.__setattr__(
|
||||||
@ -86,7 +83,6 @@ class TestFinalizeSickDay:
|
|||||||
def test_marks_commitment_broken_and_writes_debt(
|
def test_marks_commitment_broken_and_writes_debt(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Marks commitment broken and writes debt."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker.workout_data = {}
|
locker.workout_data = {}
|
||||||
history = SickHistory(commitments={"2026-05-10": True})
|
history = SickHistory(commitments={"2026-05-10": True})
|
||||||
@ -105,7 +101,6 @@ class TestFinalizeSickDay:
|
|||||||
def test_loads_history_when_cache_missing(
|
def test_loads_history_when_cache_missing(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Loads history when cache missing."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker.workout_data = {}
|
locker.workout_data = {}
|
||||||
object.__setattr__(locker, "unlock_screen", MagicMock())
|
object.__setattr__(locker, "unlock_screen", MagicMock())
|
||||||
@ -131,7 +126,6 @@ class TestClearDebtOnVerifiedWorkout:
|
|||||||
def test_returns_none_when_not_phone_verified(
|
def test_returns_none_when_not_phone_verified(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Returns none when not phone verified."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker.workout_data = {"type": "sick_day"}
|
locker.workout_data = {"type": "sick_day"}
|
||||||
assert locker._clear_debt_on_verified_workout() is None
|
assert locker._clear_debt_on_verified_workout() is None
|
||||||
@ -139,7 +133,6 @@ class TestClearDebtOnVerifiedWorkout:
|
|||||||
def test_returns_zero_when_no_debt(
|
def test_returns_zero_when_no_debt(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Returns zero when no debt."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker.workout_data = {"type": "phone_verified"}
|
locker.workout_data = {"type": "phone_verified"}
|
||||||
with patch.object(
|
with patch.object(
|
||||||
@ -150,7 +143,6 @@ class TestClearDebtOnVerifiedWorkout:
|
|||||||
def test_decrements_when_debt_positive(
|
def test_decrements_when_debt_positive(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Decrements when debt positive."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker.workout_data = {"type": "phone_verified"}
|
locker.workout_data = {"type": "phone_verified"}
|
||||||
history = SickHistory(debt=2)
|
history = SickHistory(debt=2)
|
||||||
@ -168,7 +160,6 @@ class TestUnlockScreenCommitmentPrompt:
|
|||||||
def test_phone_verified_schedules_commitment_prompt(
|
def test_phone_verified_schedules_commitment_prompt(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Phone verified schedules commitment prompt."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker.workout_data = {"type": "phone_verified"}
|
locker.workout_data = {"type": "phone_verified"}
|
||||||
locker.log_file = tmp_path / "log.json"
|
locker.log_file = tmp_path / "log.json"
|
||||||
@ -191,7 +182,6 @@ class TestUnlockScreenCommitmentPrompt:
|
|||||||
def test_non_verified_schedules_close_directly(
|
def test_non_verified_schedules_close_directly(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Non verified schedules close directly."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker.workout_data = {"type": "sick_day"}
|
locker.workout_data = {"type": "sick_day"}
|
||||||
locker.log_file = tmp_path / "log.json"
|
locker.log_file = tmp_path / "log.json"
|
||||||
@ -213,7 +203,6 @@ class TestUnlockScreenCommitmentPrompt:
|
|||||||
def test_renders_debt_label_when_positive(
|
def test_renders_debt_label_when_positive(
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Renders debt label when positive."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
locker.workout_data = {"type": "phone_verified"}
|
locker.workout_data = {"type": "phone_verified"}
|
||||||
locker.log_file = tmp_path / "log.json"
|
locker.log_file = tmp_path / "log.json"
|
||||||
@ -237,3 +226,76 @@ class TestUnlockScreenCommitmentPrompt:
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# _sick_dialog.py — UI mixin
|
# _sick_dialog.py — UI mixin
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestShowSickJustification:
|
||||||
|
"""Tests for the structured sick justification dialog."""
|
||||||
|
|
||||||
|
def test_renders_form_without_commitment(
|
||||||
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
with patch.object(_sick_tracker, "load_history", return_value=SickHistory()):
|
||||||
|
locker._show_sick_justification()
|
||||||
|
assert locker._sick_history_cache.sick_days == []
|
||||||
|
assert hasattr(locker, "_sick_submit_button")
|
||||||
|
# Submit button starts enabled (no commitment).
|
||||||
|
# config(state="disabled") only called for commitment path.
|
||||||
|
for call in locker._sick_submit_button.first.configure.call_args_list:
|
||||||
|
assert call.kwargs.get("state") != "disabled"
|
||||||
|
|
||||||
|
def test_renders_form_with_commitment_disables_submit(
|
||||||
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
history = SickHistory(commitments={"2026-05-10": True})
|
||||||
|
with (
|
||||||
|
patch.object(_sick_tracker, "load_history", return_value=history),
|
||||||
|
patch.object(_sick_tracker, "had_commitment_for_today", return_value=True),
|
||||||
|
):
|
||||||
|
locker._show_sick_justification()
|
||||||
|
# Submit button was disabled and forced-delay started.
|
||||||
|
states = [
|
||||||
|
call.kwargs.get("state")
|
||||||
|
for call in locker._sick_submit_button.first.configure.call_args_list
|
||||||
|
]
|
||||||
|
assert "disabled" in states
|
||||||
|
|
||||||
|
def test_renders_recent_history_when_present(
|
||||||
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
history = SickHistory(
|
||||||
|
justifications=[
|
||||||
|
{"date": "2026-05-01", "symptom": "fever", "severity": 7},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
with patch.object(_sick_tracker, "load_history", return_value=history):
|
||||||
|
locker._show_sick_justification()
|
||||||
|
labels = [call.kwargs.get("text", "") for call in mock_tk.Label.call_args_list]
|
||||||
|
assert any("Recent sick days" in t for t in labels)
|
||||||
|
|
||||||
|
|
||||||
|
class TestUpdateCommitmentForcedDelay:
|
||||||
|
"""Tests for _update_commitment_forced_delay."""
|
||||||
|
|
||||||
|
def test_ticks_down(
|
||||||
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
locker._sick_submit_button = MagicMock()
|
||||||
|
locker._commitment_forced_remaining = 3
|
||||||
|
locker._update_commitment_forced_delay()
|
||||||
|
assert locker._commitment_forced_remaining == 2
|
||||||
|
locker.root.after.assert_called()
|
||||||
|
|
||||||
|
def test_enables_when_done(
|
||||||
|
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
|
locker._sick_submit_button = MagicMock()
|
||||||
|
locker._commitment_forced_remaining = 0
|
||||||
|
locker._update_commitment_forced_delay()
|
||||||
|
locker._sick_submit_button.config.assert_called_with(
|
||||||
|
text="SUBMIT", state="normal"
|
||||||
|
)
|
||||||
|
|||||||
@ -1,92 +0,0 @@
|
|||||||
"""Tests for sick-budget UI integration, finalize, debt-clear, and dialogs."""
|
|
||||||
# pylint: disable=protected-access
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
from unittest.mock import MagicMock, patch
|
|
||||||
|
|
||||||
from screen_locker import _sick_tracker
|
|
||||||
from screen_locker._sick_tracker import SickHistory
|
|
||||||
from screen_locker.tests.conftest import create_locker
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
|
|
||||||
class TestShowSickJustification:
|
|
||||||
"""Tests for the structured sick justification dialog."""
|
|
||||||
|
|
||||||
def test_renders_form_without_commitment(
|
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
||||||
) -> None:
|
|
||||||
"""Renders form without commitment."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
with patch.object(_sick_tracker, "load_history", return_value=SickHistory()):
|
|
||||||
locker._show_sick_justification()
|
|
||||||
assert locker._sick_history_cache.sick_days == []
|
|
||||||
assert hasattr(locker, "_sick_submit_button")
|
|
||||||
# Submit button starts enabled (no commitment).
|
|
||||||
# config(state="disabled") only called for commitment path.
|
|
||||||
for call in locker._sick_submit_button.first.configure.call_args_list:
|
|
||||||
assert call.kwargs.get("state") != "disabled"
|
|
||||||
|
|
||||||
def test_renders_form_with_commitment_disables_submit(
|
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
||||||
) -> None:
|
|
||||||
"""Renders form with commitment disables submit."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
history = SickHistory(commitments={"2026-05-10": True})
|
|
||||||
with (
|
|
||||||
patch.object(_sick_tracker, "load_history", return_value=history),
|
|
||||||
patch.object(_sick_tracker, "had_commitment_for_today", return_value=True),
|
|
||||||
):
|
|
||||||
locker._show_sick_justification()
|
|
||||||
# Submit button was disabled and forced-delay started.
|
|
||||||
states = [
|
|
||||||
call.kwargs.get("state")
|
|
||||||
for call in locker._sick_submit_button.first.configure.call_args_list
|
|
||||||
]
|
|
||||||
assert "disabled" in states
|
|
||||||
|
|
||||||
def test_renders_recent_history_when_present(
|
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
||||||
) -> None:
|
|
||||||
"""Renders recent history when present."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
history = SickHistory(
|
|
||||||
justifications=[
|
|
||||||
{"date": "2026-05-01", "symptom": "fever", "severity": 7},
|
|
||||||
],
|
|
||||||
)
|
|
||||||
with patch.object(_sick_tracker, "load_history", return_value=history):
|
|
||||||
locker._show_sick_justification()
|
|
||||||
labels = [call.kwargs.get("text", "") for call in mock_tk.Label.call_args_list]
|
|
||||||
assert any("Recent sick days" in t for t in labels)
|
|
||||||
|
|
||||||
|
|
||||||
class TestUpdateCommitmentForcedDelay:
|
|
||||||
"""Tests for _update_commitment_forced_delay."""
|
|
||||||
|
|
||||||
def test_ticks_down(
|
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
||||||
) -> None:
|
|
||||||
"""Ticks down."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
locker._sick_submit_button = MagicMock()
|
|
||||||
locker._commitment_forced_remaining = 3
|
|
||||||
locker._update_commitment_forced_delay()
|
|
||||||
assert locker._commitment_forced_remaining == 2
|
|
||||||
locker.root.after.assert_called()
|
|
||||||
|
|
||||||
def test_enables_when_done(
|
|
||||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
|
||||||
) -> None:
|
|
||||||
"""Enables when done."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
|
||||||
locker._sick_submit_button = MagicMock()
|
|
||||||
locker._commitment_forced_remaining = 0
|
|
||||||
locker._update_commitment_forced_delay()
|
|
||||||
locker._sick_submit_button.config.assert_called_with(
|
|
||||||
text="SUBMIT", state="normal"
|
|
||||||
)
|
|
||||||
@ -242,3 +242,48 @@ class TestRunStatusWorkoutLog:
|
|||||||
run_status(locker)
|
run_status(locker)
|
||||||
out = capsys.readouterr().out
|
out = capsys.readouterr().out
|
||||||
assert "heat_skip" in out
|
assert "heat_skip" in out
|
||||||
|
|
||||||
|
|
||||||
|
class TestWeeklyTotalUsesPerWorkoutRule:
|
||||||
|
"""The final summary must count each verified workout, not days-with-any."""
|
||||||
|
|
||||||
|
def test_multiple_same_day_workouts_all_count(
|
||||||
|
self, tmp_path: Path, capsys: pytest.CaptureFixture
|
||||||
|
) -> None:
|
||||||
|
"""One day with 2 manual + 3 verified entries = 5, not capped at 1.
|
||||||
|
|
||||||
|
Regression test: the summary used to derive its total from a
|
||||||
|
per-day checkmark count (max 1 per day), undercounting any day
|
||||||
|
holding more than one counted workout — exactly what multi-workout
|
||||||
|
days are supposed to support. Also covers manual workouts counting
|
||||||
|
individually (no once-per-day collapse), same as verified ones.
|
||||||
|
"""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
today = datetime.now(tz=timezone.utc).astimezone().date().isoformat()
|
||||||
|
log_file = tmp_path / "log.json"
|
||||||
|
log_file.write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
today: [
|
||||||
|
{"workout_data": {"type": "manual_workout", "source": "gym"}},
|
||||||
|
{"workout_data": {"type": "runnerup_verified", "source": "a"}},
|
||||||
|
{"workout_data": {"type": "phone_verified", "source": "b"}},
|
||||||
|
{"workout_data": {"type": "runnerup_verified", "source": "c"}},
|
||||||
|
{"workout_data": {"type": "manual_workout", "source": "gym2"}},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
eb_file = tmp_path / "eb.json"
|
||||||
|
# n_filled=0 so the summary is derived purely from before_count.
|
||||||
|
locker = _make_locker(log_file, n_filled=0)
|
||||||
|
with (
|
||||||
|
patch("screen_locker._status.EXTRA_BENEFITS_FILE", eb_file),
|
||||||
|
patch("screen_locker._status.current_streak", return_value=0),
|
||||||
|
patch("screen_locker._status.has_extended_early_bird", return_value=False),
|
||||||
|
patch("sys.exit"),
|
||||||
|
):
|
||||||
|
run_status(locker)
|
||||||
|
out = capsys.readouterr().out
|
||||||
|
assert "Weekly minimum met exactly (5/5)." in out
|
||||||
|
|||||||
@ -1,63 +0,0 @@
|
|||||||
"""Tests for run_status's weekly-total rule.
|
|
||||||
|
|
||||||
Split out of test_status.py for the 250-line cap.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
from screen_locker._status import run_status
|
|
||||||
from screen_locker.tests.conftest import _make_locker
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
class TestWeeklyTotalUsesPerWorkoutRule:
|
|
||||||
"""The final summary must count each verified workout, not days-with-any."""
|
|
||||||
|
|
||||||
def test_multiple_same_day_workouts_all_count(
|
|
||||||
self, tmp_path: Path, capsys: pytest.CaptureFixture
|
|
||||||
) -> None:
|
|
||||||
"""One day with 2 manual + 3 verified entries = 5, not capped at 1.
|
|
||||||
|
|
||||||
Regression test: the summary used to derive its total from a
|
|
||||||
per-day checkmark count (max 1 per day), undercounting any day
|
|
||||||
holding more than one counted workout — exactly what multi-workout
|
|
||||||
days are supposed to support. Also covers manual workouts counting
|
|
||||||
individually (no once-per-day collapse), same as verified ones.
|
|
||||||
"""
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
today = datetime.now(tz=timezone.utc).astimezone().date().isoformat()
|
|
||||||
log_file = tmp_path / "log.json"
|
|
||||||
log_file.write_text(
|
|
||||||
json.dumps(
|
|
||||||
{
|
|
||||||
today: [
|
|
||||||
{"workout_data": {"type": "manual_workout", "source": "gym"}},
|
|
||||||
{"workout_data": {"type": "runnerup_verified", "source": "a"}},
|
|
||||||
{"workout_data": {"type": "phone_verified", "source": "b"}},
|
|
||||||
{"workout_data": {"type": "runnerup_verified", "source": "c"}},
|
|
||||||
{"workout_data": {"type": "manual_workout", "source": "gym2"}},
|
|
||||||
]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
eb_file = tmp_path / "eb.json"
|
|
||||||
# n_filled=0 so the summary is derived purely from before_count.
|
|
||||||
locker = _make_locker(log_file, n_filled=0)
|
|
||||||
with (
|
|
||||||
patch("screen_locker._status.EXTRA_BENEFITS_FILE", eb_file),
|
|
||||||
patch("screen_locker._status.current_streak", return_value=0),
|
|
||||||
patch("screen_locker._status.has_extended_early_bird", return_value=False),
|
|
||||||
patch("sys.exit"),
|
|
||||||
):
|
|
||||||
run_status(locker)
|
|
||||||
out = capsys.readouterr().out
|
|
||||||
assert "Weekly minimum met exactly (5/5)." in out
|
|
||||||
@ -2,12 +2,14 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import TYPE_CHECKING
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from screen_locker._compliance_state import AutoUpgradeOpportunity
|
from screen_locker._compliance_state import AutoUpgradeOpportunity
|
||||||
|
from screen_locker._status_view_verify import (
|
||||||
if TYPE_CHECKING:
|
PhoneCheckOutcome,
|
||||||
from unittest.mock import MagicMock
|
_backfill_week_and_apply_bonus,
|
||||||
|
_verify_phone_then_runnerup,
|
||||||
|
)
|
||||||
from screen_locker.tests._status_view_helpers import (
|
from screen_locker.tests._status_view_helpers import (
|
||||||
_day,
|
_day,
|
||||||
_lock_explanation,
|
_lock_explanation,
|
||||||
@ -21,10 +23,7 @@ from screen_locker.tests._status_view_helpers import (
|
|||||||
|
|
||||||
|
|
||||||
class TestSectionToday:
|
class TestSectionToday:
|
||||||
"""SectionToday."""
|
|
||||||
|
|
||||||
def test_counted_shows_checkmark_and_entry(self, mock_tk: MagicMock) -> None:
|
def test_counted_shows_checkmark_and_entry(self, mock_tk: MagicMock) -> None:
|
||||||
"""Counted shows checkmark and entry."""
|
|
||||||
snap = _snapshot(
|
snap = _snapshot(
|
||||||
today=_day(
|
today=_day(
|
||||||
entry_types=("phone_verified",),
|
entry_types=("phone_verified",),
|
||||||
@ -39,19 +38,16 @@ class TestSectionToday:
|
|||||||
assert any(t == "gym" for t in texts)
|
assert any(t == "gym" for t in texts)
|
||||||
|
|
||||||
def test_sick_day_shows_sick_mark(self, mock_tk: MagicMock) -> None:
|
def test_sick_day_shows_sick_mark(self, mock_tk: MagicMock) -> None:
|
||||||
"""Sick day shows sick mark."""
|
|
||||||
snap = _snapshot(today=_day(entry_types=(), is_sick_day=True))
|
snap = _snapshot(today=_day(entry_types=(), is_sick_day=True))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert any("😷" in t and "sick day" in t for t in _texts(mock_tk))
|
assert any("😷" in t and "sick day" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_no_entry_shows_dash(self, mock_tk: MagicMock) -> None:
|
def test_no_entry_shows_dash(self, mock_tk: MagicMock) -> None:
|
||||||
"""No entry shows dash."""
|
|
||||||
snap = _snapshot(today=_day(entry_types=(), is_sick_day=False))
|
snap = _snapshot(today=_day(entry_types=(), is_sick_day=False))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert any("no entry yet" in t for t in _texts(mock_tk))
|
assert any("no entry yet" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_empty_source_adds_no_extra_line(self, mock_tk: MagicMock) -> None:
|
def test_empty_source_adds_no_extra_line(self, mock_tk: MagicMock) -> None:
|
||||||
"""Empty source adds no extra line."""
|
|
||||||
snap = _snapshot(
|
snap = _snapshot(
|
||||||
today=_day(
|
today=_day(
|
||||||
entry_types=("phone_verified",),
|
entry_types=("phone_verified",),
|
||||||
@ -67,24 +63,19 @@ class TestSectionToday:
|
|||||||
|
|
||||||
|
|
||||||
class TestSectionWeek:
|
class TestSectionWeek:
|
||||||
"""SectionWeek."""
|
|
||||||
|
|
||||||
def test_shows_remaining_message_when_under_minimum(
|
def test_shows_remaining_message_when_under_minimum(
|
||||||
self, mock_tk: MagicMock
|
self, mock_tk: MagicMock
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Shows remaining message when under minimum."""
|
|
||||||
snap = _snapshot(week=_week(counted_count=2, remaining=2, extra=0))
|
snap = _snapshot(week=_week(counted_count=2, remaining=2, extra=0))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert any("Need 2 more this week." in t for t in _texts(mock_tk))
|
assert any("Need 2 more this week." in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_shows_extra_message_when_over_minimum(self, mock_tk: MagicMock) -> None:
|
def test_shows_extra_message_when_over_minimum(self, mock_tk: MagicMock) -> None:
|
||||||
"""Shows extra message when over minimum."""
|
|
||||||
snap = _snapshot(week=_week(counted_count=5, remaining=0, extra=1))
|
snap = _snapshot(week=_week(counted_count=5, remaining=0, extra=1))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert any("above the weekly minimum" in t for t in _texts(mock_tk))
|
assert any("above the weekly minimum" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_shows_neither_message_at_exact_minimum(self, mock_tk: MagicMock) -> None:
|
def test_shows_neither_message_at_exact_minimum(self, mock_tk: MagicMock) -> None:
|
||||||
"""Shows neither message at exact minimum."""
|
|
||||||
snap = _snapshot(week=_week(counted_count=4, remaining=0, extra=0))
|
snap = _snapshot(week=_week(counted_count=4, remaining=0, extra=0))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
texts = _texts(mock_tk)
|
texts = _texts(mock_tk)
|
||||||
@ -92,7 +83,6 @@ class TestSectionWeek:
|
|||||||
assert not any("above the weekly minimum" in t for t in texts)
|
assert not any("above the weekly minimum" in t for t in texts)
|
||||||
|
|
||||||
def test_renders_a_line_per_day(self, mock_tk: MagicMock) -> None:
|
def test_renders_a_line_per_day(self, mock_tk: MagicMock) -> None:
|
||||||
"""Renders a line per day."""
|
|
||||||
days = (
|
days = (
|
||||||
_day(
|
_day(
|
||||||
date="2024-01-01",
|
date="2024-01-01",
|
||||||
@ -113,12 +103,9 @@ class TestSectionWeek:
|
|||||||
|
|
||||||
|
|
||||||
class TestSectionLockExplanation:
|
class TestSectionLockExplanation:
|
||||||
"""SectionLockExplanation."""
|
|
||||||
|
|
||||||
def test_fired_with_auto_upgrade_and_heat_skip_pending(
|
def test_fired_with_auto_upgrade_and_heat_skip_pending(
|
||||||
self, mock_tk: MagicMock
|
self, mock_tk: MagicMock
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Fired with auto upgrade and heat skip pending."""
|
|
||||||
snap = _snapshot(
|
snap = _snapshot(
|
||||||
lock_explanation=_lock_explanation(
|
lock_explanation=_lock_explanation(
|
||||||
fired=True,
|
fired=True,
|
||||||
@ -135,7 +122,6 @@ class TestSectionLockExplanation:
|
|||||||
assert any("Pending auto-upgrade: will try phone" in t for t in texts)
|
assert any("Pending auto-upgrade: will try phone" in t for t in texts)
|
||||||
|
|
||||||
def test_not_fired_no_auto_upgrade(self, mock_tk: MagicMock) -> None:
|
def test_not_fired_no_auto_upgrade(self, mock_tk: MagicMock) -> None:
|
||||||
"""Not fired no auto upgrade."""
|
|
||||||
snap = _snapshot(
|
snap = _snapshot(
|
||||||
lock_explanation=_lock_explanation(fired=False, reason="Skipped.")
|
lock_explanation=_lock_explanation(fired=False, reason="Skipped.")
|
||||||
)
|
)
|
||||||
@ -157,10 +143,7 @@ class TestSectionLockExplanation:
|
|||||||
|
|
||||||
|
|
||||||
class TestSectionSickBudget:
|
class TestSectionSickBudget:
|
||||||
"""SectionSickBudget."""
|
|
||||||
|
|
||||||
def test_exhausted_uses_warning_color(self, mock_tk: MagicMock) -> None:
|
def test_exhausted_uses_warning_color(self, mock_tk: MagicMock) -> None:
|
||||||
"""Exhausted uses warning color."""
|
|
||||||
snap = _snapshot(sick_budget=_sick_budget(used_7d=1, exhausted=True))
|
snap = _snapshot(sick_budget=_sick_budget(used_7d=1, exhausted=True))
|
||||||
window = _make_window(mock_tk, snap)
|
window = _make_window(mock_tk, snap)
|
||||||
calls = [
|
calls = [
|
||||||
@ -171,7 +154,6 @@ class TestSectionSickBudget:
|
|||||||
assert any(c.kwargs.get("fg") == window._colors.danger for c in calls)
|
assert any(c.kwargs.get("fg") == window._colors.danger for c in calls)
|
||||||
|
|
||||||
def test_not_exhausted_uses_normal_color(self, mock_tk: MagicMock) -> None:
|
def test_not_exhausted_uses_normal_color(self, mock_tk: MagicMock) -> None:
|
||||||
"""Not exhausted uses normal color."""
|
|
||||||
snap = _snapshot(sick_budget=_sick_budget(used_7d=0, exhausted=False))
|
snap = _snapshot(sick_budget=_sick_budget(used_7d=0, exhausted=False))
|
||||||
window = _make_window(mock_tk, snap)
|
window = _make_window(mock_tk, snap)
|
||||||
calls = [
|
calls = [
|
||||||
@ -183,24 +165,130 @@ class TestSectionSickBudget:
|
|||||||
|
|
||||||
|
|
||||||
class TestSectionShutdown:
|
class TestSectionShutdown:
|
||||||
"""SectionShutdown."""
|
|
||||||
|
|
||||||
def test_tonight_present_shows_live_config(self, mock_tk: MagicMock) -> None:
|
def test_tonight_present_shows_live_config(self, mock_tk: MagicMock) -> None:
|
||||||
"""Tonight present shows live config."""
|
|
||||||
snap = _snapshot(shutdown=_shutdown(tonight=(22, 23, 5)))
|
snap = _snapshot(shutdown=_shutdown(tonight=(22, 23, 5)))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert any("22:00" in t and "23:00" in t for t in _texts(mock_tk))
|
assert any("22:00" in t and "23:00" in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_tonight_absent_shows_unavailable_message(self, mock_tk: MagicMock) -> None:
|
def test_tonight_absent_shows_unavailable_message(self, mock_tk: MagicMock) -> None:
|
||||||
"""Tonight absent shows unavailable message."""
|
|
||||||
snap = _snapshot(shutdown=_shutdown(tonight=None))
|
snap = _snapshot(shutdown=_shutdown(tonight=None))
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
assert any("Live shutdown config unavailable." in t for t in _texts(mock_tk))
|
assert any("Live shutdown config unavailable." in t for t in _texts(mock_tk))
|
||||||
|
|
||||||
def test_shows_rest_of_week_and_next_week_preview(self, mock_tk: MagicMock) -> None:
|
def test_shows_rest_of_week_and_next_week_preview(self, mock_tk: MagicMock) -> None:
|
||||||
"""Shows rest of week and next week preview."""
|
|
||||||
snap = _snapshot()
|
snap = _snapshot()
|
||||||
_make_window(mock_tk, snap)
|
_make_window(mock_tk, snap)
|
||||||
texts = _texts(mock_tk)
|
texts = _texts(mock_tk)
|
||||||
assert any("Rest of week:" in t for t in texts)
|
assert any("Rest of week:" in t for t in texts)
|
||||||
assert any("Next week (speculative):" 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()
|
||||||
|
|
||||||
|
|
||||||
|
class TestBackfillWeekAndApplyBonus:
|
||||||
|
"""The week-scan fallback: backfill unlogged days, apply the earned bonus."""
|
||||||
|
|
||||||
|
def test_nothing_filled_returns_none(self) -> None:
|
||||||
|
verifier = MagicMock()
|
||||||
|
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,
|
||||||
|
):
|
||||||
|
assert _backfill_week_and_apply_bonus(verifier) is None
|
||||||
|
verifier._adjust_shutdown_time_by.assert_not_called()
|
||||||
|
|
||||||
|
def test_fill_at_or_below_minimum_earns_no_bonus(self) -> None:
|
||||||
|
"""Filling up to (not past) the weekly minimum earns no shutdown push."""
|
||||||
|
verifier = MagicMock()
|
||||||
|
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=[3, 4],
|
||||||
|
):
|
||||||
|
message = _backfill_week_and_apply_bonus(verifier)
|
||||||
|
|
||||||
|
assert message == "Auto-filled 1 workout from earlier this week."
|
||||||
|
verifier._adjust_shutdown_time_by.assert_not_called()
|
||||||
|
|
||||||
|
def test_fill_past_minimum_applies_bonus(self) -> None:
|
||||||
|
verifier = MagicMock()
|
||||||
|
verifier._scan_and_fill_week_runnerup.return_value = 1
|
||||||
|
verifier._try_fill_stronglifts_for_week.return_value = 1
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"screen_locker._status_view_verify.count_weekly_workouts",
|
||||||
|
side_effect=[4, 7],
|
||||||
|
):
|
||||||
|
message = _backfill_week_and_apply_bonus(verifier)
|
||||||
|
|
||||||
|
assert message == (
|
||||||
|
"Auto-filled 2 workouts from earlier this week. +2h shutdown time."
|
||||||
|
)
|
||||||
|
verifier._adjust_shutdown_time_by.assert_called_once_with(2)
|
||||||
|
|||||||
@ -1,58 +0,0 @@
|
|||||||
"""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 (
|
|
||||||
_backfill_week_and_apply_bonus,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestBackfillWeekAndApplyBonus:
|
|
||||||
"""The week-scan fallback: backfill unlogged days, apply the earned bonus."""
|
|
||||||
|
|
||||||
def test_nothing_filled_returns_none(self) -> None:
|
|
||||||
"""Nothing filled returns none."""
|
|
||||||
verifier = MagicMock()
|
|
||||||
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,
|
|
||||||
):
|
|
||||||
assert _backfill_week_and_apply_bonus(verifier) is None
|
|
||||||
verifier._adjust_shutdown_time_by.assert_not_called()
|
|
||||||
|
|
||||||
def test_fill_at_or_below_minimum_earns_no_bonus(self) -> None:
|
|
||||||
"""Filling up to (not past) the weekly minimum earns no shutdown push."""
|
|
||||||
verifier = MagicMock()
|
|
||||||
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=[3, 4],
|
|
||||||
):
|
|
||||||
message = _backfill_week_and_apply_bonus(verifier)
|
|
||||||
|
|
||||||
assert message == "Auto-filled 1 workout from earlier this week."
|
|
||||||
verifier._adjust_shutdown_time_by.assert_not_called()
|
|
||||||
|
|
||||||
def test_fill_past_minimum_applies_bonus(self) -> None:
|
|
||||||
"""Fill past minimum applies bonus."""
|
|
||||||
verifier = MagicMock()
|
|
||||||
verifier._scan_and_fill_week_runnerup.return_value = 1
|
|
||||||
verifier._try_fill_stronglifts_for_week.return_value = 1
|
|
||||||
|
|
||||||
with patch(
|
|
||||||
"screen_locker._status_view_verify.count_weekly_workouts",
|
|
||||||
side_effect=[4, 7],
|
|
||||||
):
|
|
||||||
message = _backfill_week_and_apply_bonus(verifier)
|
|
||||||
|
|
||||||
assert message == (
|
|
||||||
"Auto-filled 2 workouts from earlier this week. +2h shutdown time."
|
|
||||||
)
|
|
||||||
verifier._adjust_shutdown_time_by.assert_called_once_with(2)
|
|
||||||
@ -1,74 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@ -244,3 +244,108 @@ class TestPollVerifyWorkoutCheck:
|
|||||||
"verified",
|
"verified",
|
||||||
"Found workout",
|
"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 = []
|
||||||
|
|||||||
@ -1,116 +0,0 @@
|
|||||||
"""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 = []
|
|
||||||
@ -10,7 +10,9 @@ from unittest.mock import patch
|
|||||||
|
|
||||||
from screen_locker._weekly_check import (
|
from screen_locker._weekly_check import (
|
||||||
_RELAXED_WEEKDAYS,
|
_RELAXED_WEEKDAYS,
|
||||||
|
WEEKLY_WORKOUT_MINIMUM,
|
||||||
count_weekly_workouts,
|
count_weekly_workouts,
|
||||||
|
has_weekly_minimum,
|
||||||
is_relaxed_day,
|
is_relaxed_day,
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -50,42 +52,31 @@ def _make_log(entries: dict[str, str], log_file: Path) -> Path:
|
|||||||
|
|
||||||
|
|
||||||
class TestIsRelaxedDay:
|
class TestIsRelaxedDay:
|
||||||
"""Tue-Thu are optional; Fri-Mon are enforced lock days."""
|
|
||||||
|
|
||||||
def test_monday_is_enforced(self) -> None:
|
def test_monday_is_enforced(self) -> None:
|
||||||
"""Monday is an enforced day."""
|
|
||||||
assert is_relaxed_day(today=_dt(0)) is False
|
assert is_relaxed_day(today=_dt(0)) is False
|
||||||
|
|
||||||
def test_tuesday_is_relaxed(self) -> None:
|
def test_tuesday_is_relaxed(self) -> None:
|
||||||
"""Tuesday is relaxed."""
|
|
||||||
assert is_relaxed_day(today=_dt(1)) is True
|
assert is_relaxed_day(today=_dt(1)) is True
|
||||||
|
|
||||||
def test_wednesday_is_relaxed(self) -> None:
|
def test_wednesday_is_relaxed(self) -> None:
|
||||||
"""Wednesday is relaxed."""
|
|
||||||
assert is_relaxed_day(today=_dt(2)) is True
|
assert is_relaxed_day(today=_dt(2)) is True
|
||||||
|
|
||||||
def test_thursday_is_relaxed(self) -> None:
|
def test_thursday_is_relaxed(self) -> None:
|
||||||
"""Thursday is relaxed."""
|
|
||||||
assert is_relaxed_day(today=_dt(3)) is True
|
assert is_relaxed_day(today=_dt(3)) is True
|
||||||
|
|
||||||
def test_friday_is_enforced(self) -> None:
|
def test_friday_is_enforced(self) -> None:
|
||||||
"""Friday is an enforced day."""
|
|
||||||
assert is_relaxed_day(today=_dt(4)) is False
|
assert is_relaxed_day(today=_dt(4)) is False
|
||||||
|
|
||||||
def test_saturday_is_enforced(self) -> None:
|
def test_saturday_is_enforced(self) -> None:
|
||||||
"""Saturday is an enforced day."""
|
|
||||||
assert is_relaxed_day(today=_dt(5)) is False
|
assert is_relaxed_day(today=_dt(5)) is False
|
||||||
|
|
||||||
def test_sunday_is_enforced(self) -> None:
|
def test_sunday_is_enforced(self) -> None:
|
||||||
"""Sunday is an enforced day."""
|
|
||||||
assert is_relaxed_day(today=_dt(6)) is False
|
assert is_relaxed_day(today=_dt(6)) is False
|
||||||
|
|
||||||
def test_relaxed_weekdays_constant_correct(self) -> None:
|
def test_relaxed_weekdays_constant_correct(self) -> None:
|
||||||
"""The relaxed set is exactly Tue/Wed/Thu (weekday 1-3)."""
|
|
||||||
assert frozenset({1, 2, 3}) == _RELAXED_WEEKDAYS
|
assert frozenset({1, 2, 3}) == _RELAXED_WEEKDAYS
|
||||||
|
|
||||||
def test_uses_local_time_by_default(self) -> None:
|
def test_uses_local_time_by_default(self) -> None:
|
||||||
"""Called with no argument it reads local time and still returns a bool."""
|
|
||||||
result = is_relaxed_day()
|
result = is_relaxed_day()
|
||||||
assert isinstance(result, bool)
|
assert isinstance(result, bool)
|
||||||
|
|
||||||
@ -96,61 +87,50 @@ class TestIsRelaxedDay:
|
|||||||
|
|
||||||
|
|
||||||
class TestCountWeeklyWorkouts:
|
class TestCountWeeklyWorkouts:
|
||||||
"""Counting verified workouts inside the current ISO week."""
|
|
||||||
|
|
||||||
def test_no_log_file_returns_zero(self, tmp_path: Path) -> None:
|
def test_no_log_file_returns_zero(self, tmp_path: Path) -> None:
|
||||||
"""A missing log counts as zero rather than raising."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
||||||
|
|
||||||
def test_corrupt_json_returns_zero(self, tmp_path: Path) -> None:
|
def test_corrupt_json_returns_zero(self, tmp_path: Path) -> None:
|
||||||
"""Unparsable JSON counts as zero rather than raising."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
log.write_text("{not valid json}")
|
log.write_text("{not valid json}")
|
||||||
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
||||||
|
|
||||||
def test_oserror_returns_zero(self, tmp_path: Path) -> None:
|
def test_oserror_returns_zero(self, tmp_path: Path) -> None:
|
||||||
"""An unreadable log counts as zero rather than raising."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
log.write_text("{}")
|
log.write_text("{}")
|
||||||
with patch("builtins.open", side_effect=OSError("no permission")):
|
with patch("builtins.open", side_effect=OSError("no permission")):
|
||||||
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
||||||
|
|
||||||
def test_counts_phone_verified_in_current_week(self, tmp_path: Path) -> None:
|
def test_counts_phone_verified_in_current_week(self, tmp_path: Path) -> None:
|
||||||
"""Two phone-verified days in the same week count as two."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
# Mon=2025-05-19, Tue=2025-05-20 both in same week; check on Fri=2025-05-23
|
# Mon=2025-05-19, Tue=2025-05-20 both in same week; check on Fri=2025-05-23
|
||||||
_make_log({"2025-05-19": "phone_verified", "2025-05-20": "phone_verified"}, log)
|
_make_log({"2025-05-19": "phone_verified", "2025-05-20": "phone_verified"}, log)
|
||||||
assert count_weekly_workouts(log, today=_dt(4)) == 2
|
assert count_weekly_workouts(log, today=_dt(4)) == 2
|
||||||
|
|
||||||
def test_sick_day_not_counted(self, tmp_path: Path) -> None:
|
def test_sick_day_not_counted(self, tmp_path: Path) -> None:
|
||||||
"""A sick day is not a workout."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
_make_log({"2025-05-19": "sick_day"}, log)
|
_make_log({"2025-05-19": "sick_day"}, log)
|
||||||
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
||||||
|
|
||||||
def test_early_bird_not_counted(self, tmp_path: Path) -> None:
|
def test_early_bird_not_counted(self, tmp_path: Path) -> None:
|
||||||
"""An early-bird entry is not a workout."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
_make_log({"2025-05-19": "early_bird"}, log)
|
_make_log({"2025-05-19": "early_bird"}, log)
|
||||||
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
||||||
|
|
||||||
def test_previous_week_not_counted(self, tmp_path: Path) -> None:
|
def test_previous_week_not_counted(self, tmp_path: Path) -> None:
|
||||||
"""Last week's workouts do not count toward this week."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
# 2025-05-12 is the Monday of the previous week
|
# 2025-05-12 is the Monday of the previous week
|
||||||
_make_log({"2025-05-12": "phone_verified"}, log)
|
_make_log({"2025-05-12": "phone_verified"}, log)
|
||||||
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
||||||
|
|
||||||
def test_future_date_not_counted(self, tmp_path: Path) -> None:
|
def test_future_date_not_counted(self, tmp_path: Path) -> None:
|
||||||
"""A date after today does not count, even in the same week."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
# 2025-05-24 is Saturday, checking on Friday 2025-05-23
|
# 2025-05-24 is Saturday, checking on Friday 2025-05-23
|
||||||
_make_log({"2025-05-24": "phone_verified"}, log)
|
_make_log({"2025-05-24": "phone_verified"}, log)
|
||||||
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
||||||
|
|
||||||
def test_invalid_date_key_skipped(self, tmp_path: Path) -> None:
|
def test_invalid_date_key_skipped(self, tmp_path: Path) -> None:
|
||||||
"""An unparsable date key is skipped, and valid siblings still count."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
data: dict[str, Any] = {
|
data: dict[str, Any] = {
|
||||||
"not-a-date": {
|
"not-a-date": {
|
||||||
@ -166,14 +146,12 @@ class TestCountWeeklyWorkouts:
|
|||||||
assert count_weekly_workouts(log, today=_dt(4)) == 1
|
assert count_weekly_workouts(log, today=_dt(4)) == 1
|
||||||
|
|
||||||
def test_non_dict_entry_skipped(self, tmp_path: Path) -> None:
|
def test_non_dict_entry_skipped(self, tmp_path: Path) -> None:
|
||||||
"""An entry that is not a dict is skipped rather than raising."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
data: dict[str, Any] = {"2025-05-19": "not-a-dict"}
|
data: dict[str, Any] = {"2025-05-19": "not-a-dict"}
|
||||||
log.write_text(json.dumps(data))
|
log.write_text(json.dumps(data))
|
||||||
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
assert count_weekly_workouts(log, today=_dt(4)) == 0
|
||||||
|
|
||||||
def test_counts_up_to_four(self, tmp_path: Path) -> None:
|
def test_counts_up_to_four(self, tmp_path: Path) -> None:
|
||||||
"""Four workouts in one week count as four (no cap below the minimum)."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
_make_log(
|
_make_log(
|
||||||
{
|
{
|
||||||
@ -187,21 +165,18 @@ class TestCountWeeklyWorkouts:
|
|||||||
assert count_weekly_workouts(log, today=_dt(4)) == 4
|
assert count_weekly_workouts(log, today=_dt(4)) == 4
|
||||||
|
|
||||||
def test_today_counts_if_this_week(self, tmp_path: Path) -> None:
|
def test_today_counts_if_this_week(self, tmp_path: Path) -> None:
|
||||||
"""Today's own workout counts."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
# today is Friday 2025-05-23
|
# today is Friday 2025-05-23
|
||||||
_make_log({"2025-05-23": "phone_verified"}, log)
|
_make_log({"2025-05-23": "phone_verified"}, log)
|
||||||
assert count_weekly_workouts(log, today=_dt(4)) == 1
|
assert count_weekly_workouts(log, today=_dt(4)) == 1
|
||||||
|
|
||||||
def test_monday_start_of_week_counted(self, tmp_path: Path) -> None:
|
def test_monday_start_of_week_counted(self, tmp_path: Path) -> None:
|
||||||
"""Monday is the first day of the week, so it counts when checked on Monday."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
_make_log({"2025-05-19": "phone_verified"}, log)
|
_make_log({"2025-05-19": "phone_verified"}, log)
|
||||||
# Checking on Monday itself (today=Mon)
|
# Checking on Monday itself (today=Mon)
|
||||||
assert count_weekly_workouts(log, today=_dt(0)) == 1
|
assert count_weekly_workouts(log, today=_dt(0)) == 1
|
||||||
|
|
||||||
def test_mixed_types_only_verified_counted(self, tmp_path: Path) -> None:
|
def test_mixed_types_only_verified_counted(self, tmp_path: Path) -> None:
|
||||||
"""Only verified workouts count; sick/early-bird entries are ignored."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
log = tmp_path / "workout_log.json"
|
||||||
_make_log(
|
_make_log(
|
||||||
{
|
{
|
||||||
@ -234,3 +209,51 @@ class TestCountWeeklyWorkouts:
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# has_weekly_minimum
|
# has_weekly_minimum
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestHasWeeklyMinimum:
|
||||||
|
def test_zero_workouts_is_false(self, tmp_path: Path) -> None:
|
||||||
|
log = tmp_path / "workout_log.json"
|
||||||
|
assert has_weekly_minimum(log, today=_dt(4)) is False
|
||||||
|
|
||||||
|
def test_three_workouts_is_false(self, tmp_path: Path) -> None:
|
||||||
|
log = tmp_path / "workout_log.json"
|
||||||
|
_make_log(
|
||||||
|
{
|
||||||
|
"2025-05-19": "phone_verified",
|
||||||
|
"2025-05-20": "phone_verified",
|
||||||
|
"2025-05-21": "phone_verified",
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
)
|
||||||
|
assert has_weekly_minimum(log, today=_dt(4)) is False
|
||||||
|
|
||||||
|
def test_four_workouts_is_false(self, tmp_path: Path) -> None:
|
||||||
|
log = tmp_path / "workout_log.json"
|
||||||
|
_make_log(
|
||||||
|
{
|
||||||
|
"2025-05-19": "phone_verified",
|
||||||
|
"2025-05-20": "phone_verified",
|
||||||
|
"2025-05-21": "phone_verified",
|
||||||
|
"2025-05-22": "phone_verified",
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
)
|
||||||
|
assert has_weekly_minimum(log, today=_dt(4)) is False
|
||||||
|
|
||||||
|
def test_five_workouts_is_true(self, tmp_path: Path) -> None:
|
||||||
|
log = tmp_path / "workout_log.json"
|
||||||
|
_make_log(
|
||||||
|
{
|
||||||
|
"2025-05-19": "phone_verified",
|
||||||
|
"2025-05-20": "phone_verified",
|
||||||
|
"2025-05-21": "phone_verified",
|
||||||
|
"2025-05-22": "phone_verified",
|
||||||
|
"2025-05-23": "phone_verified",
|
||||||
|
},
|
||||||
|
log,
|
||||||
|
)
|
||||||
|
assert has_weekly_minimum(log, today=_dt(4)) is True
|
||||||
|
|
||||||
|
def test_weekly_workout_minimum_constant(self) -> None:
|
||||||
|
assert WEEKLY_WORKOUT_MINIMUM == 5
|
||||||
|
|||||||
@ -1,73 +0,0 @@
|
|||||||
"""Tests for _weekly_check.has_weekly_minimum.
|
|
||||||
|
|
||||||
Split out of test_weekly_check.py for the 250-line cap; the shared _dt /
|
|
||||||
_make_log helpers stay in that module and are imported here.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
|
|
||||||
from screen_locker._weekly_check import (
|
|
||||||
WEEKLY_WORKOUT_MINIMUM,
|
|
||||||
has_weekly_minimum,
|
|
||||||
)
|
|
||||||
from screen_locker.tests.test_weekly_check import _dt, _make_log
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
|
|
||||||
class TestHasWeeklyMinimum:
|
|
||||||
"""has_weekly_minimum counts verified workouts against the weekly bar."""
|
|
||||||
|
|
||||||
def test_zero_workouts_is_false(self, tmp_path: Path) -> None:
|
|
||||||
"""An empty log does not meet the weekly minimum."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
|
||||||
assert has_weekly_minimum(log, today=_dt(4)) is False
|
|
||||||
|
|
||||||
def test_three_workouts_is_false(self, tmp_path: Path) -> None:
|
|
||||||
"""Three workouts is short of the five-workout bar."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
|
||||||
_make_log(
|
|
||||||
{
|
|
||||||
"2025-05-19": "phone_verified",
|
|
||||||
"2025-05-20": "phone_verified",
|
|
||||||
"2025-05-21": "phone_verified",
|
|
||||||
},
|
|
||||||
log,
|
|
||||||
)
|
|
||||||
assert has_weekly_minimum(log, today=_dt(4)) is False
|
|
||||||
|
|
||||||
def test_four_workouts_is_false(self, tmp_path: Path) -> None:
|
|
||||||
"""Four workouts is still one short of the bar."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
|
||||||
_make_log(
|
|
||||||
{
|
|
||||||
"2025-05-19": "phone_verified",
|
|
||||||
"2025-05-20": "phone_verified",
|
|
||||||
"2025-05-21": "phone_verified",
|
|
||||||
"2025-05-22": "phone_verified",
|
|
||||||
},
|
|
||||||
log,
|
|
||||||
)
|
|
||||||
assert has_weekly_minimum(log, today=_dt(4)) is False
|
|
||||||
|
|
||||||
def test_five_workouts_is_true(self, tmp_path: Path) -> None:
|
|
||||||
"""Five workouts meets the bar exactly."""
|
|
||||||
log = tmp_path / "workout_log.json"
|
|
||||||
_make_log(
|
|
||||||
{
|
|
||||||
"2025-05-19": "phone_verified",
|
|
||||||
"2025-05-20": "phone_verified",
|
|
||||||
"2025-05-21": "phone_verified",
|
|
||||||
"2025-05-22": "phone_verified",
|
|
||||||
"2025-05-23": "phone_verified",
|
|
||||||
},
|
|
||||||
log,
|
|
||||||
)
|
|
||||||
assert has_weekly_minimum(log, today=_dt(4)) is True
|
|
||||||
|
|
||||||
def test_weekly_workout_minimum_constant(self) -> None:
|
|
||||||
"""The bar is five workouts per ISO week."""
|
|
||||||
assert WEEKLY_WORKOUT_MINIMUM == 5
|
|
||||||
@ -5,13 +5,13 @@ from __future__ import annotations
|
|||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from unittest.mock import MagicMock, patch
|
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
|
from screen_locker.tests.conftest import create_locker, create_locker_relaxed_day
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from screen_locker.screen_lock import ScreenLocker
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# _check_today_state_exits: return True/False branches
|
# _check_today_state_exits: return True/False branches
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@ -33,7 +33,6 @@ class TestCheckTodayStateExits:
|
|||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Early bird upgrade success returns true."""
|
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
with (
|
with (
|
||||||
patch.object(locker, "_is_early_bird_pending", return_value=True),
|
patch.object(locker, "_is_early_bird_pending", return_value=True),
|
||||||
@ -49,7 +48,6 @@ class TestCheckTodayStateExits:
|
|||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Early bird upgrade fail returns false."""
|
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
with (
|
with (
|
||||||
patch.object(locker, "_is_early_bird_pending", return_value=True),
|
patch.object(locker, "_is_early_bird_pending", return_value=True),
|
||||||
@ -65,7 +63,6 @@ class TestCheckTodayStateExits:
|
|||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Early bird window active returns true."""
|
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
with (
|
with (
|
||||||
patch.object(locker, "_is_early_bird_pending", return_value=True),
|
patch.object(locker, "_is_early_bird_pending", return_value=True),
|
||||||
@ -80,7 +77,6 @@ class TestCheckTodayStateExits:
|
|||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Sick day auto upgrade returns true."""
|
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
with (
|
with (
|
||||||
patch.object(locker, "_is_early_bird_pending", return_value=False),
|
patch.object(locker, "_is_early_bird_pending", return_value=False),
|
||||||
@ -116,7 +112,6 @@ class TestCheckTodayStateExits:
|
|||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Workout skip today returns true."""
|
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
with (
|
with (
|
||||||
patch.object(locker, "_is_early_bird_pending", return_value=False),
|
patch.object(locker, "_is_early_bird_pending", return_value=False),
|
||||||
@ -136,7 +131,6 @@ class TestCheckTodayStateExits:
|
|||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Early bird time returns true."""
|
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
with (
|
with (
|
||||||
patch.object(locker, "_is_early_bird_pending", return_value=False),
|
patch.object(locker, "_is_early_bird_pending", return_value=False),
|
||||||
@ -158,7 +152,6 @@ class TestCheckTodayStateExits:
|
|||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""No exit conditions returns false."""
|
|
||||||
locker = self._make_locker(mock_tk, tmp_path)
|
locker = self._make_locker(mock_tk, tmp_path)
|
||||||
with (
|
with (
|
||||||
patch.object(locker, "_is_early_bird_pending", return_value=False),
|
patch.object(locker, "_is_early_bird_pending", return_value=False),
|
||||||
@ -183,7 +176,6 @@ class TestCheckNonVerifyExitsScheduledSkip:
|
|||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Scheduled skip return reached."""
|
|
||||||
locker = create_locker(mock_tk, tmp_path)
|
locker = create_locker(mock_tk, tmp_path)
|
||||||
with patch.object(locker, "_is_scheduled_skip_today", return_value=True):
|
with patch.object(locker, "_is_scheduled_skip_today", return_value=True):
|
||||||
locker._check_non_verify_exits()
|
locker._check_non_verify_exits()
|
||||||
@ -199,7 +191,6 @@ class TestRelaxedDayCloseAndRun:
|
|||||||
mock_sys_exit: MagicMock,
|
mock_sys_exit: MagicMock,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Relaxed day close and run use root directly."""
|
|
||||||
locker = create_locker_relaxed_day(mock_tk, tmp_path)
|
locker = create_locker_relaxed_day(mock_tk, tmp_path)
|
||||||
assert locker._lock is None
|
assert locker._lock is None
|
||||||
|
|
||||||
@ -214,3 +205,115 @@ class TestRelaxedDayCloseAndRun:
|
|||||||
# _check_non_verify_exits: heat-skip branch (reached after weekly minimum
|
# _check_non_verify_exits: heat-skip branch (reached after weekly minimum
|
||||||
# is not met — the only remaining same-day skip is genuine extreme heat)
|
# 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()
|
||||||
|
|||||||
@ -1,130 +0,0 @@
|
|||||||
"""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()
|
|
||||||
@ -8,14 +8,16 @@ and the cross-device merge. The backend selection (``sync_client`` /
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
from crdt_sync import Hlc, Record
|
from crdt_sync import GitHubSyncError, Hlc, Record
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from screen_locker import _workout_sync
|
from screen_locker import _workout_sync
|
||||||
from screen_locker.tests._workout_sync_fixtures import (
|
from screen_locker.tests._workout_sync_fixtures import (
|
||||||
_manual_payload,
|
_manual_payload,
|
||||||
_manual_record_dict,
|
_manual_record_dict,
|
||||||
|
_multi_device_client,
|
||||||
_record_json,
|
_record_json,
|
||||||
_session_payload,
|
_session_payload,
|
||||||
_session_record_dict,
|
_session_record_dict,
|
||||||
@ -31,19 +33,14 @@ from screen_locker.tests._workout_sync_fixtures import (
|
|||||||
|
|
||||||
|
|
||||||
class TestReadSyncToken:
|
class TestReadSyncToken:
|
||||||
"""ReadSyncToken."""
|
|
||||||
|
|
||||||
def test_returns_none_when_file_is_missing(self) -> None:
|
def test_returns_none_when_file_is_missing(self) -> None:
|
||||||
"""Returns none when file is missing."""
|
|
||||||
assert _workout_sync.read_sync_token() is None
|
assert _workout_sync.read_sync_token() is None
|
||||||
|
|
||||||
def test_returns_none_when_file_is_empty(self) -> None:
|
def test_returns_none_when_file_is_empty(self) -> None:
|
||||||
"""Returns none when file is empty."""
|
|
||||||
_workout_sync.SYNC_TOKEN_FILE.write_text(" \n")
|
_workout_sync.SYNC_TOKEN_FILE.write_text(" \n")
|
||||||
assert _workout_sync.read_sync_token() is None
|
assert _workout_sync.read_sync_token() is None
|
||||||
|
|
||||||
def test_returns_the_stripped_token(self) -> None:
|
def test_returns_the_stripped_token(self) -> None:
|
||||||
"""Returns the stripped token."""
|
|
||||||
_workout_sync.SYNC_TOKEN_FILE.write_text(" abc123 \n")
|
_workout_sync.SYNC_TOKEN_FILE.write_text(" abc123 \n")
|
||||||
assert _workout_sync.read_sync_token() == "abc123"
|
assert _workout_sync.read_sync_token() == "abc123"
|
||||||
|
|
||||||
@ -52,15 +49,12 @@ class TestIsSessionPayload:
|
|||||||
"""Sessions are identified by SHAPE (an ``exercises`` list), not ``kind``."""
|
"""Sessions are identified by SHAPE (an ``exercises`` list), not ``kind``."""
|
||||||
|
|
||||||
def test_true_for_a_dict_with_an_exercises_list(self) -> None:
|
def test_true_for_a_dict_with_an_exercises_list(self) -> None:
|
||||||
"""True for a dict with an exercises list."""
|
|
||||||
assert _workout_sync._is_session_payload(_session_payload()) is True
|
assert _workout_sync._is_session_payload(_session_payload()) is True
|
||||||
|
|
||||||
def test_true_even_with_an_empty_exercises_list(self) -> None:
|
def test_true_even_with_an_empty_exercises_list(self) -> None:
|
||||||
"""True even with an empty exercises list."""
|
|
||||||
assert _workout_sync._is_session_payload({"exercises": []}) is True
|
assert _workout_sync._is_session_payload({"exercises": []}) is True
|
||||||
|
|
||||||
def test_false_for_a_manual_workout(self) -> None:
|
def test_false_for_a_manual_workout(self) -> None:
|
||||||
"""False for a manual workout."""
|
|
||||||
assert _workout_sync._is_session_payload(_manual_payload()) is False
|
assert _workout_sync._is_session_payload(_manual_payload()) is False
|
||||||
|
|
||||||
def test_false_for_verified_records_sharing_the_same_log(self) -> None:
|
def test_false_for_verified_records_sharing_the_same_log(self) -> None:
|
||||||
@ -69,33 +63,24 @@ class TestIsSessionPayload:
|
|||||||
assert _workout_sync._is_session_payload({"kind": "phone_verified"}) is False
|
assert _workout_sync._is_session_payload({"kind": "phone_verified"}) is False
|
||||||
|
|
||||||
def test_false_when_exercises_is_not_a_list(self) -> None:
|
def test_false_when_exercises_is_not_a_list(self) -> None:
|
||||||
"""False when exercises is not a list."""
|
|
||||||
assert _workout_sync._is_session_payload({"exercises": "Squat"}) is False
|
assert _workout_sync._is_session_payload({"exercises": "Squat"}) is False
|
||||||
|
|
||||||
def test_false_for_a_non_dict_payload(self) -> None:
|
def test_false_for_a_non_dict_payload(self) -> None:
|
||||||
"""False for a non dict payload."""
|
|
||||||
assert _workout_sync._is_session_payload("not-a-dict") is False
|
assert _workout_sync._is_session_payload("not-a-dict") is False
|
||||||
assert _workout_sync._is_session_payload(None) is False
|
assert _workout_sync._is_session_payload(None) is False
|
||||||
|
|
||||||
|
|
||||||
class TestIsManualPayload:
|
class TestIsManualPayload:
|
||||||
"""IsManualPayload."""
|
|
||||||
|
|
||||||
def test_true_for_manual_kind(self) -> None:
|
def test_true_for_manual_kind(self) -> None:
|
||||||
"""True for manual kind."""
|
|
||||||
assert _workout_sync._is_manual_payload({"kind": "manual_workout"}) is True
|
assert _workout_sync._is_manual_payload({"kind": "manual_workout"}) is True
|
||||||
|
|
||||||
def test_false_for_session_or_non_dict(self) -> None:
|
def test_false_for_session_or_non_dict(self) -> None:
|
||||||
"""False for session or non dict."""
|
|
||||||
assert _workout_sync._is_manual_payload(_session_payload()) is False
|
assert _workout_sync._is_manual_payload(_session_payload()) is False
|
||||||
assert _workout_sync._is_manual_payload("not-a-dict") is False
|
assert _workout_sync._is_manual_payload("not-a-dict") is False
|
||||||
|
|
||||||
|
|
||||||
class TestSessionRecords:
|
class TestSessionRecords:
|
||||||
"""SessionRecords."""
|
|
||||||
|
|
||||||
def test_returns_only_session_records(self) -> None:
|
def test_returns_only_session_records(self) -> None:
|
||||||
"""Returns only session records."""
|
|
||||||
log = {
|
log = {
|
||||||
"s": _session_record_dict("session:1", _session_payload()),
|
"s": _session_record_dict("session:1", _session_payload()),
|
||||||
"m": _manual_record_dict("manual:1", _manual_payload()),
|
"m": _manual_record_dict("manual:1", _manual_payload()),
|
||||||
@ -105,7 +90,6 @@ class TestSessionRecords:
|
|||||||
assert list(result) == ["session:1"]
|
assert list(result) == ["session:1"]
|
||||||
|
|
||||||
def test_skips_records_without_a_payload_field(self) -> None:
|
def test_skips_records_without_a_payload_field(self) -> None:
|
||||||
"""Skips records without a payload field."""
|
|
||||||
no_payload = Record(
|
no_payload = Record(
|
||||||
id="a",
|
id="a",
|
||||||
fields={"other": (1, Hlc(wall_time_ms=1, counter=0, node_id="phone"))},
|
fields={"other": (1, Hlc(wall_time_ms=1, counter=0, node_id="phone"))},
|
||||||
@ -114,27 +98,21 @@ class TestSessionRecords:
|
|||||||
assert _workout_sync._session_records(json.dumps(log)) == {}
|
assert _workout_sync._session_records(json.dumps(log)) == {}
|
||||||
|
|
||||||
def test_raises_type_error_when_top_level_is_not_an_object(self) -> None:
|
def test_raises_type_error_when_top_level_is_not_an_object(self) -> None:
|
||||||
"""Raises type error when top level is not an object."""
|
|
||||||
with pytest.raises(TypeError, match="not a JSON object"):
|
with pytest.raises(TypeError, match="not a JSON object"):
|
||||||
_workout_sync._session_records(json.dumps([1, 2, 3]))
|
_workout_sync._session_records(json.dumps([1, 2, 3]))
|
||||||
|
|
||||||
def test_raises_value_error_for_invalid_json(self) -> None:
|
def test_raises_value_error_for_invalid_json(self) -> None:
|
||||||
"""Raises value error for invalid JSON."""
|
|
||||||
with pytest.raises(ValueError, match="Expecting property name"):
|
with pytest.raises(ValueError, match="Expecting property name"):
|
||||||
_workout_sync._session_records("{not valid json")
|
_workout_sync._session_records("{not valid json")
|
||||||
|
|
||||||
def test_raises_key_error_for_a_malformed_record(self) -> None:
|
def test_raises_key_error_for_a_malformed_record(self) -> None:
|
||||||
"""Raises key error for a malformed record."""
|
|
||||||
log = {"a": {"id": "a"}} # missing "fields"
|
log = {"a": {"id": "a"}} # missing "fields"
|
||||||
with pytest.raises(KeyError):
|
with pytest.raises(KeyError):
|
||||||
_workout_sync._session_records(json.dumps(log))
|
_workout_sync._session_records(json.dumps(log))
|
||||||
|
|
||||||
|
|
||||||
class TestManualRecords:
|
class TestManualRecords:
|
||||||
"""ManualRecords."""
|
|
||||||
|
|
||||||
def test_returns_only_manual_records(self) -> None:
|
def test_returns_only_manual_records(self) -> None:
|
||||||
"""Returns only manual records."""
|
|
||||||
log = {
|
log = {
|
||||||
"s": _record_json(_session_payload()),
|
"s": _record_json(_session_payload()),
|
||||||
"m": _manual_record_dict("manual:1", _manual_payload()),
|
"m": _manual_record_dict("manual:1", _manual_payload()),
|
||||||
@ -143,7 +121,6 @@ class TestManualRecords:
|
|||||||
assert list(result) == ["manual:1"]
|
assert list(result) == ["manual:1"]
|
||||||
|
|
||||||
def test_skips_records_without_a_payload_field(self) -> None:
|
def test_skips_records_without_a_payload_field(self) -> None:
|
||||||
"""Skips records without a payload field."""
|
|
||||||
no_payload = Record(
|
no_payload = Record(
|
||||||
id="a",
|
id="a",
|
||||||
fields={"other": (1, Hlc(wall_time_ms=1, counter=0, node_id="phone"))},
|
fields={"other": (1, Hlc(wall_time_ms=1, counter=0, node_id="phone"))},
|
||||||
@ -152,6 +129,150 @@ class TestManualRecords:
|
|||||||
assert _workout_sync._manual_records(json.dumps(log)) == {}
|
assert _workout_sync._manual_records(json.dumps(log)) == {}
|
||||||
|
|
||||||
def test_raises_type_error_when_top_level_is_not_an_object(self) -> None:
|
def test_raises_type_error_when_top_level_is_not_an_object(self) -> None:
|
||||||
"""Raises type error when top level is not an object."""
|
|
||||||
with pytest.raises(TypeError, match="not a JSON object"):
|
with pytest.raises(TypeError, match="not a JSON object"):
|
||||||
_workout_sync._manual_records(json.dumps([1, 2, 3]))
|
_workout_sync._manual_records(json.dumps([1, 2, 3]))
|
||||||
|
|
||||||
|
|
||||||
|
class TestMergeDeviceRecords:
|
||||||
|
"""The walk over EVERY ``devices/<id>/log.json``, not one hardcoded path."""
|
||||||
|
|
||||||
|
def test_merges_records_across_every_device(self) -> None:
|
||||||
|
client = _multi_device_client(
|
||||||
|
{
|
||||||
|
"phone": json.dumps(
|
||||||
|
{"a": _session_record_dict("session:a", _session_payload())}
|
||||||
|
),
|
||||||
|
"pc": json.dumps(
|
||||||
|
{"b": _session_record_dict("session:b", _session_payload())}
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
merged = _workout_sync._merge_device_records(
|
||||||
|
client, _workout_sync._session_records, "sessions"
|
||||||
|
)
|
||||||
|
assert sorted(merged) == ["session:a", "session:b"]
|
||||||
|
|
||||||
|
def test_dedups_the_same_id_keeping_the_highest_clock(self) -> None:
|
||||||
|
client = _multi_device_client(
|
||||||
|
{
|
||||||
|
"phone": json.dumps(
|
||||||
|
{
|
||||||
|
"a": _session_record_dict(
|
||||||
|
"session:a",
|
||||||
|
_session_payload(note="OLD"),
|
||||||
|
wall_time_ms=100,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
),
|
||||||
|
"pc": json.dumps(
|
||||||
|
{
|
||||||
|
"a": _session_record_dict(
|
||||||
|
"session:a",
|
||||||
|
_session_payload(note="NEW"),
|
||||||
|
wall_time_ms=200,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
merged = _workout_sync._merge_device_records(
|
||||||
|
client, _workout_sync._session_records, "sessions"
|
||||||
|
)
|
||||||
|
assert len(merged) == 1
|
||||||
|
assert merged["session:a"][0]["note"] == "NEW"
|
||||||
|
|
||||||
|
def test_ignores_a_lower_clock_duplicate_seen_later(self) -> None:
|
||||||
|
client = _multi_device_client(
|
||||||
|
{
|
||||||
|
"phone": json.dumps(
|
||||||
|
{
|
||||||
|
"a": _session_record_dict(
|
||||||
|
"session:a",
|
||||||
|
_session_payload(note="NEW"),
|
||||||
|
wall_time_ms=200,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
),
|
||||||
|
"pc": json.dumps(
|
||||||
|
{
|
||||||
|
"a": _session_record_dict(
|
||||||
|
"session:a",
|
||||||
|
_session_payload(note="OLD"),
|
||||||
|
wall_time_ms=100,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
merged = _workout_sync._merge_device_records(
|
||||||
|
client, _workout_sync._session_records, "sessions"
|
||||||
|
)
|
||||||
|
assert merged["session:a"][0]["note"] == "NEW"
|
||||||
|
|
||||||
|
def test_skips_a_corrupt_device_log(self) -> None:
|
||||||
|
client = _multi_device_client(
|
||||||
|
{
|
||||||
|
"good": json.dumps(
|
||||||
|
{"a": _session_record_dict("session:a", _session_payload())}
|
||||||
|
),
|
||||||
|
"corrupt": "{not json",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
merged = _workout_sync._merge_device_records(
|
||||||
|
client, _workout_sync._session_records, "sessions"
|
||||||
|
)
|
||||||
|
assert list(merged) == ["session:a"]
|
||||||
|
|
||||||
|
def test_skips_an_unreachable_device(self) -> None:
|
||||||
|
client = _multi_device_client(
|
||||||
|
{
|
||||||
|
"good": json.dumps(
|
||||||
|
{"a": _session_record_dict("session:a", _session_payload())}
|
||||||
|
),
|
||||||
|
"gone": GitHubSyncError("404"),
|
||||||
|
"empty": None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
merged = _workout_sync._merge_device_records(
|
||||||
|
client, _workout_sync._session_records, "sessions"
|
||||||
|
)
|
||||||
|
assert list(merged) == ["session:a"]
|
||||||
|
|
||||||
|
def test_returns_empty_on_a_listing_failure_when_not_strict(self) -> None:
|
||||||
|
client = MagicMock()
|
||||||
|
client.list_directory.side_effect = GitHubSyncError("offline")
|
||||||
|
merged = _workout_sync._merge_device_records(
|
||||||
|
client, _workout_sync._session_records, "sessions"
|
||||||
|
)
|
||||||
|
assert merged == {}
|
||||||
|
|
||||||
|
def test_reraises_on_a_listing_failure_when_strict(self) -> None:
|
||||||
|
"""Callers separating "nothing to sync" from "sync broke" need the raise."""
|
||||||
|
client = MagicMock()
|
||||||
|
client.list_directory.side_effect = GitHubSyncError("offline")
|
||||||
|
with pytest.raises(GitHubSyncError, match="offline"):
|
||||||
|
_workout_sync._merge_device_records(
|
||||||
|
client, _workout_sync._session_records, "sessions", strict=True
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_warns_about_a_listing_failure(
|
||||||
|
self, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
"""A total pull failure must never be silent."""
|
||||||
|
client = MagicMock()
|
||||||
|
client.list_directory.side_effect = GitHubSyncError("offline")
|
||||||
|
with caplog.at_level("WARNING"):
|
||||||
|
_workout_sync._merge_device_records(
|
||||||
|
client, _workout_sync._session_records, "sessions"
|
||||||
|
)
|
||||||
|
assert "offline" in caplog.text
|
||||||
|
|
||||||
|
def test_warns_about_a_skipped_device(
|
||||||
|
self, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
client = _multi_device_client({"gone": GitHubSyncError("404")})
|
||||||
|
with caplog.at_level("WARNING"):
|
||||||
|
_workout_sync._merge_device_records(
|
||||||
|
client, _workout_sync._session_records, "sessions"
|
||||||
|
)
|
||||||
|
assert "SKIPPING that device" in caplog.text
|
||||||
|
|||||||
@ -1,173 +0,0 @@
|
|||||||
"""Tests for the phone-workout sync pull (crdt-sync transport).
|
|
||||||
|
|
||||||
Covers the token read, the payload predicates, the per-log record extractors
|
|
||||||
and the cross-device merge. The backend selection (``sync_client`` /
|
|
||||||
``remote_client``) and the two public pulls live in ``_part2``.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
from unittest.mock import MagicMock
|
|
||||||
|
|
||||||
from crdt_sync import GitHubSyncError
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from screen_locker import _workout_sync
|
|
||||||
from screen_locker.tests._workout_sync_fixtures import (
|
|
||||||
_multi_device_client,
|
|
||||||
_session_payload,
|
|
||||||
_session_record_dict,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestMergeDeviceRecords:
|
|
||||||
"""The walk over EVERY ``devices/<id>/log.json``, not one hardcoded path."""
|
|
||||||
|
|
||||||
def test_merges_records_across_every_device(self) -> None:
|
|
||||||
"""Merges records across every device."""
|
|
||||||
client = _multi_device_client(
|
|
||||||
{
|
|
||||||
"phone": json.dumps(
|
|
||||||
{"a": _session_record_dict("session:a", _session_payload())}
|
|
||||||
),
|
|
||||||
"pc": json.dumps(
|
|
||||||
{"b": _session_record_dict("session:b", _session_payload())}
|
|
||||||
),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
merged = _workout_sync._merge_device_records(
|
|
||||||
client, _workout_sync._session_records, "sessions"
|
|
||||||
)
|
|
||||||
assert sorted(merged) == ["session:a", "session:b"]
|
|
||||||
|
|
||||||
def test_dedups_the_same_id_keeping_the_highest_clock(self) -> None:
|
|
||||||
"""Dedups the same ID keeping the highest clock."""
|
|
||||||
client = _multi_device_client(
|
|
||||||
{
|
|
||||||
"phone": json.dumps(
|
|
||||||
{
|
|
||||||
"a": _session_record_dict(
|
|
||||||
"session:a",
|
|
||||||
_session_payload(note="OLD"),
|
|
||||||
wall_time_ms=100,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
),
|
|
||||||
"pc": json.dumps(
|
|
||||||
{
|
|
||||||
"a": _session_record_dict(
|
|
||||||
"session:a",
|
|
||||||
_session_payload(note="NEW"),
|
|
||||||
wall_time_ms=200,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
merged = _workout_sync._merge_device_records(
|
|
||||||
client, _workout_sync._session_records, "sessions"
|
|
||||||
)
|
|
||||||
assert len(merged) == 1
|
|
||||||
assert merged["session:a"][0]["note"] == "NEW"
|
|
||||||
|
|
||||||
def test_ignores_a_lower_clock_duplicate_seen_later(self) -> None:
|
|
||||||
"""Ignores a lower clock duplicate seen later."""
|
|
||||||
client = _multi_device_client(
|
|
||||||
{
|
|
||||||
"phone": json.dumps(
|
|
||||||
{
|
|
||||||
"a": _session_record_dict(
|
|
||||||
"session:a",
|
|
||||||
_session_payload(note="NEW"),
|
|
||||||
wall_time_ms=200,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
),
|
|
||||||
"pc": json.dumps(
|
|
||||||
{
|
|
||||||
"a": _session_record_dict(
|
|
||||||
"session:a",
|
|
||||||
_session_payload(note="OLD"),
|
|
||||||
wall_time_ms=100,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
merged = _workout_sync._merge_device_records(
|
|
||||||
client, _workout_sync._session_records, "sessions"
|
|
||||||
)
|
|
||||||
assert merged["session:a"][0]["note"] == "NEW"
|
|
||||||
|
|
||||||
def test_skips_a_corrupt_device_log(self) -> None:
|
|
||||||
"""Skips a corrupt device log."""
|
|
||||||
client = _multi_device_client(
|
|
||||||
{
|
|
||||||
"good": json.dumps(
|
|
||||||
{"a": _session_record_dict("session:a", _session_payload())}
|
|
||||||
),
|
|
||||||
"corrupt": "{not json",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
merged = _workout_sync._merge_device_records(
|
|
||||||
client, _workout_sync._session_records, "sessions"
|
|
||||||
)
|
|
||||||
assert list(merged) == ["session:a"]
|
|
||||||
|
|
||||||
def test_skips_an_unreachable_device(self) -> None:
|
|
||||||
"""Skips an unreachable device."""
|
|
||||||
client = _multi_device_client(
|
|
||||||
{
|
|
||||||
"good": json.dumps(
|
|
||||||
{"a": _session_record_dict("session:a", _session_payload())}
|
|
||||||
),
|
|
||||||
"gone": GitHubSyncError("404"),
|
|
||||||
"empty": None,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
merged = _workout_sync._merge_device_records(
|
|
||||||
client, _workout_sync._session_records, "sessions"
|
|
||||||
)
|
|
||||||
assert list(merged) == ["session:a"]
|
|
||||||
|
|
||||||
def test_returns_empty_on_a_listing_failure_when_not_strict(self) -> None:
|
|
||||||
"""Returns empty on a listing failure when not strict."""
|
|
||||||
client = MagicMock()
|
|
||||||
client.list_directory.side_effect = GitHubSyncError("offline")
|
|
||||||
merged = _workout_sync._merge_device_records(
|
|
||||||
client, _workout_sync._session_records, "sessions"
|
|
||||||
)
|
|
||||||
assert merged == {}
|
|
||||||
|
|
||||||
def test_reraises_on_a_listing_failure_when_strict(self) -> None:
|
|
||||||
"""Callers separating "nothing to sync" from "sync broke" need the raise."""
|
|
||||||
client = MagicMock()
|
|
||||||
client.list_directory.side_effect = GitHubSyncError("offline")
|
|
||||||
with pytest.raises(GitHubSyncError, match="offline"):
|
|
||||||
_workout_sync._merge_device_records(
|
|
||||||
client, _workout_sync._session_records, "sessions", strict=True
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_warns_about_a_listing_failure(
|
|
||||||
self, caplog: pytest.LogCaptureFixture
|
|
||||||
) -> None:
|
|
||||||
"""A total pull failure must never be silent."""
|
|
||||||
client = MagicMock()
|
|
||||||
client.list_directory.side_effect = GitHubSyncError("offline")
|
|
||||||
with caplog.at_level("WARNING"):
|
|
||||||
_workout_sync._merge_device_records(
|
|
||||||
client, _workout_sync._session_records, "sessions"
|
|
||||||
)
|
|
||||||
assert "offline" in caplog.text
|
|
||||||
|
|
||||||
def test_warns_about_a_skipped_device(
|
|
||||||
self, caplog: pytest.LogCaptureFixture
|
|
||||||
) -> None:
|
|
||||||
"""Warns about a skipped device."""
|
|
||||||
client = _multi_device_client({"gone": GitHubSyncError("404")})
|
|
||||||
with caplog.at_level("WARNING"):
|
|
||||||
_workout_sync._merge_device_records(
|
|
||||||
client, _workout_sync._session_records, "sessions"
|
|
||||||
)
|
|
||||||
assert "SKIPPING that device" in caplog.text
|
|
||||||
@ -1,229 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""Regenerate the violations table in ``refactor_claude_todo.md``.
|
|
||||||
|
|
||||||
The todo file doubles as the prompt for the next refactor session, so its
|
|
||||||
counts must never go stale: a hand-written hand-off summary drifts the moment
|
|
||||||
one more file is split. This script derives everything from the gate's own
|
|
||||||
output plus ``git log`` churn, so the resume state is simply "run this, then
|
|
||||||
take the top N".
|
|
||||||
|
|
||||||
ROI = lines x commits in the last year. A long file nobody edits has near-zero
|
|
||||||
payoff and should not be first.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
python3 scripts/refresh_refactor_todo.py [--check]
|
|
||||||
|
|
||||||
``--check`` exits 1 if the file is out of date instead of rewriting it, so CI
|
|
||||||
or a hook can fail on a stale table.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import logging
|
|
||||||
from pathlib import Path
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
|
||||||
TODO_FILE = REPO_ROOT / "refactor_claude_todo.md"
|
|
||||||
GATE = REPO_ROOT / "scripts" / "check_file_length.sh"
|
|
||||||
FALLBACK_GATE = Path.home() / "utils" / "scripts" / "check_file_length.sh"
|
|
||||||
|
|
||||||
BEGIN_MARKER = "<!-- BEGIN GENERATED VIOLATIONS -->"
|
|
||||||
END_MARKER = "<!-- END GENERATED VIOLATIONS -->"
|
|
||||||
TOP_N = 15
|
|
||||||
|
|
||||||
_VIOLATION_RE = re.compile(
|
|
||||||
r"^\s*(?P<path>.+?):\s*(?P<lines>\d+) lines \(over by \d+\)$"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _executable(name: str) -> str:
|
|
||||||
"""Absolute path to `name`, so the subprocess call is not PATH-dependent."""
|
|
||||||
found = shutil.which(name)
|
|
||||||
if found is None:
|
|
||||||
msg = f"required executable not found on PATH: {name}"
|
|
||||||
raise FileNotFoundError(msg)
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def gate_script() -> Path:
|
|
||||||
"""The file-length gate to run, preferring the in-repo vendored copy."""
|
|
||||||
return GATE if GATE.is_file() else FALLBACK_GATE
|
|
||||||
|
|
||||||
|
|
||||||
def collect_violations() -> list[tuple[Path, int]]:
|
|
||||||
"""Every file over the cap, as (repo-relative path, line count)."""
|
|
||||||
script = gate_script()
|
|
||||||
if not script.is_file():
|
|
||||||
msg = f"file-length gate not found at {script}"
|
|
||||||
raise FileNotFoundError(msg)
|
|
||||||
result = subprocess.run(
|
|
||||||
[_executable("bash"), str(script), "--all"],
|
|
||||||
cwd=REPO_ROOT,
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
check=False,
|
|
||||||
)
|
|
||||||
# Exit 0 means no violations; 1 means violations were listed on stderr.
|
|
||||||
# Anything else is a real failure and must not be reported as "all clean".
|
|
||||||
if result.returncode not in (0, 1):
|
|
||||||
msg = (
|
|
||||||
f"file-length gate failed with exit {result.returncode}: "
|
|
||||||
f"{result.stderr.strip() or result.stdout.strip()}"
|
|
||||||
)
|
|
||||||
raise RuntimeError(msg)
|
|
||||||
|
|
||||||
violations: list[tuple[Path, int]] = []
|
|
||||||
for line in (result.stderr + result.stdout).splitlines():
|
|
||||||
match = _VIOLATION_RE.match(line)
|
|
||||||
if match is None:
|
|
||||||
continue
|
|
||||||
path = Path(match.group("path"))
|
|
||||||
try:
|
|
||||||
relative = path.relative_to(REPO_ROOT)
|
|
||||||
except ValueError:
|
|
||||||
# The gate reported a file outside the repo root. Keep it in the
|
|
||||||
# table (it is still a violation) but say so, because an absolute
|
|
||||||
# path in the output means the gate was run from the wrong cwd.
|
|
||||||
_logger.warning(
|
|
||||||
"gate reported %s outside the repo root %s — listing it with "
|
|
||||||
"its absolute path; check the cwd the gate ran in",
|
|
||||||
path,
|
|
||||||
REPO_ROOT,
|
|
||||||
)
|
|
||||||
relative = path
|
|
||||||
violations.append((relative, int(match.group("lines"))))
|
|
||||||
return violations
|
|
||||||
|
|
||||||
|
|
||||||
def commits_last_year(path: Path) -> int:
|
|
||||||
"""How many commits touched `path` in the last year (0 if untracked)."""
|
|
||||||
result = subprocess.run(
|
|
||||||
[_executable("git"), "log", "--since=1 year ago", "--oneline", "--", str(path)],
|
|
||||||
cwd=REPO_ROOT,
|
|
||||||
capture_output=True,
|
|
||||||
text=True,
|
|
||||||
check=False,
|
|
||||||
)
|
|
||||||
if result.returncode != 0:
|
|
||||||
_logger.warning(
|
|
||||||
"git log failed for %s (%s) — counting 0 commits, so its ROI "
|
|
||||||
"rank will read lower than it should",
|
|
||||||
path,
|
|
||||||
result.stderr.strip(),
|
|
||||||
)
|
|
||||||
return 0
|
|
||||||
return len(result.stdout.splitlines())
|
|
||||||
|
|
||||||
|
|
||||||
def kind_of(path: Path) -> str:
|
|
||||||
"""Coarse bucket used in the table's ``kind`` column."""
|
|
||||||
if path.suffix in {".md", ".txt", ".rst", ".tex"}:
|
|
||||||
return "prose"
|
|
||||||
return "code"
|
|
||||||
|
|
||||||
|
|
||||||
def render_table(rows: list[tuple[int, int, int, Path]]) -> str:
|
|
||||||
"""The markdown section between the generated-content markers."""
|
|
||||||
total_files = len(rows)
|
|
||||||
total_over = sum(lines - 250 for _, lines, _, _ in rows)
|
|
||||||
longest = max((lines for _, lines, _, _ in rows), default=0)
|
|
||||||
|
|
||||||
out = [BEGIN_MARKER, ""]
|
|
||||||
if not rows:
|
|
||||||
out += [
|
|
||||||
"**No violations.** Every file is at or under the 250-line cap.",
|
|
||||||
"",
|
|
||||||
END_MARKER,
|
|
||||||
]
|
|
||||||
return "\n".join(out)
|
|
||||||
|
|
||||||
out += [
|
|
||||||
f"- **{total_files} files** currently exceed 250 lines.",
|
|
||||||
f"- **{total_over:,} lines** over the cap in total (the work left to "
|
|
||||||
f"do); longest file is **{longest}** 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.",
|
|
||||||
"",
|
|
||||||
"| lines | commits/yr | kind | file |",
|
|
||||||
"| ----: | ---------: | :--- | :--- |",
|
|
||||||
]
|
|
||||||
for _, lines, commits, path in rows[:TOP_N]:
|
|
||||||
out.append(f"| {lines} | {commits} | {kind_of(path)} | `{path}` |")
|
|
||||||
|
|
||||||
remaining = total_files - min(TOP_N, total_files)
|
|
||||||
if remaining > 0:
|
|
||||||
out += [
|
|
||||||
"",
|
|
||||||
f"_({remaining} further files over 250 lines not listed — "
|
|
||||||
"re-run `python3 scripts/refresh_refactor_todo.py` for the "
|
|
||||||
"current set.)_",
|
|
||||||
]
|
|
||||||
out += ["", END_MARKER]
|
|
||||||
return "\n".join(out)
|
|
||||||
|
|
||||||
|
|
||||||
def build_section() -> str:
|
|
||||||
"""Compute ROI for every violation and render the table."""
|
|
||||||
rows = []
|
|
||||||
for path, lines in collect_violations():
|
|
||||||
# One git log per file, not two: this runs over ~70 files.
|
|
||||||
commits = commits_last_year(path)
|
|
||||||
rows.append((lines * commits, lines, commits, path))
|
|
||||||
rows.sort(key=lambda row: (-row[0], -row[1]))
|
|
||||||
return render_table(rows)
|
|
||||||
|
|
||||||
|
|
||||||
def splice(original: str, section: str) -> str:
|
|
||||||
"""Replace the marked region of `original` with `section`."""
|
|
||||||
start = original.find(BEGIN_MARKER)
|
|
||||||
end = original.find(END_MARKER)
|
|
||||||
if start == -1 or end == -1:
|
|
||||||
msg = (
|
|
||||||
f"{TODO_FILE.name} is missing the generated-content markers "
|
|
||||||
f"({BEGIN_MARKER} / {END_MARKER})"
|
|
||||||
)
|
|
||||||
raise ValueError(msg)
|
|
||||||
return original[:start] + section + original[end + len(END_MARKER) :]
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
"""Rewrite (or check) the todo file's violations table."""
|
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
|
||||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
|
|
||||||
parser.add_argument(
|
|
||||||
"--check",
|
|
||||||
action="store_true",
|
|
||||||
help="exit 1 if the table is out of date instead of rewriting it",
|
|
||||||
)
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
original = TODO_FILE.read_text()
|
|
||||||
updated = splice(original, build_section())
|
|
||||||
|
|
||||||
if args.check:
|
|
||||||
if updated != original:
|
|
||||||
_logger.error(
|
|
||||||
"%s is out of date — run `python3 scripts/refresh_refactor_todo.py`",
|
|
||||||
TODO_FILE.name,
|
|
||||||
)
|
|
||||||
return 1
|
|
||||||
return 0
|
|
||||||
|
|
||||||
if updated != original:
|
|
||||||
TODO_FILE.write_text(updated)
|
|
||||||
_logger.info("Updated %s", TODO_FILE.name)
|
|
||||||
else:
|
|
||||||
_logger.info("%s already up to date", TODO_FILE.name)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
raise SystemExit(main())
|
|
||||||
@ -1,141 +0,0 @@
|
|||||||
# Fix TODO — make pylint a perfect 10.00 gate
|
|
||||||
|
|
||||||
> **This file is a ready-to-use prompt.** Paste it to Claude, or open this repo
|
|
||||||
> and say "do todo_fix_pylint_10_prompt". It is self-contained: everything
|
|
||||||
> needed to execute is below. Generated 2026-08-15 from a measured run.
|
|
||||||
|
|
||||||
## Goal
|
|
||||||
|
|
||||||
`pylint` must score **10.00/10** on this repo, enforced by the pre-commit hook
|
|
||||||
at `--fail-under=10` — not the current `--fail-under=8.0`, which lets real
|
|
||||||
findings through as long as enough clean files dilute them.
|
|
||||||
|
|
||||||
Why the current bar is wrong: pylint's hook scores the **staged batch** as one
|
|
||||||
number. A commit touching many test files fails while the identical code
|
|
||||||
committed alongside a few clean source files passes. The score is a property of
|
|
||||||
*which files you staged*, not of the code. A 10.00 bar removes that entirely —
|
|
||||||
zero findings is zero findings regardless of batching.
|
|
||||||
|
|
||||||
## Measured starting point (2026-08-15)
|
|
||||||
|
|
||||||
Whole repo (`screen_locker/` + `scripts/`): **8.76/10**.
|
|
||||||
|
|
||||||
Findings by category, highest first:
|
|
||||||
|
|
||||||
| count | check | fixable? |
|
|
||||||
| ----: | :--- | :--- |
|
|
||||||
| 473 | `protected-access` (W0212) | no — test-inherent |
|
|
||||||
| 369 | `unused-argument` (W0613) | no — test-inherent |
|
|
||||||
| 245 | `missing-function-docstring` (C0116) | **yes** |
|
|
||||||
| 238 | `suppressed-message` (I0020) | disappears with W0212/W0613 |
|
|
||||||
| 73 | `duplicate-code` (R0801) | no — test-inherent |
|
|
||||||
| 66 | `use-implicit-booleaness-not-comparison-to-zero` (C1805) | **yes** |
|
|
||||||
| 27 | `import-outside-toplevel` (C0415) | **yes**, mostly |
|
|
||||||
| 25 | `missing-class-docstring` (C0115) | **yes** |
|
|
||||||
| 25 | `locally-disabled` (I0011) | disappears with W0212/W0613 |
|
|
||||||
| 24 | `use-implicit-booleaness-not-comparison` (C1803) | **yes** |
|
|
||||||
| 10 | `useless-suppression` (I0021) | **yes** — delete the dead disables |
|
|
||||||
| ~40 | long tail (see "Long tail" below) | **yes** |
|
|
||||||
|
|
||||||
## The decision already taken
|
|
||||||
|
|
||||||
Three checks are **disabled for test paths only**, because they are not defects
|
|
||||||
— they are how pytest works, and fixing them would mean rewriting ~840 call
|
|
||||||
sites and making production APIs public to suit tests:
|
|
||||||
|
|
||||||
- **`protected-access` (W0212)** — tests drive private mixin methods directly
|
|
||||||
(`locker._verify_phone_workout()`). This is deliberate: those methods *are*
|
|
||||||
the unit under test. Ruff already exempts the same thing in tests via
|
|
||||||
`SLF001` in `pyproject.toml`'s per-file-ignores, so pylint disagreeing with
|
|
||||||
ruff is just noise.
|
|
||||||
- **`unused-argument` (W0613)** — pytest fixtures such as `mock_tk` and
|
|
||||||
`mock_sys_exit` must be *requested* in the signature to take effect, but are
|
|
||||||
never referenced in the body. Consuming them with a dummy `assert` to satisfy
|
|
||||||
a linter is strictly worse code.
|
|
||||||
- **`duplicate-code` (R0801)** — near-identical `with patch(...)` preambles
|
|
||||||
across sibling test modules. Deduplicating them into helpers hurts: a test
|
|
||||||
should read top-to-bottom without chasing a shared fixture.
|
|
||||||
|
|
||||||
Everything else gets **fixed for real**. No `# pylint: disable=` lines, no
|
|
||||||
per-line suppressions — this repo bans `# noqa` / `# type: ignore` repo-wide and
|
|
||||||
the same spirit applies here.
|
|
||||||
|
|
||||||
## Steps
|
|
||||||
|
|
||||||
1. **Scope the three disables to tests only.** They must NOT apply to
|
|
||||||
`screen_locker/*.py` or `scripts/*.py`. pylint has no per-path `disable` in
|
|
||||||
`pyproject.toml`, so use one of:
|
|
||||||
- a `screen_locker/tests/.pylintrc` that inherits and adds the disables
|
|
||||||
(pylint picks the nearest rcfile per directory), or
|
|
||||||
- two pre-commit hooks (`pylint-src` with `exclude: ^screen_locker/tests/`,
|
|
||||||
`pylint-tests` with `files: ^screen_locker/tests/`), each `--fail-under=10`.
|
|
||||||
|
|
||||||
Verify the scoping works: introduce a deliberate `protected-access` in a
|
|
||||||
*source* file and confirm it still fails.
|
|
||||||
|
|
||||||
2. **Fix `missing-function-docstring` / `missing-class-docstring` (270).**
|
|
||||||
Docstrings must say what the test *pins down*, not restate its name.
|
|
||||||
Good: `"""An unsigned entry is rejected once a key is available."""`
|
|
||||||
Bad: `"""Test rejected when key available."""`
|
|
||||||
A generator that drafts from the test name lives at
|
|
||||||
`/tmp/.../scratchpad/add_docstrings.py` in the session that wrote this file;
|
|
||||||
it is refactor tooling, not a deliverable — rewrite it if it is gone. Every
|
|
||||||
generated line still needs reading: the draft is a starting point.
|
|
||||||
|
|
||||||
3. **Fix the booleanness checks (94).** `assert x == []` → `assert not x`,
|
|
||||||
`assert n == 0` → `assert not n`, `assert s == ""` → `assert not s`.
|
|
||||||
Careful: only where the value really is a sequence/int/str. `is False` /
|
|
||||||
`is True` assertions on tri-state returns must NOT be collapsed.
|
|
||||||
|
|
||||||
4. **Fix `import-outside-toplevel` (27).** Hoist each to module scope unless it
|
|
||||||
exists to break an import cycle — where it does, that is a real constraint;
|
|
||||||
restructure the modules so the cycle is gone, or leave it and note why.
|
|
||||||
|
|
||||||
5. **Delete `useless-suppression` (10)** — dead `# pylint: disable=` comments
|
|
||||||
that no longer suppress anything.
|
|
||||||
|
|
||||||
6. **Long tail (~40).** `too-many-instance-attributes`, `too-many-arguments`,
|
|
||||||
`too-many-return-statements`, `unspecified-encoding`, `line-too-long`,
|
|
||||||
`comparison-with-callable`, `superfluous-parens`,
|
|
||||||
`pointless-string-statement`, `reimported`, `consider-using-with`,
|
|
||||||
`unreachable`. Fix each on its merits.
|
|
||||||
- `unspecified-encoding` (3) is a genuine latent bug — add `encoding="utf-8"`.
|
|
||||||
- `comparison-with-callable` (3) is often a real bug (comparing a function
|
|
||||||
instead of calling it). Read each one carefully.
|
|
||||||
- `unreachable` (4) is `sys.exit(0)` followed by `return` in
|
|
||||||
`_startup_checks.py` and elsewhere. Those `return`s are **load-bearing
|
|
||||||
under test**: `conftest.py` patches `sys.exit` to a no-op, so without the
|
|
||||||
`return` execution continues into the next branch. Do not delete them
|
|
||||||
blindly — restructure so the intent is expressed without dead code, or
|
|
||||||
leave them and record the reason.
|
|
||||||
- `too-many-ancestors` (1) is `ScreenLocker`'s 19 mixins. Inherent to the
|
|
||||||
design; raise `max-parents` in config rather than collapsing mixins.
|
|
||||||
|
|
||||||
7. **Flip the gate.** Set `--fail-under=10` in `.pre-commit-config.yaml` (both
|
|
||||||
hooks if you split them) and update the hook `name:` to say 10.
|
|
||||||
|
|
||||||
## Done condition
|
|
||||||
|
|
||||||
- `pylint --rcfile=pyproject.toml screen_locker/ scripts/` prints
|
|
||||||
**`rated at 10.00/10`**.
|
|
||||||
- `pre-commit run --all-files` passes.
|
|
||||||
- A deliberately-introduced pylint finding in a **source** file makes
|
|
||||||
`git commit` fail (proves the gate is live and correctly scoped).
|
|
||||||
- `python -m pytest` still green at `fail_under = 100` branch coverage.
|
|
||||||
- No `# pylint: disable=` added anywhere as part of this work.
|
|
||||||
|
|
||||||
## Verify
|
|
||||||
|
|
||||||
Run the suite, then actually run the locker entry point —
|
|
||||||
`python -m screen_locker.screen_lock --status` — because this repo deploys from
|
|
||||||
the working tree, so a broken import is a live outage. Hoisting imports (step 4)
|
|
||||||
is exactly the change that can cause one.
|
|
||||||
|
|
||||||
## Do not
|
|
||||||
|
|
||||||
- Do not lower `--fail-under` below 10 once it is raised.
|
|
||||||
- Do not add per-line `# pylint: disable=` comments to reach the number.
|
|
||||||
- Do not disable W0212/W0613/R0801 globally — tests only. A source file calling
|
|
||||||
another class's private attribute is a real finding.
|
|
||||||
- Do not touch `refactor_claude_todo.md`'s 250-line work; that is a separate,
|
|
||||||
in-progress task with its own prompt file.
|
|
||||||
Loading…
Reference in New Issue
Block a user