Compare commits

...

2 Commits

Author SHA1 Message Date
8429cf04d5 Fix ScreenLocker test-factory log_file isolation flake
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
create_locker (+ _relaxed_day / _early_bird variants) patched
Path.resolve to return tmp_path, but ScreenLocker.__init__ computes
script_dir = Path(__file__).resolve().parent — the .parent turned the
intended per-test tmp_path into tmp_path.parent, pytest's session-shared
temp base. Every factory-built locker therefore shared ONE
workout_log.json, so any test that wrote a log polluted it and
test_saves_pending_marker's `assert not locker.log_file.exists()`
passed or failed purely by random ordering (pytest-randomly).

The flake was invisible until now because CI died at conftest import
(missing crdt_sync) before any test ran; fixing that import in the prior
commit exposed it. Reproduced deterministically at CI seed 2701400184.

Fix: resolve() now returns tmp_path / "screen_locker" so .parent is the
unique per-test tmp_path — each locker gets its own log_file. Also stops
tests writing workout_log.json into the real source tree. Verified 747
passed across seeds 2701400184/1/42/999/123456 (was 1 failed at the CI
seed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018PMRRVVkeRyrSaaqueMZKG
2026-07-11 17:20:01 +02:00
53140a96e2 Fix pre-existing CI failures (crdt_sync dep, dead type:ignore, ruff)
CI ran on 399f981 before these fixes landed; both workflows were red:

- Tests: ModuleNotFoundError: No module named 'crdt_sync'. CI installs
  requirements.txt (not pyproject deps), which lacked the crdt-sync git
  dependency the Workstream-C sync introduced. Add crdt-sync + mcp>=1.9
  to requirements.txt (mirrors diet-guard's fix).
- pre-commit no-noqa: ~45 `# type: ignore[attr-defined]` comments across
  _auto_upgrade/_runnerup_db/_status/_heat_skip flagged repo-wide by the
  no-noqa hook. The mypy hook already runs with
  --disable-error-code=attr-defined, so every one of these ignores was
  suppressing an already-disabled check — dead weight. Removed them; mypy
  and pytest (747 passed, 100% cov) both stay green. Same for the test's
  redundant `# type: ignore[override]` (override never fired).
- pre-commit ruff: FBT003 in _heat_skip.py (tk positional bools, its API)
  and C901/PLR0912 in _status.py run_status (branchy weekly pipeline by
  design) — added per-file-ignores with rationale, matching the existing
  ignores for the sibling validation-chain modules.
- Added crdt-sync/mcp/pydantic to the pylint hook's additional_dependencies
  so pylint can resolve the new imports.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018PMRRVVkeRyrSaaqueMZKG
2026-07-11 17:05:03 +02:00
9 changed files with 59 additions and 51 deletions

View File

@ -93,6 +93,9 @@ repos:
additional_dependencies:
- pytest
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.1.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync
- mcp
- pydantic
- repo: https://github.com/PyCQA/bandit
rev: 1.7.10

View File

@ -64,7 +64,13 @@ unfixable = []
# branch and a crash risk in the lock's startup path for zero real benefit).
"screen_locker/_temperature.py" = ["S310"]
"screen_locker/_shutdown_base.py" = ["SLF001"]
"screen_locker/_status.py" = ["PLR0915", "SLF001", "T201"]
# run_status walks the weekly-status pipeline (weekly logic, RunnerUp scan,
# bonus, heat-skip) as a sequence of stages — genuinely branchy by design, same
# rationale as the validation-chain functions below; not a config-object case.
"screen_locker/_status.py" = ["C901", "PLR0912", "PLR0915", "SLF001", "T201"]
# _heat_skip.py opens a tkinter fullscreen window; tk's .attributes()/other
# calls take positional booleans (its API), which FBT003 always flags.
"screen_locker/_heat_skip.py" = ["FBT003"]
# StatusWindow.__init__ takes one arg per independently-mocked dependency
# (verifier_factory, temperature_fetcher, log_file, ...) — same
# dependency-injection rationale as _status_data.py's gather_status below.

View File

@ -3,7 +3,9 @@
bandit>=1.7.0
codespell>=2.2.0
coverage>=7.4.0
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.1.0#subdirectory=crdt-sync
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.1.0#subdirectory=gatelock
mcp>=1.9
mypy>=1.8.0
pre-commit>=3.6.0
pylint>=3.0.0

View File

@ -35,32 +35,29 @@ class AutoUpgradeMixin:
_logger.info("No sick day logged today. Nothing to verify.")
sys.exit(0)
return
self._check_non_verify_exits() # type: ignore[attr-defined]
self._check_non_verify_exits()
def _check_today_state_exits(self) -> bool:
"""Handle early-bird and today's log states. Return True to stop startup."""
if (
self._is_early_bird_pending() # type: ignore[attr-defined]
and not self._is_early_bird_time() # type: ignore[attr-defined]
):
if self._is_early_bird_pending() and not self._is_early_bird_time():
if self._try_auto_upgrade_early_bird():
_logger.info("Auto-upgraded early_bird entry to phone_verified.")
sys.exit(0)
return True
return False # Expired early bird, upgrade unavailable — full lock.
if self._is_early_bird_pending(): # type: ignore[attr-defined]
if self._is_early_bird_pending():
_logger.info("Early bird window still active — skipping lock.")
elif self._is_sick_day_today():
if self._try_auto_upgrade_sick_day():
_logger.info("Auto-upgraded today's sick_day entry to phone_verified.")
else:
_logger.info("Sick day already logged today.")
elif self.has_logged_today(): # type: ignore[attr-defined]
elif self.has_logged_today():
_logger.info("Workout already logged today. Skipping screen lock.")
elif has_workout_skip_today():
_logger.info("Wake alarm earned workout skip. Skipping screen lock.")
elif self._is_early_bird_time(): # type: ignore[attr-defined]
self._save_early_bird_pending() # type: ignore[attr-defined]
elif self._is_early_bird_time():
self._save_early_bird_pending()
_logger.info("Early bird time — skipping lock, will re-check at 08:30.")
else:
return False
@ -70,20 +67,20 @@ class AutoUpgradeMixin:
def _try_auto_upgrade_sick_day(self) -> bool:
"""Upgrade sick_day entry when phone or RunnerUp detects a valid workout."""
try:
status, message = self._verify_phone_workout() # type: ignore[attr-defined]
status, message = self._verify_phone_workout()
except (OSError, RuntimeError) as exc:
_logger.info("Auto-upgrade phone check failed: %s", exc)
status, message = "error", str(exc)
if status == "verified":
self.workout_data["type"] = "phone_verified" # type: ignore[attr-defined]
self.workout_data["source"] = message # type: ignore[attr-defined]
self.workout_data["after_sick_day"] = "true" # type: ignore[attr-defined]
self._adjust_shutdown_time_later() # type: ignore[attr-defined]
self.save_workout_log() # type: ignore[attr-defined]
self.workout_data["type"] = "phone_verified"
self.workout_data["source"] = message
self.workout_data["after_sick_day"] = "true"
self._adjust_shutdown_time_later()
self.save_workout_log()
return True
_logger.info("Auto-upgrade phone skipped (%s), trying RunnerUp...", status)
try:
runnerup_status, runnerup_msg = self._verify_runnerup_workout() # type: ignore[attr-defined]
runnerup_status, runnerup_msg = self._verify_runnerup_workout()
except (OSError, RuntimeError) as exc:
_logger.info("Auto-upgrade RunnerUp check failed: %s", exc)
return False
@ -92,30 +89,30 @@ class AutoUpgradeMixin:
"Auto-upgrade RunnerUp skipped (%s): %s", runnerup_status, runnerup_msg
)
return False
self.workout_data["type"] = "runnerup_verified" # type: ignore[attr-defined]
self.workout_data["source"] = runnerup_msg # type: ignore[attr-defined]
self.workout_data["after_sick_day"] = "true" # type: ignore[attr-defined]
self._adjust_shutdown_time_later() # type: ignore[attr-defined]
self.save_workout_log() # type: ignore[attr-defined]
self.workout_data["type"] = "runnerup_verified"
self.workout_data["source"] = runnerup_msg
self.workout_data["after_sick_day"] = "true"
self._adjust_shutdown_time_later()
self.save_workout_log()
return True
def _try_auto_upgrade_early_bird(self) -> bool:
"""Try phone then RunnerUp to upgrade an early_bird log entry."""
try:
status, message = self._verify_phone_workout() # type: ignore[attr-defined]
status, message = self._verify_phone_workout()
except (OSError, RuntimeError) as exc:
_logger.info("Early bird upgrade phone check failed: %s", exc)
status, message = "error", str(exc)
if status == "verified":
self.workout_data["type"] = "phone_verified" # type: ignore[attr-defined]
self.workout_data["source"] = message # type: ignore[attr-defined]
self.workout_data["after_early_bird"] = "true" # type: ignore[attr-defined]
self._adjust_shutdown_time_later() # type: ignore[attr-defined]
self.save_workout_log() # type: ignore[attr-defined]
self.workout_data["type"] = "phone_verified"
self.workout_data["source"] = message
self.workout_data["after_early_bird"] = "true"
self._adjust_shutdown_time_later()
self.save_workout_log()
return True
_logger.info("Early bird phone skipped (%s), trying RunnerUp...", status)
try:
runnerup_status, runnerup_msg = self._verify_runnerup_workout() # type: ignore[attr-defined]
runnerup_status, runnerup_msg = self._verify_runnerup_workout()
except (OSError, RuntimeError) as exc:
_logger.info("Early bird RunnerUp check failed: %s", exc)
return False
@ -124,9 +121,9 @@ class AutoUpgradeMixin:
"Early bird RunnerUp skipped (%s): %s", runnerup_status, runnerup_msg
)
return False
self.workout_data["type"] = "runnerup_verified" # type: ignore[attr-defined]
self.workout_data["source"] = runnerup_msg # type: ignore[attr-defined]
self.workout_data["after_early_bird"] = "true" # type: ignore[attr-defined]
self._adjust_shutdown_time_later() # type: ignore[attr-defined]
self.save_workout_log() # type: ignore[attr-defined]
self.workout_data["type"] = "runnerup_verified"
self.workout_data["source"] = runnerup_msg
self.workout_data["after_early_bird"] = "true"
self._adjust_shutdown_time_later()
self.save_workout_log()
return True

