Compare commits

...

4 Commits

Author SHA1 Message Date
2d728fb791 workout_app: same 30/25 duration bar as the locker
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (flutter, flutter-analyze, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint,flutter-analyze) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / lock-popup-safety (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (0) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (1) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (2) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (3) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (4) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (5) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (6) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (7) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (8) (push) Waiting to run
Tests / flutter test (shard ${{ matrix.shard }}) (9) (push) Waiting to run
Tests / flutter-coverage (push) Blocked by required conditions
Tests / web-coverage (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-01 17:34:14 +01:00
dc885b9903 One workout duration bar for every activity: advertise 30, accept 25 (walks included)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-01 17:33:33 +01:00
8b0fb81d7b Temperature bound test: assert the default is at most 5 s, not exactly 5 s
The original only bounded the elapsed time, so == 5.0 was stricter than the
requirement it replaced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:31:26 +01:00
f04b0d0efd Commit gate: pytest 67.7 s serial -> 9.4 s, screens-fit hook 3.6 s -> 0.7 s
- addopts: -n 4 --dist worksteal (fixed, not auto: 24 workers would break
  capped.sh's 4 GiB). CI's own -n auto still wins.
- coverage core = sysmon (PEP 669): ~40% less tracing overhead, same data.
- shutdown ceiling invariant: one plain-function patch of earned_units per
  day instead of a MagicMock per unit (~5000 per case); every day and every
  case still checked.
- poke/web server tests: serve_forever(poll_interval=0.01), so shutdown()
  no longer waits 0.5 s per test.
- autouse _no_real_ntp: check_clock_skew sent real UDP to pool.ntp.org from
  every verification test, and a lost reply cost a random test 5 s.
- temperature hard-timeout test: pins the default to 5 s and times the
  mechanism at 0.1 s instead of waiting 5 real seconds.
- _xvfb_reexec: Xvfb -displayfd instead of xvfb-run's fixed 3 s sleep.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:27:27 +01:00
19 changed files with 176 additions and 95 deletions

View File

@ -58,11 +58,11 @@ jobs:
enable-cache: true
cache-dependency-glob: requirements.txt
# No apt step: the runner image already ships xvfb-run, and
# No apt step: the runner image already ships Xvfb, and
# setup-python's interpreter has its own tkinter (python3-tk is for the
# system python, which this job never runs). The apt-get update +
# install cost ~35 s. If either ever goes missing the check does not
# skip -- _xvfb_reexec returns 1 without xvfb-run, and the import fails
# skip -- _xvfb_reexec returns 1 without Xvfb, and the import fails
# without tkinter.
- name: Install dependencies
run: |

View File

@ -231,6 +231,14 @@ addopts = [
"--cov-branch",
"--cov-report=term-missing",
"--cov-report=lcov",
# The commit gate runs plain `python -m pytest -q`; serial it took 26 s of
# its 60 s budget, 4 workers 9 s. Fixed, not `auto`: auto is 24 workers
# here, past capped.sh's 4 GiB. CI's own `-n auto` comes later and wins;
# `-n0` gets a serial run back.
"-n",
"4",
"--dist",
"worksteal",
# A fixture-only plugin module, not conftest.py (already at the
# repo's 400-line-per-file cap) -- see its own docstring.
"-p",
@ -245,6 +253,9 @@ filterwarnings = [
[tool.coverage.run]
source = ["screen_locker"]
branch = true
# sys.monitoring (PEP 669) rather than the C tracer: test_shutdown_ceiling_
# invariant.py alone measured 13 s vs 22 s, for the same line+branch data.
core = "sysmon"
omit = [
"*/__pycache__/*",
"*/tests/*",

View File

@ -53,13 +53,13 @@ WORKOUT_APP_JSON_REMOTES = (
)
# Port the workout app's HTTP server listens on (no ADB/developer-options needed).
WORKOUT_HTTP_PORT = 8765
# The ONE duration bar every workout type answers to — weightlifting, manual
# entries and runs alike. This is the ADVERTISED number: it is the only one
# that may ever appear in a message the user reads.
MIN_WORKOUT_DURATION_MINUTES = 40
# The ONE duration bar every activity answers to — weightlifting, manual
# entries, runs and walks (summed moving time) alike. This is the ADVERTISED
# number: it is the only one that may ever appear in a message the user reads.
MIN_WORKOUT_DURATION_MINUTES = 30
# ...and this is the leeway that is deliberately INVISIBLE. A session is
# actually accepted at MIN_WORKOUT_DURATION_MINUTES - this, so 35 minutes
# passes while every string still says 40. That gap is intentional (the user
# actually accepted at MIN_WORKOUT_DURATION_MINUTES - this, so 25 minutes
# passes while every string still says 30. That gap is intentional (the user
# asked for it explicitly): do NOT "fix" the inconsistency by advertising the
# real cutoff, and never interpolate WORKOUT_DURATION_ACCEPT_MINUTES into an
# f-string.
@ -67,7 +67,7 @@ WORKOUT_DURATION_LEEWAY_MINUTES = 5
# Derived so the advertised bar and the accept bar cannot drift apart.
# Comparisons use this; messages use MIN_WORKOUT_DURATION_MINUTES. Every
# caller compares with `>=` — one operator across all workout types, so a
# 35.0-minute session cannot pass one gate and fail another.
# 25.0-minute session cannot pass one gate and fail another.
WORKOUT_DURATION_ACCEPT_MINUTES = (
MIN_WORKOUT_DURATION_MINUTES - WORKOUT_DURATION_LEEWAY_MINUTES
)
@ -106,8 +106,8 @@ REST_DAY_FILE = Path(__file__).resolve().parent / "rest_days.json"
REST_DAYS_PER_ISO_WEEK = 2
GRACE_STATE_FILE = Path(__file__).resolve().parent / "grace_floor.json"
# A day's RunnerUp walks (commute legs) count as the workout once their
# MOVING time sums to this; moving = trackpoint pairs at walking speed.
WALK_MIN_MOVING_MINUTES = 40
# MOVING time reaches WORKOUT_DURATION_ACCEPT_MINUTES (the shared bar above);
# moving = trackpoint pairs at walking speed.
WALK_SPEED_MPS = (0.5, 3.0)
WALK_MAX_GAP_SECONDS = 30
# Workout records this PC must keep deleted in the sync store, pushed as

View File

@ -1,8 +1,8 @@
"""Walking in RunnerUp TCX exports: which files are walks, and their moving time.
A day's walking counts as the workout once its walks -- usually separate
commute legs, one file each -- add up to ``WALK_MIN_MOVING_MINUTES`` of
*moving* time.
commute legs, one file each -- add up to the shared workout duration bar
(``WORKOUT_DURATION_ACCEPT_MINUTES``) of *moving* time.
**Which files are walks.** RunnerUp's WebDAV and File synchronisers both
export with ``ExportOptions.getDefault()``, whose TCX writer knows only
@ -29,9 +29,10 @@ import logging
from typing import TYPE_CHECKING, Any
from screen_locker._constants import (
MIN_WORKOUT_DURATION_MINUTES,
WALK_MAX_GAP_SECONDS,
WALK_MIN_MOVING_MINUTES,
WALK_SPEED_MPS,
WORKOUT_DURATION_ACCEPT_MINUTES,
)
if TYPE_CHECKING:
@ -109,7 +110,7 @@ class WalkDay:
@property
def qualifies(self) -> bool:
"""Whether the day's walking counts as its workout."""
return self.moving_minutes >= WALK_MIN_MOVING_MINUTES
return self.moving_minutes >= WORKOUT_DURATION_ACCEPT_MINUTES
def message(self) -> str:
"""The verification line, in the RunnerUp verifier's own style."""
@ -121,7 +122,7 @@ class WalkDay:
def walk_shortfall(day: WalkDay) -> str:
"""Why a day's walking did not count yet."""
return f"{day.message()} -- need {WALK_MIN_MOVING_MINUTES}+ min moving"
return f"{day.message()} -- need {MIN_WORKOUT_DURATION_MINUTES}+ min moving"
def walk_day(walks: Iterable[dict[str, Any]]) -> WalkDay:
@ -134,7 +135,7 @@ def walk_day(walks: Iterable[dict[str, Any]]) -> WalkDay:
completed_at: float | None = None
for walk in ordered:
moving += float(walk.get("moving_seconds", 0.0))
if completed_at is None and moving / 60 >= WALK_MIN_MOVING_MINUTES:
if completed_at is None and moving / 60 >= WORKOUT_DURATION_ACCEPT_MINUTES:
completed_at = walk.get("ended_at")
return WalkDay(
legs=len(ordered),

View File

@ -200,3 +200,17 @@ def _no_real_night_lockdown(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) ->
"NIGHT_LOCKDOWN_STAMP",
tmp_path / "locked_at_epoch",
)
@pytest.fixture(autouse=True)
def _no_real_ntp() -> Iterator[None]:
"""Never send a real NTP query to pool.ntp.org from a test.
``check_clock_skew`` (every phone and RunnerUp verification) opens a UDP
socket, which ``_block_real_network``'s ``create_connection`` stub cannot
reach. A lost reply cost a test the full 5 s ``_NTP_TIMEOUT``, at random.
Stubbed as "unreachable", what the real query answers on any OSError.
``test_time_check`` drives the real query through its own import.
"""
with patch("screen_locker._time_check._query_ntp_offset", return_value=None):
yield

View File

@ -8,16 +8,16 @@
"threshold, change it here and watch both suites fail together.",
"",
"advertised_minutes is the ONLY number that may appear in a user-facing",
"message. accept_minutes is deliberately invisible: a 35-minute session",
"passes while every string still says 40. Do not advertise accept_minutes."
"message. accept_minutes is deliberately invisible: a 25-minute session",
"passes while every string still says 30. Do not advertise accept_minutes."
],
"advertised_minutes": 40,
"advertised_minutes": 30,
"leeway_minutes": 5,
"accept_minutes": 35,
"accept_minutes": 25,
"cases": [
{ "duration_minutes": 34, "accepted": false },
{ "duration_minutes": 35, "accepted": true },
{ "duration_minutes": 40, "accepted": true },
{ "duration_minutes": 24, "accepted": false },
{ "duration_minutes": 25, "accepted": true },
{ "duration_minutes": 30, "accepted": true },
{ "duration_minutes": 60, "accepted": true }
]
}

View File

@ -52,7 +52,8 @@ def port(monkeypatch: pytest.MonkeyPatch) -> Iterator[int]:
"""A running PokeServer on 127.0.0.1:0; shut down afterwards."""
monkeypatch.setattr(socket, "create_connection", _REAL_CREATE_CONNECTION)
server = PokeServer(("127.0.0.1", 0), _KEY)
thread = threading.Thread(target=server.serve_forever, daemon=True)
# poll_interval: shutdown() waits out one poll, 0.5 s per test by default.
thread = threading.Thread(target=server.serve_forever, args=(0.01,), daemon=True)
thread.start()
try:
yield server.server_address[1]

View File

@ -156,16 +156,16 @@ class TestValidateRunnerupData:
) -> None:
"""Both criteria missed → too_short naming both.
0.1 km is far under the distance line and 30 min is under the duration
0.1 km is far under the distance line and 20 min is under the duration
line, so neither branch of the OR qualifies.
"""
locker = create_locker(mock_tk, tmp_path)
status, msg = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 1800, "distance_m": 100}
{"sport": 0, "duration_seconds": 1200, "distance_m": 100}
)
assert status == "too_short"
assert "3.5+ km" in msg
assert "40+ min" in msg
assert "30+ min" in msg
def test_valid_run_returns_verified(
self,

View File

@ -106,14 +106,14 @@ class TestValidateRunnerupDataOrCriteria:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""3.0 km in 25 min misses both branches; message names both."""
"""3.0 km in 20 min misses both branches; message names both."""
locker = create_locker(mock_tk, tmp_path)
status, msg = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 1500, "distance_m": 3000}
{"sport": 0, "duration_seconds": 1200, "distance_m": 3000}
)
assert status == "too_short"
# Pinned literally: a ':.0f' format spec would render 3.5 as "4".
assert "need 3.5+ km or 40+ min" in msg
assert "need 3.5+ km or 30+ min" in msg
def test_distance_boundary_is_inclusive(
self,
@ -134,22 +134,22 @@ class TestValidateRunnerupDataOrCriteria:
mock_sys_exit: MagicMock,
tmp_path: Path,
) -> None:
"""Runs answer to the shared accept bar (35), not the advertised 40.
"""Runs answer to the shared accept bar (25), not the advertised 30.
The distance stays at 1 km throughout so the OR distance arm cannot
rescue the run — this pins the duration arm alone.
"""
locker = create_locker(mock_tk, tmp_path)
just_under, _ = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 2094, "distance_m": 1000}
{"sport": 0, "duration_seconds": 1494, "distance_m": 1000}
)
assert just_under == "too_short"
at_accept_bar, _ = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 2100, "distance_m": 1000}
{"sport": 0, "duration_seconds": 1500, "distance_m": 1000}
)
assert at_accept_bar == "verified"
def test_too_short_message_advertises_40_not_the_real_cutoff(
def test_too_short_message_advertises_30_not_the_real_cutoff(
self,
mock_tk: MagicMock,
mock_sys_exit: MagicMock,

View File

@ -91,12 +91,12 @@ class TestValidateRunnerupDataDistanceTolerance:
) -> None:
"""3.45 km * 1.05 = 3.62 >= 3.5 km minimum → verified.
Duration is held under 40 min so the distance branch is what is
Duration is held under the 25-min accept bar so the distance branch is what is
actually under test, not the duration branch of the OR.
"""
locker = create_locker(mock_tk, tmp_path)
status, msg = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 1500, "distance_m": 3450.0}
{"sport": 0, "duration_seconds": 1200, "distance_m": 3450.0}
)
assert status == "verified"
assert "3.5 km" in msg
@ -109,11 +109,12 @@ class TestValidateRunnerupDataDistanceTolerance:
) -> None:
"""3.0 km * 1.05 = 3.15 km, still short of the 3.5 km minimum → too_short.
Duration is under 40 min so the duration branch cannot rescue it.
Duration is under the 25-min accept bar so the duration branch cannot
rescue it.
"""
locker = create_locker(mock_tk, tmp_path)
status, msg = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 1500, "distance_m": 3000}
{"sport": 0, "duration_seconds": 1200, "distance_m": 3000}
)
assert status == "too_short"
assert "3.5+ km" in msg
@ -128,6 +129,6 @@ class TestValidateRunnerupDataDistanceTolerance:
additive leeway, not a stricter requirement)."""
locker = create_locker(mock_tk, tmp_path)
status, _ = locker._validate_runnerup_data(
{"sport": 0, "duration_seconds": 1947, "distance_m": 5000}
{"sport": 0, "duration_seconds": 1200, "distance_m": 5000}
)
assert status == "verified"

View File

@ -97,8 +97,8 @@ class TestVerifyToday:
return verifier._verify_runnerup_via_files()
def test_walks_summing_to_the_bar_verify(self, verifier: Verifier) -> None:
drop(verifier.folder, "08-00-00_Walking", tcx("Other", 25, "08:00"))
drop(verifier.folder, "17-00-00_Walking", tcx("Other", 20, "17:00"))
drop(verifier.folder, "08-00-00_Walking", tcx("Other", 15, "08:00"))
drop(verifier.folder, "17-00-00_Walking", tcx("Other", 12, "17:00"))
result = self._verify(verifier)
assert result is not None
assert result[0] == "verified"
@ -111,7 +111,7 @@ class TestVerifyToday:
drop(verifier.folder, "08-00-00_Walking", tcx("Other", 60, "08:00", 0.1))
assert self._verify(verifier) == (
"too_short",
"Walking: 1 walk(s), 0.4 km, 0 min moving -- need 40+ min moving",
"Walking: 1 walk(s), 0.4 km, 0 min moving -- need 30+ min moving",
)
def test_a_run_still_verifies_beside_short_walks(self, verifier: Verifier) -> None:
@ -135,8 +135,8 @@ class TestBackfill:
def test_walks_are_logged_as_one_workout(
self, verifier: Verifier, tmp_path: Path
) -> None:
drop(verifier.folder, "08-00-00_Walking", tcx("Other", 25, "08:00"))
drop(verifier.folder, "17-00-00_Walking", tcx("Other", 20, "17:00"))
drop(verifier.folder, "08-00-00_Walking", tcx("Other", 15, "08:00"))
drop(verifier.folder, "17-00-00_Walking", tcx("Other", 12, "17:00"))
log = tmp_path / "log.json"
ingested = MagicMock()
assert verifier._try_fill_runnerup_for_date(_DAY, log, ingested) is True
@ -144,10 +144,10 @@ class TestBackfill:
data = entry["workout_data"]
assert data["type"] == "runnerup_verified"
assert data["activity"] == "walking"
assert data["duration_minutes"] == pytest.approx(45)
assert data["duration_minutes"] == pytest.approx(27)
assert (
data["completed_at"]
== datetime(2026, 10, 10, 17, 20, tzinfo=UTC).timestamp()
== datetime(2026, 10, 10, 17, 12, tzinfo=UTC).timestamp()
)
ingested.assert_called_once()
# The same day again is the same slot: nothing new.
@ -159,7 +159,7 @@ class TestBackfill:
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
drop(verifier.folder, "08-00-00_Walking", tcx("Other", 30, "08:00"))
drop(verifier.folder, "08-00-00_Walking", tcx("Other", 20, "08:00"))
log = tmp_path / "log.json"
with caplog.at_level(logging.WARNING):
assert verifier._try_fill_runnerup_for_date(_DAY, log) is False

View File

@ -65,16 +65,16 @@ class TestValidateSession:
assert "not a number" in detail
def test_accepts_exactly_the_hidden_accept_threshold(self) -> None:
"""35 min passes; the message still advertises the round 40."""
ok, _ = validate_session(_session(duration_seconds=35 * 60))
"""25 min passes; the message still advertises the round 30."""
ok, _ = validate_session(_session(duration_seconds=25 * 60))
assert ok
def test_rejects_just_below_the_accept_threshold(self) -> None:
ok, detail = validate_session(_session(duration_seconds=34 * 60 + 59))
ok, detail = validate_session(_session(duration_seconds=24 * 60 + 59))
assert not ok
# The real bar (35) must never leak into a user-visible string.
assert "35" not in detail
assert "40 min" in detail
# The real bar (25) must never leak into a user-visible string.
assert "25" not in detail
assert "30 min" in detail
class TestBuildSessionEntry:

View File

@ -161,12 +161,17 @@ def _live_pass(day: date, case: tuple[str, bool, int, str]) -> int:
for _ in range(further if extra else 0):
host._adjust_shutdown_time_by(extra, at=when)
state: dict[str, Any] = {}
for gate in (e for e in registry_for(day) if is_gate(e)):
if gate.kind == "flat":
host._adjust_shutdown_time_by(first_minutes(gate, day), at=when)
continue
for units in range(1, (gate.max_units or 1) + 1):
with patch.object(_gate_bonus, "earned_units", return_value=units):
# One plain-function patch per day, not a MagicMock per unit: building
# ~5000 mocks was half of this file's runtime. ``answered`` is the ledger's
# unit count at the moment each counted credit is applied.
answered = [0]
with patch.object(_gate_bonus, "earned_units", lambda _e, _d: answered[0]):
for gate in (e for e in registry_for(day) if is_gate(e)):
if gate.kind == "flat":
host._adjust_shutdown_time_by(first_minutes(gate, day), at=when)
continue
for units in range(1, (gate.max_units or 1) + 1):
answered[0] = units
apply_counted_bonus(
state,
partial(host._adjust_shutdown_time_by, at=when),

View File

@ -3,6 +3,8 @@
from __future__ import annotations
import http.client
from inspect import signature
import threading
import time
from unittest.mock import MagicMock, patch
import urllib.error
@ -134,16 +136,26 @@ class TestNothingEscapesTheFetch:
assert result.timed_out is False
def test_the_whole_check_is_bounded_by_the_hard_timeout(self) -> None:
"""The user's requirement: at most 5s, then lock regardless."""
"""The user's requirement: at most 5s, then lock regardless.
The bound is the default argument, so it is pinned to at most 5s here
and the mechanism is timed at 0.1s: the same guarantee without 5 real
seconds.
"""
default = signature(fetch_current_temp_with_status).parameters["hard_timeout"]
assert default.default == HARD_TIMEOUT_SECONDS
assert HARD_TIMEOUT_SECONDS <= 5.0
hang = threading.Event()
with patch(
"screen_locker._temperature._fetch_current_temp_celsius_unbounded",
side_effect=lambda _city: time.sleep(30),
side_effect=lambda _city: hang.wait(30),
):
started = time.monotonic()
result = fetch_current_temp_with_status("Warsaw")
result = fetch_current_temp_with_status("Warsaw", hard_timeout=0.1)
elapsed = time.monotonic() - started
hang.set() # release the abandoned worker thread
assert result.timed_out is True
assert elapsed <= HARD_TIMEOUT_SECONDS + 0.5
assert elapsed <= 0.1 + 0.5
class TestSubmitBackground:

