mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-24 12:46:28 +01:00
Compare commits
3 Commits
c1c73d43ba
...
390e916922
| Author | SHA1 | Date | |
|---|---|---|---|
| 390e916922 | |||
| 957e4566c2 | |||
| 6a7a7d8933 |
@ -116,7 +116,7 @@ repos:
|
||||
- --jobs=4
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.6.0#subdirectory=crdt-sync
|
||||
- mcp>=2,<3
|
||||
- pydantic
|
||||
@ -131,7 +131,7 @@ repos:
|
||||
- --disable=protected-access,unused-argument,duplicate-code
|
||||
additional_dependencies:
|
||||
- pytest
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock
|
||||
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock
|
||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.6.0#subdirectory=crdt-sync
|
||||
- mcp>=2,<3
|
||||
- pydantic
|
||||
|
||||
@ -7,7 +7,7 @@ requires-python = ">=3.10"
|
||||
# crdt-sync: shared CRDT merge scheme + GitHub-Contents-API sync transport,
|
||||
# also used by diet_guard; here for phone-workout GitHub sync (Workstream C)
|
||||
dependencies = [
|
||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock",
|
||||
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock",
|
||||
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.7.0#subdirectory=crdt-sync",
|
||||
]
|
||||
|
||||
|
||||
@ -4,7 +4,7 @@ bandit>=1.7.0
|
||||
codespell>=2.2.0
|
||||
coverage>=7.4.0
|
||||
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.7.0#subdirectory=crdt-sync
|
||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.4.0#subdirectory=gatelock
|
||||
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.7.1#subdirectory=gatelock
|
||||
mcp>=2,<3
|
||||
mypy>=1.8.0
|
||||
pre-commit>=3.6.0
|
||||
|
||||
@ -4,8 +4,14 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from gatelock import default_runtime_dir
|
||||
from gatelock.log_integrity import DEFAULT_HMAC_KEY_FILE
|
||||
|
||||
# Ephemeral runtime state (self-clears on reboot, same directory gatelock's
|
||||
# own Arbiter uses) -- not repo-tracked data, so it does not belong next to
|
||||
# log.json/sick_history.json below.
|
||||
INSTANCE_LOCK_FILE = default_runtime_dir() / "screen_locker-instance.lock"
|
||||
|
||||
# Single-sourced from gatelock so the literal key path can't drift.
|
||||
HMAC_KEY_FILE = DEFAULT_HMAC_KEY_FILE
|
||||
SICK_LOCKOUT_SECONDS = 120 # base 2 minutes wait when sick (escalates with usage)
|
||||
@ -87,8 +93,6 @@ MIN_RUN_DISTANCE_KM = 3.5 # inclusive: "as low as 3.5 km"
|
||||
# that one is a deliberate concession to the user, this one corrects a
|
||||
# measurement error. Duration now gets a leeway too, but for the other reason.
|
||||
RUNNERUP_DISTANCE_TOLERANCE = 0.05
|
||||
RUNNERUP_ACCEPTED_SPORTS: frozenset[int] = frozenset({0, 3, 5})
|
||||
# 0=RUNNING, 3=ORIENTEERING, 5=TREADMILL
|
||||
MAX_CLOCK_SKEW_SECONDS = 300 # 5 minutes max time skew from NTP
|
||||
EARLY_BIRD_START_HOUR = 5
|
||||
EARLY_BIRD_END_HOUR = 8
|
||||
|
||||
68
screen_locker/_instance.py
Normal file
68
screen_locker/_instance.py
Normal file
@ -0,0 +1,68 @@
|
||||
"""One workout-locker process at a time.
|
||||
|
||||
A stray re-arm (a delayed ``workout-locker.timer`` catch-up landing right on
|
||||
top of a session that just unlocked, a direct spawn outside the tracked
|
||||
systemd unit, or any other double-start) used to mean two Tk processes
|
||||
racing to build a lock window and grab the display. Copied in shape from
|
||||
``leetcode_guard._instance`` / ``diet_guard._gatelock.acquire_gate_lock``.
|
||||
|
||||
Liveness is the kernel's ``flock``, held for the process lifetime: it is
|
||||
released on *any* death, including SIGKILL and a crashed X server. No PID
|
||||
files, no staleness heuristics, no timeouts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import fcntl
|
||||
import logging
|
||||
import os
|
||||
from typing import IO, TYPE_CHECKING, Final
|
||||
|
||||
_logger: Final = logging.getLogger(__name__)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass
|
||||
class InstanceLock:
|
||||
"""A held single-instance lock."""
|
||||
|
||||
handle: IO[str]
|
||||
path: Path
|
||||
|
||||
def release(self) -> None:
|
||||
"""Drop the lock. Idempotent, and safe on a closed handle."""
|
||||
try:
|
||||
self.handle.close()
|
||||
except OSError as exc:
|
||||
_logger.warning("could not close the instance lock %s: %s", self.path, exc)
|
||||
|
||||
|
||||
def acquire(path: Path) -> InstanceLock | None:
|
||||
"""Take the single-instance lock, or ``None`` if another run holds it.
|
||||
|
||||
Opened ``"a+"`` rather than ``"w"``: ``"w"`` truncates at ``open()`` time,
|
||||
which happens *before* the lock attempt, so a losing contender would erase
|
||||
the incumbent's record on its way out.
|
||||
"""
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
handle = path.open("a+", encoding="utf-8")
|
||||
except OSError:
|
||||
_logger.exception("cannot open the instance lock %s", path)
|
||||
return None
|
||||
try:
|
||||
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError:
|
||||
_logger.warning(
|
||||
"another workout-locker run already holds %s -- standing down", path
|
||||
)
|
||||
handle.close()
|
||||
return None
|
||||
handle.seek(0)
|
||||
handle.truncate()
|
||||
handle.write(str(os.getpid()))
|
||||
handle.flush()
|
||||
return InstanceLock(handle=handle, path=path)
|
||||
@ -14,7 +14,6 @@ from typing import Any
|
||||
from screen_locker._constants import (
|
||||
MIN_RUN_DISTANCE_KM,
|
||||
MIN_WORKOUT_DURATION_MINUTES,
|
||||
RUNNERUP_ACCEPTED_SPORTS,
|
||||
RUNNERUP_DISTANCE_TOLERANCE,
|
||||
RUNNERUP_EXPORT_DIRS,
|
||||
WORKOUT_DURATION_ACCEPT_MINUTES,
|
||||
@ -78,7 +77,7 @@ class RunnerUpVerificationMixin(
|
||||
fails validation), or ``None`` if no today's file exists at all
|
||||
(caller should try the root DB path instead).
|
||||
"""
|
||||
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
today = datetime.now(tz=timezone.utc).astimezone().strftime("%Y-%m-%d")
|
||||
exports = self._find_runnerup_exports_for_date(today)
|
||||
if not exports:
|
||||
_logger.warning(
|
||||
@ -116,12 +115,6 @@ class RunnerUpVerificationMixin(
|
||||
``PhoneVerificationMixin._verify_phone_workout``.
|
||||
"""
|
||||
sport = data["sport"]
|
||||
if sport not in RUNNERUP_ACCEPTED_SPORTS:
|
||||
sport_name = _SPORT_NAMES.get(sport, f"unknown({sport})")
|
||||
return (
|
||||
"wrong_sport",
|
||||
f"Activity type '{sport_name}' doesn't count as a qualifying run",
|
||||
)
|
||||
|
||||
duration_min = data["duration_seconds"] / 60
|
||||
distance_km = data["distance_m"] / 1000
|
||||
@ -166,7 +159,7 @@ class RunnerUpVerificationMixin(
|
||||
root DB pull if no today's files are found.
|
||||
|
||||
Status values: ``verified | not_verified | no_phone | too_short |
|
||||
wrong_sport | clock_tampered``.
|
||||
clock_tampered``.
|
||||
"""
|
||||
skew_ok, skew_msg = check_clock_skew()
|
||||
if not skew_ok:
|
||||
|
||||
@ -17,6 +17,7 @@ from gatelock import (
|
||||
Arbiter,
|
||||
LockWindow,
|
||||
ScrollableSurface,
|
||||
wait_for_turn,
|
||||
)
|
||||
|
||||
from screen_locker._surface_group import FrameGroup
|
||||
@ -86,6 +87,13 @@ class WindowSetupMixin:
|
||||
disable_vt=self._colors.resolved_disable_vt(),
|
||||
)
|
||||
arbiter.publish()
|
||||
# Published first so anything lower-ranked queues behind us in turn,
|
||||
# then wait with nothing on screen. Never exits here: a higher-ranked
|
||||
# locker (wake_alarm) means "later", never "skip" -- mirrors
|
||||
# leetcode_guard's own fix for the same grab race (gatelock's own
|
||||
# module docstring: 2026-07-25, and again with diet_guard on
|
||||
# 2026-08-21).
|
||||
wait_for_turn(arbiter)
|
||||
arbiter.acquire_holder()
|
||||
lock = LockWindow(self.root, self._colors, hooks=self, arbiter=arbiter)
|
||||
lock.setup()
|
||||
|
||||
@ -18,12 +18,14 @@ from gatelock import (
|
||||
LockWindow,
|
||||
)
|
||||
|
||||
from screen_locker import _instance
|
||||
from screen_locker._auto_upgrade import AutoUpgradeMixin
|
||||
from screen_locker._constants import (
|
||||
EARLY_BIRD_END_HOUR,
|
||||
EARLY_BIRD_END_MINUTE,
|
||||
EARLY_BIRD_START_HOUR,
|
||||
HMAC_KEY_FILE,
|
||||
INSTANCE_LOCK_FILE,
|
||||
MAX_CLOCK_SKEW_SECONDS,
|
||||
MIN_WORKOUT_DURATION_MINUTES,
|
||||
PHONE_PENALTY_DELAY_DEMO,
|
||||
@ -114,6 +116,23 @@ class ScreenLocker(
|
||||
) -> None:
|
||||
"""Initialize screen locker with optional demo mode."""
|
||||
_assert_not_under_pytest()
|
||||
# Guards against a stray re-arm racing a second process into building
|
||||
# a competing lock window (the actual mechanism behind "unlocked, then
|
||||
# locked again seconds later" -- see 2026-08-21 incident notes). Not
|
||||
# released in a try/finally: standing down here calls sys.exit(0)
|
||||
# immediately, and process exit already drops the flock for free.
|
||||
instance_lock = _instance.acquire(INSTANCE_LOCK_FILE)
|
||||
if instance_lock is None:
|
||||
# _instance.acquire already logged who holds it; standing down
|
||||
# here (rather than building a second competing window) is the
|
||||
# fix for the actual mechanism behind "unlocked, then locked
|
||||
# again seconds later".
|
||||
_logger.warning(
|
||||
"standing down: another workout-locker instance already holds %s",
|
||||
INSTANCE_LOCK_FILE,
|
||||
)
|
||||
sys.exit(0)
|
||||
self._instance_lock: _instance.InstanceLock = instance_lock
|
||||
script_dir = Path(__file__).resolve().parent
|
||||
self.log_file = script_dir / "log.json"
|
||||
self.verify_only = verify_only
|
||||
@ -169,6 +188,7 @@ class ScreenLocker(
|
||||
self._lock.close()
|
||||
else:
|
||||
self.root.destroy()
|
||||
self._instance_lock.release()
|
||||
# The lock screen coming down is the end of enforcement for this run,
|
||||
# so it belongs in the journal next to the decision that raised it —
|
||||
# otherwise "the lock closed" and "the lock never opened" look alike.
|
||||
|
||||
54
screen_locker/tests/_isolated_state.py
Normal file
54
screen_locker/tests/_isolated_state.py
Normal file
@ -0,0 +1,54 @@
|
||||
"""On-disk state paths every test must redirect away from the real files.
|
||||
|
||||
Split out of ``conftest.py`` (250-line cap) -- the *fixture* itself has to
|
||||
stay in ``conftest.py`` (pytest only applies autouse fixtures declared
|
||||
there), but this static table has no such constraint.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# Each on-disk state path, and every module that bound it by value at import
|
||||
# time. All of them need patching, not just the _constants source -- a missed
|
||||
# binding lets a test write to the real file.
|
||||
ISOLATED_STATE: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
(
|
||||
"sick_history.json",
|
||||
("_sick_tracker.SICK_HISTORY_FILE", "_constants.SICK_HISTORY_FILE"),
|
||||
),
|
||||
(
|
||||
"early_bird_pending.json",
|
||||
(
|
||||
"_early_bird.EARLY_BIRD_PENDING_FILE",
|
||||
"_constants.EARLY_BIRD_PENDING_FILE",
|
||||
),
|
||||
),
|
||||
(
|
||||
"extra_benefits_state.json",
|
||||
(
|
||||
"_constants.EXTRA_BENEFITS_FILE",
|
||||
"_startup_checks.EXTRA_BENEFITS_FILE",
|
||||
"_sync_mixin.EXTRA_BENEFITS_FILE",
|
||||
"_early_bird.EXTRA_BENEFITS_FILE",
|
||||
"_status.EXTRA_BENEFITS_FILE",
|
||||
),
|
||||
),
|
||||
(
|
||||
"sick_day_state.json",
|
||||
(
|
||||
"_constants.SICK_DAY_STATE_FILE",
|
||||
"_startup_checks.SICK_DAY_STATE_FILE",
|
||||
"_shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
),
|
||||
),
|
||||
("scheduled_skips.json", ("_log_mixin.SCHEDULED_SKIPS_FILE",)),
|
||||
# The durable lock-decision trail. Written on EVERY locker run, so without
|
||||
# this the suite would append test decisions to the user's real
|
||||
# enforcement history in ~/.local/share/screen_locker/.
|
||||
("decisions.jsonl", ("_decision_log.DECISION_LOG_FILE",)),
|
||||
# Real $XDG_RUNTIME_DIR/gatelock file; unisolated, only the first test in
|
||||
# the whole suite would win it, since it is shared across all of them.
|
||||
(
|
||||
"instance.lock",
|
||||
("_constants.INSTANCE_LOCK_FILE", "screen_lock.INSTANCE_LOCK_FILE"),
|
||||
),
|
||||
)
|
||||
@ -25,6 +25,7 @@ from screen_locker.tests._gatelock_fixtures import (
|
||||
_hermetic_gatelock,
|
||||
dual_output,
|
||||
)
|
||||
from screen_locker.tests._isolated_state import ISOLATED_STATE
|
||||
from screen_locker.tests._locker_factories import (
|
||||
_make_locker,
|
||||
create_locker,
|
||||
@ -128,57 +129,18 @@ def _block_real_network() -> Iterator[None]:
|
||||
yield
|
||||
|
||||
|
||||
# Each on-disk state path, and every module that bound it by value at import
|
||||
# time. All of them need patching, not just the _constants source -- a missed
|
||||
# binding lets a test write to the real file.
|
||||
_ISOLATED_STATE: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
(
|
||||
"sick_history.json",
|
||||
("_sick_tracker.SICK_HISTORY_FILE", "_constants.SICK_HISTORY_FILE"),
|
||||
),
|
||||
(
|
||||
"early_bird_pending.json",
|
||||
(
|
||||
"_early_bird.EARLY_BIRD_PENDING_FILE",
|
||||
"_constants.EARLY_BIRD_PENDING_FILE",
|
||||
),
|
||||
),
|
||||
(
|
||||
"extra_benefits_state.json",
|
||||
(
|
||||
"_constants.EXTRA_BENEFITS_FILE",
|
||||
"_startup_checks.EXTRA_BENEFITS_FILE",
|
||||
"_sync_mixin.EXTRA_BENEFITS_FILE",
|
||||
"_early_bird.EXTRA_BENEFITS_FILE",
|
||||
"_status.EXTRA_BENEFITS_FILE",
|
||||
),
|
||||
),
|
||||
(
|
||||
"sick_day_state.json",
|
||||
(
|
||||
"_constants.SICK_DAY_STATE_FILE",
|
||||
"_startup_checks.SICK_DAY_STATE_FILE",
|
||||
"_shutdown_sick_state.SICK_DAY_STATE_FILE",
|
||||
),
|
||||
),
|
||||
("scheduled_skips.json", ("_log_mixin.SCHEDULED_SKIPS_FILE",)),
|
||||
# The durable lock-decision trail. Written on EVERY locker run, so without
|
||||
# this the suite would append test decisions to the user's real
|
||||
# enforcement history in ~/.local/share/screen_locker/.
|
||||
("decisions.jsonl", ("_decision_log.DECISION_LOG_FILE",)),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_state_files(tmp_path: Path) -> Iterator[None]:
|
||||
"""Redirect every on-disk state path to tmp_path for every test.
|
||||
|
||||
Stays in conftest.py and stays autouse: pytest only applies autouse
|
||||
fixtures declared here, so moving this to a sibling module would leave
|
||||
tests writing to the user's real state files while still passing.
|
||||
tests writing to the user's real state files while still passing. The
|
||||
table itself (ISOLATED_STATE) has no such constraint -- see
|
||||
_isolated_state.py.
|
||||
"""
|
||||
with ExitStack() as stack:
|
||||
for filename, bindings in _ISOLATED_STATE:
|
||||
for filename, bindings in ISOLATED_STATE:
|
||||
target = tmp_path / filename
|
||||
for binding in bindings:
|
||||
stack.enter_context(patch(f"screen_locker.{binding}", target))
|
||||
|
||||
@ -67,6 +67,28 @@ class TestScreenLockerInit:
|
||||
|
||||
mock_sys_exit.assert_called_once_with(0)
|
||||
|
||||
def test_init_stands_down_when_instance_lock_already_held(
|
||||
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
|
||||
) -> None:
|
||||
"""A second concurrent process must not build a competing window.
|
||||
|
||||
This is the actual fix for "unlocked, then locked again seconds
|
||||
later" -- see the 2026-08-21 incident notes in screen_lock.py.
|
||||
"""
|
||||
from screen_locker import _instance
|
||||
from screen_locker._constants import INSTANCE_LOCK_FILE
|
||||
|
||||
mock_sys_exit.side_effect = SystemExit(0)
|
||||
held = _instance.acquire(INSTANCE_LOCK_FILE)
|
||||
assert held is not None
|
||||
try:
|
||||
with pytest.raises(SystemExit):
|
||||
create_locker(mock_tk, tmp_path)
|
||||
finally:
|
||||
held.release()
|
||||
|
||||
mock_sys_exit.assert_called_once_with(0)
|
||||
|
||||
|
||||
class TestHasLoggedToday:
|
||||
"""Tests for has_logged_today method."""
|
||||
|
||||
96
screen_locker/tests/test_instance.py
Normal file
96
screen_locker/tests/test_instance.py
Normal file
@ -0,0 +1,96 @@
|
||||
"""Tests for the single-instance lock."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from screen_locker import _instance
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_the_first_run_takes_the_lock(tmp_path: Path) -> None:
|
||||
lock = _instance.acquire(tmp_path / "instance.lock")
|
||||
|
||||
assert lock is not None
|
||||
lock.release()
|
||||
|
||||
|
||||
def test_a_second_run_stands_down(
|
||||
tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Otherwise a stray re-arm races a second window into existence."""
|
||||
path = tmp_path / "instance.lock"
|
||||
first = _instance.acquire(path)
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
second = _instance.acquire(path)
|
||||
|
||||
assert first is not None
|
||||
assert second is None
|
||||
assert any("already holds" in record.message for record in caplog.records)
|
||||
first.release()
|
||||
|
||||
|
||||
def test_the_lock_is_retakeable_after_release(tmp_path: Path) -> None:
|
||||
path = tmp_path / "instance.lock"
|
||||
first = _instance.acquire(path)
|
||||
assert first is not None
|
||||
first.release()
|
||||
|
||||
second = _instance.acquire(path)
|
||||
|
||||
assert second is not None
|
||||
second.release()
|
||||
|
||||
|
||||
def test_an_unopenable_path_reports_failure_rather_than_raising(
|
||||
tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
blocker = tmp_path / "blocker"
|
||||
blocker.write_text("file", encoding="utf-8")
|
||||
|
||||
with caplog.at_level(logging.ERROR):
|
||||
assert _instance.acquire(blocker / "instance.lock") is None
|
||||
|
||||
|
||||
def test_releasing_twice_is_safe(tmp_path: Path) -> None:
|
||||
lock = _instance.acquire(tmp_path / "instance.lock")
|
||||
assert lock is not None
|
||||
|
||||
lock.release()
|
||||
lock.release()
|
||||
|
||||
|
||||
def test_the_lock_file_records_the_pid(tmp_path: Path) -> None:
|
||||
path = tmp_path / "instance.lock"
|
||||
lock = _instance.acquire(path)
|
||||
assert lock is not None
|
||||
|
||||
assert path.read_text(encoding="utf-8") == str(os.getpid())
|
||||
lock.release()
|
||||
|
||||
|
||||
def test_a_close_failure_is_reported_not_raised(
|
||||
tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
lock = _instance.acquire(tmp_path / "instance.lock")
|
||||
assert lock is not None
|
||||
|
||||
class Broken:
|
||||
def close(self) -> None:
|
||||
message = "cannot close"
|
||||
raise OSError(message)
|
||||
|
||||
lock.handle.close()
|
||||
lock.handle = Broken()
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
lock.release()
|
||||
|
||||
assert any("could not close" in record.message for record in caplog.records)
|
||||
@ -26,7 +26,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
@ -83,34 +83,52 @@ def _write_tcx(tmp_path: Path, content: str, name: str = "activity.tcx") -> str:
|
||||
class TestValidateRunnerupData:
|
||||
"""Tests for _validate_runnerup_data (lines 388-411)."""
|
||||
|
||||
def test_wrong_sport_returns_wrong_sport_status(
|
||||
def test_gym_sport_judged_only_on_distance_duration(
|
||||
self,
|
||||
mock_tk: MagicMock,
|
||||
mock_sys_exit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Sport not in RUNNERUP_ACCEPTED_SPORTS → wrong_sport."""
|
||||
"""Any sport (e.g. Gym) is verified purely by distance/duration.
|
||||
|
||||
There is no sport allowlist — a qualifying activity of any RunnerUp
|
||||
sport type counts, matching the workout-locker requirement that
|
||||
RunnerUp entries all be judged the same way.
|
||||
"""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
# Sport 6 = Gym, not accepted
|
||||
status, msg = locker._validate_runnerup_data(
|
||||
{"sport": 6, "duration_seconds": 3600, "distance_m": 6000}
|
||||
)
|
||||
assert status == "wrong_sport"
|
||||
assert status == "verified"
|
||||
assert "Gym" in msg
|
||||
|
||||
def test_walking_sport_judged_only_on_distance_duration(
|
||||
self,
|
||||
mock_tk: MagicMock,
|
||||
mock_sys_exit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A qualifying walk (sport 4) is verified, not rejected as wrong_sport."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
status, msg = locker._validate_runnerup_data(
|
||||
{"sport": 4, "duration_seconds": 3000, "distance_m": 4000}
|
||||
)
|
||||
assert status == "verified"
|
||||
assert "Walking" in msg
|
||||
|
||||
def test_unknown_sport_number_shown_in_message(
|
||||
self,
|
||||
mock_tk: MagicMock,
|
||||
mock_sys_exit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Unknown sport integer falls back to 'unknown(N)' label."""
|
||||
"""Unknown sport integer falls back to its raw number in the message."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
status, msg = locker._validate_runnerup_data(
|
||||
{"sport": 99, "duration_seconds": 3600, "distance_m": 6000}
|
||||
)
|
||||
assert status == "wrong_sport"
|
||||
assert "unknown(99)" in msg
|
||||
assert status == "verified"
|
||||
assert "99" in msg
|
||||
|
||||
def test_short_duration_alone_still_verified_on_distance(
|
||||
self,
|
||||
@ -169,7 +187,7 @@ class TestValidateRunnerupData:
|
||||
mock_sys_exit: MagicMock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Sport 3 (Orienteering) is in RUNNERUP_ACCEPTED_SPORTS."""
|
||||
"""Sport 3 (Orienteering) is verified like any other sport."""
|
||||
locker = create_locker(mock_tk, tmp_path)
|
||||
status, _ = locker._validate_runnerup_data(
|
||||
{"sport": 3, "duration_seconds": 2400, "distance_m": 6000}
|
||||
|
||||
@ -30,7 +30,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -26,7 +26,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -30,7 +30,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -28,7 +28,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -26,7 +26,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -30,7 +30,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -26,7 +26,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -23,7 +23,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -28,7 +28,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -31,7 +31,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -27,7 +27,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -27,7 +27,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -27,7 +27,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -27,7 +27,7 @@ _TCX_RUNNING = """\
|
||||
</TrainingCenterDatabase>
|
||||
"""
|
||||
|
||||
# TCX with an unrecognised sport tag (not in RUNNERUP_ACCEPTED_SPORTS).
|
||||
# TCX with a non-running sport tag (Gym).
|
||||
_TCX_GYM = """\
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<TrainingCenterDatabase
|
||||
|
||||
@ -95,8 +95,18 @@ class ScreenHost(
|
||||
self.root = surface.content.winfo_toplevel()
|
||||
self.demo_mode = False
|
||||
self.verify_only = False
|
||||
# Deliberately NOT the real log.json: is_budget_exhausted() reads it,
|
||||
# and the real file's content depends on today's actual usage --
|
||||
# exhausting the manual-workout budget in production made this crash
|
||||
# (paint_manual_form_with_error touches _mw_error_label, which the
|
||||
# budget-exhausted branch of _show_manual_workout_form never sets).
|
||||
# A path that can never exist keeps every measured screen's shape
|
||||
# independent of live data, which is the same guarantee every other
|
||||
# attribute on this class already gives (see class docstring).
|
||||
self.log_file = (
|
||||
Path(__file__).resolve().parent.parent / "screen_locker" / "log.json"
|
||||
Path(__file__).resolve().parent.parent
|
||||
/ "screen_locker"
|
||||
/ "fit_check_never_exists.json"
|
||||
)
|
||||
self._colors = LockConfig()
|
||||
self.container = FrameGroup([surface.content])
|
||||
|
||||
Loading…
Reference in New Issue
Block a user