View File

@ -113,9 +113,9 @@ class HeatSkipMixin:
def _save_heat_skip_log(self, temp: float) -> None:
"""Append a heat_skip entry to workout_log.json."""
self.workout_data = { # type: ignore[attr-defined]
self.workout_data = {
"type": "heat_skip",
"temperature_celsius": str(round(temp)),
"city": HEAT_SKIP_CITY,
}
self.save_workout_log() # type: ignore[attr-defined]
self.save_workout_log()

View File

@ -28,7 +28,7 @@ class RunnerUpDbMixin:
def _find_runnerup_package(self) -> str | None:
"""Return the first installed RunnerUp package name, or None."""
for pkg in RUNNERUP_PACKAGES:
ok, out = self._adb_shell(f"pm list packages {pkg}") # type: ignore[attr-defined]
ok, out = self._adb_shell(f"pm list packages {pkg}")
if ok and pkg in out:
return pkg
return None
@ -52,7 +52,7 @@ class RunnerUpDbMixin:
tmp_dir = tempfile.mkdtemp(prefix="runnerup_verify_")
local_db = str(Path(tmp_dir) / "runnerup.db")
ok, err = self._adb_shell( # type: ignore[attr-defined]
ok, err = self._adb_shell(
f"cp {db_device} {RUNNERUP_DB_SDCARD_TMP}",
root=True,
)
@ -62,14 +62,14 @@ class RunnerUpDbMixin:
return None
for suffix in ("-wal", "-shm"):
self._adb_shell( # type: ignore[attr-defined]
self._adb_shell(
f"test -f {db_device}{suffix} "
f"&& cp {db_device}{suffix} {RUNNERUP_DB_SDCARD_TMP}{suffix} "
f"|| true",
root=True,
)
ok, _ = self._run_adb(["pull", RUNNERUP_DB_SDCARD_TMP, local_db]) # type: ignore[attr-defined]
ok, _ = self._run_adb(["pull", RUNNERUP_DB_SDCARD_TMP, local_db])
if not ok:
_logger.info("adb pull of RunnerUp DB failed")
self._cleanup_runnerup_sdcard()
@ -77,7 +77,7 @@ class RunnerUpDbMixin:
return None
for suffix in ("-wal", "-shm"):
self._run_adb( # type: ignore[attr-defined]
self._run_adb(
["pull", f"{RUNNERUP_DB_SDCARD_TMP}{suffix}", f"{local_db}{suffix}"]
)
@ -87,7 +87,7 @@ class RunnerUpDbMixin:
def _cleanup_runnerup_sdcard(self) -> None:
"""Remove temporary RunnerUp DB files from the sdcard."""
for suffix in ("", "-wal", "-shm"):
self._adb_shell( # type: ignore[attr-defined]
self._adb_shell(
f"test -f {RUNNERUP_DB_SDCARD_TMP}{suffix} "
f"&& rm {RUNNERUP_DB_SDCARD_TMP}{suffix} || true",
root=True,
@ -147,4 +147,4 @@ class RunnerUpDbMixin:
if run_data is None:
return "not_verified", "No RunnerUp activity found for today"
return self._validate_runnerup_data(run_data) # type: ignore[attr-defined]
return self._validate_runnerup_data(run_data)

View File

@ -69,7 +69,7 @@ def run_status(locker: ScreenLocker) -> None:
"""Print weekly workout status, run RunnerUp scan, apply bonus, then exit."""
today = datetime.now(tz=timezone.utc).astimezone().date()
monday = today - timedelta(days=today.weekday())
log_file: Path = locker.log_file # type: ignore[attr-defined]
log_file: Path = locker.log_file
log_data = _load_log(log_file)
sick_days = set(load_history().sick_days)
@ -87,13 +87,13 @@ def run_status(locker: ScreenLocker) -> None:
print()
# RunnerUp scan
n_filled = locker._scan_and_fill_week_runnerup(log_file) # type: ignore[attr-defined]
n_filled = locker._scan_and_fill_week_runnerup(log_file)
if n_filled > 0:
print(f" Auto-filled {n_filled} workout(s) from RunnerUp exports.")
after_count = count_weekly_workouts(log_file)
bonus = max(0, after_count - max(WEEKLY_WORKOUT_MINIMUM, before_count))
if bonus > 0:
ok = locker._adjust_shutdown_time_by(bonus) # type: ignore[attr-defined]
ok = locker._adjust_shutdown_time_by(bonus)
if ok:
print(f" +{bonus}h shutdown bonus applied.")
else:
@ -147,7 +147,7 @@ def run_status(locker: ScreenLocker) -> None:
)
# Shutdown config
cfg = locker._read_shutdown_config() # type: ignore[attr-defined]
cfg = locker._read_shutdown_config()
if cfg:
_mw, _ts, _morning = cfg
print(f" Shutdown tonight : {_mw:02d}:00")

View File

@ -305,7 +305,7 @@ def create_locker(
) -> ScreenLocker:
"""Create a ScreenLocker instance with early bird paths disabled."""
with (
patch.object(Path, "resolve", return_value=tmp_path),
patch.object(Path, "resolve", return_value=tmp_path / "screen_locker"),
patch.object(ScreenLocker, "has_logged_today", return_value=has_logged),
patch.object(
ScreenLocker,
@ -344,7 +344,7 @@ def create_locker_relaxed_day(
The autouse ``_mock_weekly_logic`` fixture is overridden here.
"""
with (
patch.object(Path, "resolve", return_value=tmp_path),
patch.object(Path, "resolve", return_value=tmp_path / "screen_locker"),
patch.object(ScreenLocker, "has_logged_today", return_value=has_logged),
patch.object(ScreenLocker, "_is_sick_day_today", return_value=False),
patch.object(ScreenLocker, "_is_early_bird_pending", return_value=False),
@ -383,7 +383,7 @@ def create_locker_early_bird(
is_early_bird_log = state in ("log_active", "log_expired")
is_early_bird_time = state == "log_active"
with (
patch.object(Path, "resolve", return_value=tmp_path),
patch.object(Path, "resolve", return_value=tmp_path / "screen_locker"),
patch.object(ScreenLocker, "has_logged_today", return_value=has_logged),
patch.object(ScreenLocker, "_is_sick_day_today", return_value=False),
patch.object(

View File

@ -143,7 +143,7 @@ class TestRunStatusMinimumStatus:
class _FakeDatetime(datetime):
@classmethod
def now(cls, tz=None): # type: ignore[override]
def now(cls, tz=None):
return fake_now.astimezone(tz) if tz else fake_now
with (