View File

@ -111,12 +111,12 @@ class TestWalkDay:
assert day.legs == 3
assert day.moving_minutes == pytest.approx(50)
assert day.distance_km == pytest.approx(6)
assert day.completed_at == 200.0 # a (25) + b (20) crosses 40 at b's end
assert day.completed_at == 100.0 # a (25) alone crosses the bar at its end
assert day.qualifies
assert day.message() == "Walking: 3 walk(s), 6.0 km, 50 min moving"
def test_the_same_walk_from_two_sources_counts_once(self) -> None:
copy = leg("same", 30, 100.0)
copy = leg("same", 20, 100.0)
day = walk_day([copy, dict(copy)])
assert day.legs == 1
assert not day.qualifies
@ -130,5 +130,12 @@ class TestWalkDay:
assert day.completed_at is None
def test_shortfall_says_what_is_missing(self) -> None:
text = walk_shortfall(walk_day([leg("a", 30, 1.0)]))
assert text.endswith("need 40+ min moving")
text = walk_shortfall(walk_day([leg("a", 20, 1.0)]))
assert text.endswith("need 30+ min moving")
def test_walks_share_the_one_workout_accept_bar(self) -> None:
# Same advertised-30 / accept-25 bar as every other workout type.
assert not walk_day([leg("a", 24.9, 1.0)]).qualifies
day = walk_day([leg("a", 25, 1.0)])
assert day.qualifies
assert day.completed_at == 1.0

View File

@ -53,7 +53,8 @@ def _running() -> Iterator[int]:
The bound port.
"""
server = create_server("127.0.0.1", 0)
thread = threading.Thread(target=server.serve_forever, daemon=True)
# poll_interval: shutdown() waits out one poll, 0.5 s per test by default.
thread = threading.Thread(target=server.serve_forever, args=(0.01,), daemon=True)
thread.start()
try:
yield server.server_address[1]

View File

@ -5,7 +5,7 @@ to keep every file under the 250-line cap. Both had their own near-identical
copy; they differ only in the sentinel env var and how the inner process is
addressed, so both are parameters here.
Each script runs itself twice: the outer run starts ``xvfb-run`` and re-execs,
Each script runs itself twice: the outer run starts ``Xvfb`` and re-execs,
the inner run (marked by the sentinel) does the real work against that
display. Without the sentinel the inner process would start another Xvfb
forever.
@ -24,7 +24,7 @@ _logger = logging.getLogger(__name__)
# Comfortably bigger than every size under test, so each surface is sized by
# the geometry the harness sets rather than clamped by the display.
_SCREEN_ARG = "-screen 0 1600x1200x24"
_SCREEN_ARG = ("-screen", "0", "1600x1200x24")
def reexec_under_xvfb(
@ -46,27 +46,53 @@ def reexec_under_xvfb(
script: Absolute path of the script file to run.
Returns:
The inner process's exit code, or 1 if ``xvfb-run`` is unavailable.
The inner process's exit code, or 1 if ``Xvfb`` is unavailable or
never became ready.
"""
if (module is None) == (script is None):
msg = "pass exactly one of module= or script="
raise ValueError(msg)
xvfb_run = shutil.which("xvfb-run")
if xvfb_run is None:
xvfb = shutil.which("Xvfb")
if xvfb is None:
_logger.error(
"xvfb-run not found. Install it with: sudo pacman -S --needed "
"xorg-server-xvfb"
"Xvfb not found. Install it with: sudo pacman -S --needed xorg-server-xvfb"
)
return 1
env = dict(os.environ, **{inner_env: "1"})
repo_root = Path(__file__).resolve().parent.parent
# Absolute argv, no shell.
target = ["-m", module] if module is not None else [str(script)]
return subprocess.run(
[xvfb_run, "-a", "-s", _SCREEN_ARG, sys.executable, *target],
check=False,
cwd=repo_root,
env=env,
).returncode
server, display = _start_xvfb(xvfb)
try:
if display is None:
_logger.error("Xvfb exited before it was ready to accept clients")
return 1
env = dict(os.environ, DISPLAY=display, **{inner_env: "1"})
env.pop("XAUTHORITY", None) # a throwaway server has no cookie to check
return subprocess.run(
[sys.executable, *target], check=False, cwd=repo_root, env=env
).returncode
finally:
server.terminate()
server.wait(timeout=5)
def _start_xvfb(xvfb: str) -> tuple[subprocess.Popen[bytes], str | None]:
"""Start Xvfb on a free display; return it and ``:N`` once it is ready.
``-displayfd`` makes Xvfb pick a free display and write its number only
once it accepts clients. ``xvfb-run`` instead sleeps a fixed 3 s after
starting it, which was most of this pre-commit hook's runtime.
"""
read_fd, write_fd = os.pipe()
server = subprocess.Popen(
[xvfb, "-displayfd", str(write_fd), "-nolisten", "tcp", *_SCREEN_ARG],
pass_fds=(write_fd,),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
os.close(write_fd)
with os.fdopen(read_fd) as ready:
number = ready.readline().strip()
return server, f":{number}" if number else None

View File

@ -31,22 +31,22 @@ const int kManualWorkoutBudgetPer7Days = 2;
/// Max manual workouts allowed in any rolling 30-day window.
const int kManualWorkoutBudgetPer30Days = 10;
/// The ONE duration bar every workout type answers to, in minutes. This is
/// The ONE duration bar every activity answers to, in minutes. This is
/// the ADVERTISED number — the only one that may appear in a message the user
/// reads. Mirrors `MIN_WORKOUT_DURATION_MINUTES` in the locker's
/// `_constants.py`; the two must move together.
const int kMinWorkoutDurationMinutes = 40;
const int kMinWorkoutDurationMinutes = 30;
/// The leeway that is deliberately INVISIBLE. A session is accepted at
/// [kMinWorkoutDurationMinutes] minus this, so 35 minutes passes while every
/// string still says 40. That gap is intentional: do NOT "fix" it by
/// [kMinWorkoutDurationMinutes] minus this, so 25 minutes passes while every
/// string still says 30. That gap is intentional: do NOT "fix" it by
/// advertising the real cutoff, and never interpolate
/// [kWorkoutDurationAcceptMinutes] into a user-facing string.
const int kWorkoutDurationLeewayMinutes = 5;
/// Derived so the advertised and accept bars cannot drift apart. Comparisons
/// use this; messages use [kMinWorkoutDurationMinutes]. Compare with `>=`,
/// matching the locker, so 35.0 cannot pass one side and fail the other.
/// matching the locker, so 25.0 cannot pass one side and fail the other.
const int kWorkoutDurationAcceptMinutes =
kMinWorkoutDurationMinutes - kWorkoutDurationLeewayMinutes;
@ -185,7 +185,6 @@ class ManualWorkoutDraft {
final String equipment;
}
/// Builds the persisted `workout_data` dict for a validated draft.
///
/// Byte-for-byte equivalent of the Python `build_entry`.

View File

@ -89,10 +89,13 @@ void main() {
}
});
test('the rejection message advertises 40 and never the real cutoff', () {
final error = validateManualWorkout(_draft(10));
expect(error, isNotNull);
expect(error, contains('$kMinWorkoutDurationMinutes'));
expect(error, isNot(contains('$kWorkoutDurationAcceptMinutes')));
});
test(
'the rejection message advertises the round bar and never the real cutoff',
() {
final error = validateManualWorkout(_draft(10));
expect(error, isNotNull);
expect(error, contains('$kMinWorkoutDurationMinutes'));
expect(error, isNot(contains('$kWorkoutDurationAcceptMinutes')));
},
);
}