Compare commits

..

No commits in common. "a0923ce694cb6faf4bdd6511701324ce37b3fe96" and "60d8c3361b712610d05d7c8d25aa562131cf8e83" have entirely different histories.

35 changed files with 120 additions and 3453 deletions

View File

@ -113,9 +113,8 @@ RUNNERUP_EXPORT_DIRS: tuple[str, ...] = (
# Sync (phone workout data) — Workstream C, built on the shared crdt-sync
# library. GitHub is used purely as dumb file storage via the REST Contents
# API (not a git clone), same pattern as diet_guard's cross-device sync. The
# phone app pushes to devices/<SYNC_PHONE_DEVICE_ID>/log.json; the PC reads
# every device's log and pushes its OWN manual workouts to devices/pc/log.json
# (see _manual_push) — which needs a token with contents:write, not read-only.
# phone app pushes to devices/<SYNC_PHONE_DEVICE_ID>/log.json; the PC only
# ever reads that one path, it never pushes here itself.
# ---------------------------------------------------------------------------
SYNC_REPO_OWNER: str = "kuhyx"
SYNC_REPO_NAME: str = "syncs"

View File

@ -19,44 +19,6 @@ if TYPE_CHECKING:
_logger = logging.getLogger(__name__)
def _read_logs(log_file: Path) -> dict:
"""Load ``workout_log.json`` as a dict, or ``{}`` if missing/corrupt."""
if not log_file.exists():
return {}
try:
with log_file.open() as f:
return json.load(f)
except (OSError, json.JSONDecodeError):
return {}
def write_signed_entry(
log_file: Path, date: str, workout_data: Mapping[str, object]
) -> None:
"""Write one HMAC-signed workout entry into ``log_file`` keyed by ``date``.
Shared by the live save path (today's workout) and manual-sync ingestion,
which files a synced workout under its OWN date so the weekly count places
it in the right ISO week. The log is day-keyed: one entry per date.
"""
logs = _read_logs(log_file)
entry: dict[str, object] = {
"timestamp": datetime.now(tz=timezone.utc).isoformat(),
"workout_data": workout_data,
}
signature = compute_entry_hmac(entry)
if signature is not None:
entry["hmac"] = signature
else:
_logger.warning("HMAC key unavailable — saving unsigned entry")
logs[date] = entry
try:
with log_file.open("w") as f:
json.dump(logs, f, indent=2)
except OSError as e:
_logger.warning("Could not save workout log: %s", e)
class LogMixin:
"""Handles reading and writing workout_log.json for the ScreenLocker.
@ -75,13 +37,34 @@ class LogMixin:
def _load_existing_logs(self) -> dict:
"""Load existing workout logs from file."""
return _read_logs(self.log_file)
if not self.log_file.exists():
return {}
try:
with self.log_file.open() as f:
return json.load(f)
except (OSError, json.JSONDecodeError):
return {}
def _is_scheduled_skip_today(self) -> bool:
"""Return True if today's date is listed in the scheduled skips file."""
return _compliance_state.is_scheduled_skip_today(SCHEDULED_SKIPS_FILE)
def save_workout_log(self) -> None:
"""Save today's workout data to the log file with an HMAC signature."""
"""Save workout data to log file with HMAC signature."""
logs = self._load_existing_logs()
today = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")
write_signed_entry(self.log_file, today, self.workout_data)
entry: dict[str, object] = {
"timestamp": datetime.now(tz=timezone.utc).isoformat(),
"workout_data": self.workout_data,
}
signature = compute_entry_hmac(entry)
if signature is not None:
entry["hmac"] = signature
else:
_logger.warning("HMAC key unavailable — saving unsigned entry")
logs[today] = entry
try:
with self.log_file.open("w") as f:
json.dump(logs, f, indent=2)
except OSError as e:
_logger.warning("Could not save workout log: %s", e)

View File

@ -1,141 +0,0 @@
"""Push PC-originated manual workouts to the shared sync repo.
The PC manual-workout form writes its entry into ``workout_log.json`` (day-keyed,
locally). For the two-way shared budget, the PC must ALSO publish its manual
workouts to the sync repo so the phone can see them. This module keeps a small
crdt-sync log of *PC-originated* manuals (``manual_sync_log.json``, next to
``workout_log.json``) and pushes it to ``devices/pc/log.json``.
This reverses the old "the PC only ever reads, never pushes" invariant (it had
no data of its own to contribute); manual workouts are that data. Pushing needs
a sync token with **contents:write** on the repo — a read-only token 403s, which
is swallowed (best-effort), so the local form still works offline.
"""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING
from crdt_sync import (
GitHubSyncClient,
GitHubSyncError,
Hlc,
Record,
sync_log,
)
from screen_locker._constants import (
SYNC_REPO_NAME,
SYNC_REPO_OWNER,
SYNC_TIMEOUT_SECONDS,
)
from screen_locker._manual_workout import (
MANUAL_WORKOUT_SYNC_KIND,
_today_iso,
manual_sync_record_id,
)
from screen_locker._workout_sync import _DEVICES_PREFIX, read_sync_token
if TYPE_CHECKING:
from collections.abc import Mapping
from pathlib import Path
from crdt_sync import Log
_logger = logging.getLogger(__name__)
_PC_DEVICE_ID = "pc"
_STORE_FILENAME = "manual_sync_log.json"
_PAYLOAD_FIELD = "payload"
def _store_path(log_file: Path) -> Path:
"""Return the PC manual-sync store path next to ``workout_log.json``."""
return log_file.parent / _STORE_FILENAME
def _encode_log(log: Log) -> str:
"""Serialize a crdt-sync log to JSON (record id -> record dict)."""
return json.dumps({rid: record.to_dict() for rid, record in log.items()})
def _decode_log(text: str) -> Log:
"""Parse a crdt-sync log blob back into ``{id: Record}``."""
raw = json.loads(text)
return {rid: Record.from_dict(data) for rid, data in raw.items()}
def _load_store(store_file: Path) -> dict[str, Record]:
"""Load the local PC manual store, or ``{}`` if missing/corrupt."""
if not store_file.exists():
return {}
try:
return dict(_decode_log(store_file.read_text()))
except (OSError, ValueError, KeyError, TypeError):
_logger.warning("Corrupt PC manual store at %s — ignoring", store_file)
return {}
def _max_hlc(log: dict[str, Record]) -> Hlc | None:
"""Return the greatest HLC across the store's payload fields, if any."""
hlcs = [
record.fields[_PAYLOAD_FIELD][1]
for record in log.values()
if _PAYLOAD_FIELD in record.fields
]
return max(hlcs) if hlcs else None
def record_pc_manual(log_file: Path, entry: Mapping[str, object]) -> str:
"""Record a PC-originated manual workout into the local sync store.
``entry`` is the :func:`build_entry` dict the form already produced; this
wraps it in the shared sync payload (adds ``kind`` + ``date``) under a
stable ``manual:`` id and appends it to the store with a fresh monotonic
HLC. Fast and local — the network push happens separately
(:func:`push_pc_manuals`). Returns the record id.
"""
date = _today_iso()
store_file = _store_path(log_file)
log = _load_store(store_file)
payload = {**entry, "kind": MANUAL_WORKOUT_SYNC_KIND, "date": date}
record_id = manual_sync_record_id(date, str(entry.get("start_time", "")))
hlc = Hlc.new_tick(_PC_DEVICE_ID, previous=_max_hlc(log))
log[record_id] = Record(id=record_id, fields={_PAYLOAD_FIELD: (payload, hlc)})
store_file.write_text(_encode_log(log))
return record_id
def push_pc_manuals(log_file: Path) -> None:
"""Push the PC's manual-workout store to ``devices/pc/log.json``.
Best-effort: no token, an empty store, or any sync error (notably a 403
from a read-only token that lacks ``contents:write``) is swallowed so the
local form keeps working. Runs one full sync tick, so it also retries any
manuals a previous push failed to publish.
"""
token = read_sync_token()
if token is None:
return
log = _load_store(_store_path(log_file))
if not log:
return
client = GitHubSyncClient(
SYNC_REPO_OWNER,
SYNC_REPO_NAME,
token,
timeout_seconds=SYNC_TIMEOUT_SECONDS,
)
try:
sync_log(
client=client,
device_id=_PC_DEVICE_ID,
path_prefix=_DEVICES_PREFIX,
local_log=log,
encode=_encode_log,
decode=_decode_log,
)
except GitHubSyncError as exc:
_logger.info("PC manual push skipped (%s)", exc)

View File

@ -1,162 +0,0 @@
"""Ingest phone-/PC-synced manual workouts into ``workout_log.json``.
A manual workout logged on another device (phone form, or the PC form pushed
from elsewhere) arrives via crdt-sync as a ``kind="manual_workout"`` payload
(see :func:`screen_locker._manual_workout.build_sync_payload`). This module
turns those synced payloads into ordinary signed ``manual_workout`` entries in
``workout_log.json`` so they count toward the weekly minimum.
Trust model: the PC never trusts the phone's derived fields. Every synced
manual is re-validated with the same :func:`validate_manual_workout` the local
form uses, re-built with :func:`build_entry`, and only then HMAC-signed by the
PC. A phone can therefore at most add a budget-limited, honour-system
``manual_workout`` — never a ``phone_verified`` one (the session path skips
manual records, see :mod:`screen_locker._workout_sync`).
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from screen_locker._log_mixin import _read_logs, write_signed_entry
from screen_locker._manual_workout import (
MANUAL_WORKOUT_SYNC_KIND,
SPORT_OTHER,
ManualWorkoutDraft,
build_entry,
is_budget_exhausted,
validate_manual_workout,
)
from screen_locker._weekly_check import COUNTED_WORKOUT_TYPES
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
from pathlib import Path
_logger = logging.getLogger(__name__)
# Key under which the source sync record id is stored in the ingested
# ``workout_data`` — makes re-ingestion of the same record idempotent.
_SYNC_ID_FIELD = "sync_record_id"
def _coerce_int(value: object) -> int:
"""Coerce a JSON scalar to int; raise for a non-numeric (skips the record)."""
if isinstance(value, (int, str)):
return int(value)
raise TypeError(value)
def reconstruct_draft(payload: Mapping[str, object]) -> ManualWorkoutDraft | None:
"""Rebuild a :class:`ManualWorkoutDraft` from a synced manual payload.
Returns None if a required raw field is missing or mistyped, so a malformed
record is skipped rather than crashing ingestion. Only the raw user inputs
are read back — the derived fields (``source``, ``duration_minutes``,
``type``) are recomputed by :func:`build_entry` on the PC.
"""
try:
sport = str(payload["sport"])
activity_type_other = (
str(payload.get("activity_type", "")) if sport == SPORT_OTHER else ""
)
return ManualWorkoutDraft(
sport=sport,
start_time=str(payload["start_time"]),
end_time=str(payload["end_time"]),
location_name=str(payload["location_name"]),
transport_method=str(payload["transport_method"]),
cost=str(payload["cost"]),
rpe=_coerce_int(payload["rpe"]),
went_well=str(payload["went_well"]),
to_improve=str(payload["to_improve"]),
overall_feeling=str(payload["overall_feeling"]),
reservation_phone=str(payload.get("reservation_phone", "")),
techniques_practiced=str(payload.get("techniques_practiced", "")),
warm_up_minutes=str(payload.get("warm_up_minutes", "")),
pain_or_injury=str(payload.get("pain_or_injury", "none")),
matches_won=_coerce_int(payload.get("matches_won", 0)),
matches_lost=_coerce_int(payload.get("matches_lost", 0)),
sets_won=_coerce_int(payload.get("sets_won", 0)),
sets_lost=_coerce_int(payload.get("sets_lost", 0)),
racket=str(payload.get("racket", "")),
balls=str(payload.get("balls", "")),
activity_type_other=activity_type_other,
activity_details=str(payload.get("activity_details", "")),
equipment=str(payload.get("equipment", "")),
)
except (KeyError, TypeError, ValueError):
return None
def _already_ingested(logs: dict, record_id: str) -> bool:
"""True if a log entry already carries this sync record id."""
for entry in logs.values():
if not isinstance(entry, dict):
continue
workout_data = entry.get("workout_data", {})
if (
isinstance(workout_data, dict)
and workout_data.get(_SYNC_ID_FIELD) == record_id
):
return True
return False
def _date_has_counted_workout(logs: dict, date: str) -> bool:
"""True if ``date`` already holds a workout that counts (day-keyed log)."""
entry = logs.get(date)
if not isinstance(entry, dict):
return False
workout_data = entry.get("workout_data", {})
return (
isinstance(workout_data, dict)
and workout_data.get("type") in COUNTED_WORKOUT_TYPES
)
def ingest_manual_records(
log_file: Path,
records: Iterable[tuple[str, Mapping[str, object]]],
*,
today: str | None = None,
) -> list[str]:
"""Ingest synced manual workouts into ``workout_log.json``.
For each ``(record_id, payload)`` tagged ``kind="manual_workout"``:
reconstruct + re-validate the draft on the PC, enforce the rate budget, then
HMAC-sign and write it under its own ``date``. Idempotent (dedup by
``record_id``) and non-destructive: it never overwrites an existing counted
entry for a day (the log is day-keyed — a real workout already credits it).
Returns the record ids actually ingested.
"""
ingested: list[str] = []
for record_id, payload in records:
if payload.get("kind") != MANUAL_WORKOUT_SYNC_KIND:
continue
date = payload.get("date")
if not isinstance(date, str):
_logger.warning("Manual record %s has no date — skipped", record_id)
continue
logs = _read_logs(log_file)
if _already_ingested(logs, record_id):
continue
if _date_has_counted_workout(logs, date):
continue
draft = reconstruct_draft(payload)
if draft is None:
_logger.warning("Manual record %s is malformed — skipped", record_id)
continue
error = validate_manual_workout(draft)
if error is not None:
_logger.warning("Manual record %s invalid: %s", record_id, error)
continue
if is_budget_exhausted(log_file, today=today):
_logger.info("Manual-workout budget exhausted — %s not ingested", record_id)
continue
entry = build_entry(draft)
entry[_SYNC_ID_FIELD] = record_id
write_signed_entry(log_file, date, entry)
ingested.append(record_id)
return ingested

View File

@ -306,39 +306,3 @@ def build_entry(draft: ManualWorkoutDraft) -> dict[str, object]:
}
)
return entry
# ── Cross-device sync wire format ─────────────────────────────────────────────
# The value of the record ``kind`` discriminator equals ``MANUAL_WORKOUT_TYPE``
# by design: on the wire a manual record is tagged ``kind="manual_workout"`` and
# its payload also carries ``type="manual_workout"``. A StrongLifts session
# payload has no ``kind`` field, so an ingesting PC routes on ``kind`` first and
# a manual record can never be mistaken for (or stamped as) a verified session.
MANUAL_WORKOUT_SYNC_KIND = MANUAL_WORKOUT_TYPE
def manual_sync_record_id(date: str, start_time: str) -> str:
"""Return the stable crdt_sync record id for a manual workout.
Prefixed ``manual:`` so it never collides with the bare-ISO session ids the
phone app writes into the same device log. Derived only from
``(date, start_time)`` so re-syncing the same workout is idempotent — this
id must never be re-minted for a given workout.
"""
return f"manual:{date}T{start_time.strip()}"
def build_sync_payload(draft: ManualWorkoutDraft, date: str) -> dict[str, object]:
"""Build the cross-device sync payload for a manual workout.
This is the wire contract shared with the phone app: the same fields as
:func:`build_entry` (what lands in ``workout_log.json``), plus a ``kind``
discriminator and the workout's own ``date``. ``workout_log.json`` is
day-keyed on the PC, but the synced payload must carry its date so the
shared budget can be windowed and the entry filed in the right ISO week on
ingest.
"""
payload = build_entry(draft)
payload["kind"] = MANUAL_WORKOUT_SYNC_KIND
payload["date"] = date
return payload

View File

@ -24,7 +24,6 @@ from screen_locker._constants import (
MANUAL_WORKOUT_DESCRIPTION_MIN_CHARS,
MANUAL_WORKOUT_REFLECTION_MIN_CHARS,
)
from screen_locker._manual_push import record_pc_manual
from screen_locker._manual_workout_widgets import ManualWorkoutFormWidgetsMixin
_logger = logging.getLogger(__name__)
@ -297,7 +296,4 @@ class ManualWorkoutDialogMixin(ManualWorkoutFormWidgetsMixin):
self._mw_error_label.config(text=error)
return
entry = _manual_workout.build_entry(draft)
# Record the manual for cross-device sync (published on the next lock
# startup). Local + best-effort — never blocks saving/unlocking.
record_pc_manual(self.log_file, entry)
self._on_manual_workout_saved(entry)

View File

@ -1,11 +1,11 @@
"""Pulls phone/other-device workouts via crdt-sync's GitHub transport.
"""Pulls the phone's last-synced workout via crdt-sync's GitHub transport.
GitHub is used purely as dumb file storage (see ``crdt_sync``'s own docs) --
the phone app pushes its completed-workout log to a private repo; this module
reads the session log and every device's manual-workout records. (The PC does
push its OWN manual workouts, but via :mod:`screen_locker._manual_push`, not
here.) Sync is optional: an unconfigured token is a normal, expected state,
not an error -- unlike diet_guard, where sync is core to the app.
the phone app pushes its completed-workout log to a private repo; this
module only ever reads it, it never pushes here itself (the PC has no
workout data of its own to contribute). Sync is optional: an unconfigured
token is a normal, expected state, not an error -- unlike diet_guard, where
sync is core to the app.
"""
from __future__ import annotations
@ -13,7 +13,7 @@ from __future__ import annotations
import json
import logging
from crdt_sync import GitHubSyncClient, GitHubSyncError, Hlc, Record
from crdt_sync import GitHubSyncClient, GitHubSyncError, Record
from screen_locker._constants import (
SYNC_PHONE_DEVICE_ID,
@ -22,20 +22,13 @@ from screen_locker._constants import (
SYNC_TIMEOUT_SECONDS,
SYNC_TOKEN_FILE,
)
from screen_locker._manual_workout import MANUAL_WORKOUT_SYNC_KIND
_logger = logging.getLogger(__name__)
_DEVICES_PREFIX = "screen-locker-sync/devices"
_LOG_PATH = f"{_DEVICES_PREFIX}/{SYNC_PHONE_DEVICE_ID}/log.json"
_LOG_PATH = f"screen-locker-sync/devices/{SYNC_PHONE_DEVICE_ID}/log.json"
_PAYLOAD_FIELD = "payload"
def _is_manual_payload(payload: object) -> bool:
"""True if a decoded sync payload is a manual-workout record."""
return isinstance(payload, dict) and payload.get("kind") == MANUAL_WORKOUT_SYNC_KIND
def read_sync_token() -> str | None:
"""Return the saved sync PAT, or None if sync isn't configured.
@ -66,12 +59,7 @@ def _latest_payload(log_json: str) -> dict | None:
raise TypeError(msg)
records = [Record.from_dict(data) for data in raw.values()]
candidates = [
record
for record in records
if _PAYLOAD_FIELD in record.fields
and not _is_manual_payload(record.fields[_PAYLOAD_FIELD][0])
]
candidates = [record for record in records if _PAYLOAD_FIELD in record.fields]
if not candidates:
return None
latest = max(candidates, key=lambda record: record.fields[_PAYLOAD_FIELD][1])
@ -118,74 +106,3 @@ def pull_synced_workout() -> tuple[dict | None, str | None]:
return None, f"corrupt sync data: {exc}"
return payload, None
def _manual_records(log_json: str) -> dict[str, tuple[dict, Hlc]]:
"""Return ``{record_id: (payload, hlc)}`` for manual records in a log blob.
Raises the same decode errors as :func:`_latest_payload`; callers treat a
corrupt device log as "no manual records from that device".
"""
raw = json.loads(log_json)
if not isinstance(raw, dict):
msg = f"top-level sync payload is not a JSON object: {raw!r}"
raise TypeError(msg)
result: dict[str, tuple[dict, Hlc]] = {}
for data in raw.values():
record = Record.from_dict(data)
field = record.fields.get(_PAYLOAD_FIELD)
if field is None:
continue
payload, hlc = field
if _is_manual_payload(payload):
result[record.id] = (payload, hlc)
return result
def pull_all_manual_records() -> list[tuple[str, dict]]:
"""Return all synced manual-workout records across every device log.
Merges every ``devices/<device>/log.json`` under the sync prefix (phone,
pc, …), keeping the highest-HLC copy of each record id — records are
id-stable, so the same workout mirrored into two device logs dedups to one.
Best-effort: an unconfigured token, an unreachable repo, or a corrupt device
log yields fewer/no records rather than raising — manual sync, like session
sync, is optional.
"""
token = read_sync_token()
if token is None:
return []
client = GitHubSyncClient(
SYNC_REPO_OWNER,
SYNC_REPO_NAME,
token,
timeout_seconds=SYNC_TIMEOUT_SECONDS,
)
try:
devices = client.list_directory(_DEVICES_PREFIX)
except GitHubSyncError as exc:
_logger.info("Manual sync unavailable (%s)", exc)
return []
merged: dict[str, tuple[dict, Hlc]] = {}
for device in devices:
path = f"{_DEVICES_PREFIX}/{device}/log.json"
try:
text = client.get_file_text(path)
except GitHubSyncError as exc:
_logger.info("Skipping device log %s (%s)", path, exc)
continue
if text is None:
continue
try:
records = _manual_records(text)
except (ValueError, KeyError, TypeError) as exc:
_logger.warning("Corrupt sync data at %s: %s", path, exc)
continue
for rid, (payload, hlc) in records.items():
existing = merged.get(rid)
if existing is None or existing[1] < hlc:
merged[rid] = (payload, hlc)
return [(rid, payload) for rid, (payload, _hlc) in merged.items()]

View File

@ -40,8 +40,6 @@ from screen_locker._extra_benefits import (
)
from screen_locker._heat_skip import HeatSkipMixin
from screen_locker._log_mixin import LogMixin
from screen_locker._manual_push import push_pc_manuals
from screen_locker._manual_sync import ingest_manual_records
from screen_locker._manual_workout_dialog import ManualWorkoutDialogMixin
from screen_locker._phone_verification import PhoneVerificationMixin
from screen_locker._runnerup_verification import RunnerUpVerificationMixin
@ -60,7 +58,6 @@ from screen_locker._weekly_check import (
)
from screen_locker._window_setup import WindowSetupMixin
from screen_locker._workout_credit import WorkoutCreditMixin
from screen_locker._workout_sync import pull_all_manual_records
if TYPE_CHECKING:
from collections.abc import Callable
@ -187,10 +184,6 @@ class ScreenLocker(
SHUTDOWN_BASE_FILE, self, sick_day_state_file=SICK_DAY_STATE_FILE
):
self._apply_weekly_shutdown_bonus()
# Ingest any manual workouts synced from the phone (or another device)
# before the early-exit checks, so a manual logged off-app still counts
# toward today's/this week's minimum.
self._ingest_synced_manual_workouts()
# Auto-fill any RunnerUp workouts from earlier in the current ISO week
# before any early-exit check, so gaps are closed regardless of today's
# logged state (early_bird, sick_day, etc.).
@ -217,13 +210,6 @@ class ScreenLocker(
# shutdown-time-only reward (see _apply_weekly_shutdown_bonus).
self._check_heat_skip_exit()
def _ingest_synced_manual_workouts(self) -> None:
"""Sync manual workouts: publish this PC's, ingest everyone else's."""
push_pc_manuals(self.log_file)
ingested = ingest_manual_records(self.log_file, pull_all_manual_records())
for record_id in ingested:
_logger.info("Ingested synced manual workout: %s", record_id)
def _auto_fill_week_runnerup_bonus(self) -> None:
"""Auto-fill missed RunnerUp workouts and award any earned bonus."""
prev_count = count_weekly_workouts(self.log_file)

View File

@ -1,131 +0,0 @@
"""Tests for pushing PC-originated manual workouts to the sync repo."""
# pylint: disable=protected-access
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
from crdt_sync import GitHubSyncError, Hlc, Record
from screen_locker import _manual_push, _workout_sync
from screen_locker._manual_push import (
_decode_log,
_encode_log,
_load_store,
_max_hlc,
_store_path,
push_pc_manuals,
record_pc_manual,
)
if TYPE_CHECKING:
from pathlib import Path
_ENTRY = {
"type": "manual_workout",
"source": "table tennis at Solec",
"sport": "table_tennis",
"start_time": "18:00",
"end_time": "19:30",
"location_name": "Solec",
"rpe": 6,
}
def _hlc(ms: int) -> Hlc:
return Hlc(wall_time_ms=ms, counter=0, node_id="pc")
def _record(record_id: str, ms: int) -> Record:
return Record(id=record_id, fields={"payload": ({"x": 1}, _hlc(ms))})
class TestEncodeDecodeRoundTrip:
def test_round_trips_a_log(self) -> None:
log = {"manual:a": _record("manual:a", 100)}
assert _decode_log(_encode_log(log)) == log
class TestLoadStore:
def test_missing_file_returns_empty(self, tmp_path: Path) -> None:
assert _load_store(tmp_path / "nope.json") == {}
def test_corrupt_file_returns_empty(self, tmp_path: Path) -> None:
store = tmp_path / "manual_sync_log.json"
store.write_text("{not json")
assert _load_store(store) == {}
def test_valid_file_round_trips(self, tmp_path: Path) -> None:
store = tmp_path / "manual_sync_log.json"
log = {"manual:a": _record("manual:a", 100)}
store.write_text(_encode_log(log))
assert _load_store(store) == log
class TestMaxHlc:
def test_empty_returns_none(self) -> None:
assert _max_hlc({}) is None
def test_returns_greatest_hlc(self) -> None:
log = {"a": _record("a", 100), "b": _record("b", 300)}
assert _max_hlc(log) == _hlc(300)
def test_skips_records_without_a_payload_field(self) -> None:
no_payload = Record(id="a", fields={"other": (1, _hlc(1))})
assert _max_hlc({"a": no_payload}) is None
class TestRecordPcManual:
def test_writes_a_manual_record(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
record_id = record_pc_manual(log_file, _ENTRY)
assert record_id.startswith("manual:")
assert record_id.endswith("T18:00")
store = _load_store(_store_path(log_file))
payload, _clock = store[record_id].fields["payload"]
assert payload["kind"] == "manual_workout"
assert "date" in payload
def test_second_record_has_a_greater_clock(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
record_pc_manual(log_file, {**_ENTRY, "start_time": "18:00"})
record_pc_manual(log_file, {**_ENTRY, "start_time": "20:00"})
store = _load_store(_store_path(log_file))
clocks = sorted(rec.fields["payload"][1] for rec in store.values())
assert clocks[0] < clocks[1]
class TestPushPcManuals:
def test_no_token_is_a_no_op(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
record_pc_manual(log_file, _ENTRY)
with patch.object(_manual_push, "read_sync_token", return_value=None):
push_pc_manuals(log_file) # no exception, no client
def test_empty_store_is_a_no_op(self, tmp_path: Path) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
log_file = tmp_path / "workout_log.json"
with patch.object(_manual_push, "GitHubSyncClient") as client_cls:
push_pc_manuals(log_file)
client_cls.assert_not_called()
def test_pushes_when_token_and_store_present(self, tmp_path: Path) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
log_file = tmp_path / "workout_log.json"
record_pc_manual(log_file, _ENTRY)
client = MagicMock()
client.list_directory.return_value = []
with patch.object(_manual_push, "GitHubSyncClient", return_value=client):
push_pc_manuals(log_file)
client.put_file_text.assert_called_once()
def test_swallows_a_sync_error(self, tmp_path: Path) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
log_file = tmp_path / "workout_log.json"
record_pc_manual(log_file, _ENTRY)
client = MagicMock()
client.list_directory.return_value = []
client.put_file_text.side_effect = GitHubSyncError("403")
with patch.object(_manual_push, "GitHubSyncClient", return_value=client):
push_pc_manuals(log_file) # swallowed, no raise

View File

@ -1,204 +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._manual_sync import (
ingest_manual_records,
reconstruct_draft,
)
from screen_locker._manual_workout import (
SPORT_OTHER,
SPORT_TABLE_TENNIS,
ManualWorkoutDraft,
build_sync_payload,
manual_sync_record_id,
)
from screen_locker._weekly_check import count_weekly_workouts
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",
)
def _manual_record(draft: ManualWorkoutDraft, date: str = _DATE) -> tuple[str, dict]:
"""Build a (record_id, payload) pair as it would arrive from sync."""
payload = build_sync_payload(draft, date)
return manual_sync_record_id(date, draft.start_time), payload
class TestReconstructDraft:
def test_rebuilds_a_table_tennis_draft(self) -> None:
_, payload = _manual_record(_TT_DRAFT)
draft = reconstruct_draft(payload)
assert draft is not None
assert draft.sport == SPORT_TABLE_TENNIS
assert draft.racket == "Butterfly"
def test_rebuilds_an_other_sport_draft(self) -> None:
_, payload = _manual_record(_OTHER_DRAFT)
draft = reconstruct_draft(payload)
assert draft is not None
assert draft.activity_type_other == "squash"
def test_returns_none_when_a_required_field_is_missing(self) -> None:
_, payload = _manual_record(_TT_DRAFT)
del payload["start_time"]
assert reconstruct_draft(payload) is None
def test_returns_none_on_a_mistyped_field(self) -> None:
_, payload = _manual_record(_TT_DRAFT)
payload["rpe"] = None
assert reconstruct_draft(payload) is None
class TestIngestManualRecords:
def test_ingests_a_valid_record(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
record = _manual_record(_TT_DRAFT)
ingested = ingest_manual_records(log_file, [record], today=_DATE)
assert ingested == [record[0]]
stored = json.loads(log_file.read_text())
workout = stored[_DATE]["workout_data"]
assert workout["type"] == "manual_workout"
assert workout["sync_record_id"] == record[0]
assert count_weekly_workouts(log_file, today=_dt(_DATE)) == 1
def test_is_idempotent(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
record = _manual_record(_TT_DRAFT)
ingest_manual_records(log_file, [record], today=_DATE)
again = ingest_manual_records(log_file, [record], today=_DATE)
assert again == []
def test_skips_a_non_manual_payload(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
assert (
ingest_manual_records(log_file, [("s", {"succeeded": True})], today=_DATE)
== []
)
def test_skips_a_record_without_a_date(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
_, payload = _manual_record(_TT_DRAFT)
del payload["date"]
assert ingest_manual_records(log_file, [("m", payload)], today=_DATE) == []
def test_does_not_clobber_an_existing_counted_day(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)
assert ingest_manual_records(log_file, [record], today=_DATE) == []
# The original phone_verified entry is untouched.
stored = json.loads(log_file.read_text())
assert stored[_DATE]["workout_data"]["type"] == "phone_verified"
def test_skips_a_malformed_payload(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
_, payload = _manual_record(_TT_DRAFT)
payload["rpe"] = None # reconstruct_draft -> None
assert ingest_manual_records(log_file, [("m", payload)], today=_DATE) == []
def test_skips_an_invalid_draft(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
_, payload = _manual_record(_TT_DRAFT)
payload["location_name"] = " " # fails validate_manual_workout
assert ingest_manual_records(log_file, [("m", payload)], today=_DATE) == []
def test_skips_when_budget_exhausted(self, tmp_path: Path) -> None:
log_file = tmp_path / "workout_log.json"
record = _manual_record(_TT_DRAFT)
with patch.object(_manual_sync, "is_budget_exhausted", return_value=True):
assert ingest_manual_records(log_file, [record], today=_DATE) == []
def test_writes_unsigned_entry_when_hmac_key_unavailable(
self, tmp_path: Path
) -> None:
log_file = tmp_path / "workout_log.json"
record = _manual_record(_TT_DRAFT)
with patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None):
ingest_manual_records(log_file, [record], today=_DATE)
stored = json.loads(log_file.read_text())
assert "hmac" not in stored[_DATE]
class TestIngestHelpers:
def test_already_ingested_ignores_non_dict_entries(self) -> None:
logs = {"a": "not-a-dict", "b": {"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_date_has_counted_workout_variants(self) -> None:
logs = {
"d1": {"workout_data": {"type": "manual_workout"}},
"d2": {"workout_data": {"type": "nope"}},
"d3": "not-a-dict",
}
assert _manual_sync._date_has_counted_workout(logs, "d1") is True
assert _manual_sync._date_has_counted_workout(logs, "d2") is False
assert _manual_sync._date_has_counted_workout(logs, "d3") is False
assert _manual_sync._date_has_counted_workout(logs, "missing") is False
class TestReadLogs:
def test_missing_file_returns_empty(self, tmp_path: Path) -> None:
from screen_locker._log_mixin import _read_logs
assert _read_logs(tmp_path / "nope.json") == {}
def test_corrupt_file_returns_empty(self, tmp_path: Path) -> None:
from screen_locker._log_mixin import _read_logs
log_file = tmp_path / "workout_log.json"
log_file.write_text("{not valid json")
assert _read_logs(log_file) == {}
def _dt(date: str) -> object:
from datetime import datetime, timezone
return datetime.strptime(date, "%Y-%m-%d").replace(tzinfo=timezone.utc)

View File

@ -22,10 +22,8 @@ from screen_locker._manual_workout import (
ManualWorkoutDraft,
budget_summary,
build_entry,
build_sync_payload,
count_in_window,
is_budget_exhausted,
manual_sync_record_id,
validate_manual_workout,
)
@ -296,83 +294,3 @@ class TestBuildEntry:
def test_pain_or_injury_defaults_to_none(self) -> None:
entry = build_entry(_tt_draft())
assert entry["pain_or_injury"] == "none"
# The canonical manual-workout sync payload. This literal is the cross-language
# wire contract shared with the Flutter workout_app: an IDENTICAL literal lives
# in the Dart test suite (manual_workout model test). Neither side's own
# round-trip test can catch a key-name/format drift from the other (e.g.
# went_well vs wentWell, duration_minutes formatting) — only this shared literal
# on both sides does. If you change a field here, change it there too.
_WIRE_DATE = "2026-07-13"
_WIRE_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",
reservation_phone="600100200",
techniques_practiced="topspin serve",
warm_up_minutes="10",
pain_or_injury="none",
matches_won=3,
matches_lost=1,
sets_won=7,
sets_lost=4,
racket="Butterfly",
balls="Nittaku 3-star",
)
_WIRE_PAYLOAD: dict[str, object] = {
"type": "manual_workout",
"source": "table tennis at Solec",
"sport": "table_tennis",
"activity_type": "table tennis",
"start_time": "18:00",
"end_time": "19:30",
"duration_minutes": "90.0",
"location_name": "Solec",
"transport_method": "bike",
"cost": "40 PLN",
"reservation_phone": "600100200",
"rpe": 6,
"techniques_practiced": "topspin serve",
"warm_up_minutes": "10",
"pain_or_injury": "none",
"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",
"kind": "manual_workout",
"date": "2026-07-13",
}
class TestSyncWireFormat:
"""Cross-language wire-format contract for the manual-workout sync payload."""
def test_build_sync_payload_matches_fixture(self) -> None:
assert build_sync_payload(_WIRE_DRAFT, _WIRE_DATE) == _WIRE_PAYLOAD
def test_sync_payload_is_json_serializable(self) -> None:
# The Dart side round-trips the same literal through JSON; guard that our
# payload contains only JSON-native types (no stray dataclass/objects).
restored = json.loads(json.dumps(build_sync_payload(_WIRE_DRAFT, _WIRE_DATE)))
assert restored == _WIRE_PAYLOAD
def test_record_id_is_stable_and_prefixed(self) -> None:
assert manual_sync_record_id(_WIRE_DATE, "18:00") == "manual:2026-07-13T18:00"
def test_kind_discriminator_present_and_typed(self) -> None:
payload = build_sync_payload(_WIRE_DRAFT, _WIRE_DATE)
# Absent-kind means a StrongLifts session; a manual must be tagged.
assert payload["kind"] == "manual_workout"

View File

@ -180,40 +180,3 @@ class TestUnlockScreenExtras:
patch("screen_locker._log_mixin.compute_entry_hmac", return_value=None),
):
locker.unlock_screen()
class TestIngestSyncedManualWorkouts:
"""Tests for _ingest_synced_manual_workouts (manual-sync wiring)."""
def test_logs_each_ingested_record(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker.screen_lock.pull_all_manual_records",
return_value=[("manual:x", {})],
),
patch(
"screen_locker.screen_lock.ingest_manual_records",
return_value=["manual:x"],
) as ingest,
):
locker._ingest_synced_manual_workouts()
ingest.assert_called_once()
def test_no_records_ingests_nothing(
self, mock_tk: MagicMock, mock_sys_exit: MagicMock, tmp_path: Path
) -> None:
locker = create_locker(mock_tk, tmp_path)
with (
patch(
"screen_locker.screen_lock.pull_all_manual_records",
return_value=[],
),
patch(
"screen_locker.screen_lock.ingest_manual_records",
return_value=[],
),
):
locker._ingest_synced_manual_workouts()

View File

@ -118,177 +118,3 @@ class TestPullSyncedWorkout:
assert data is None
assert error is not None
assert "corrupt sync data" in error
def _manual_payload(**extra: object) -> dict:
payload = {"kind": "manual_workout", "date": "2026-07-13"}
payload.update(extra)
return payload
def _manual_record_dict(
record_id: str, payload: dict, *, wall_time_ms: int = 1000
) -> dict:
hlc = Hlc(wall_time_ms=wall_time_ms, counter=0, node_id="phone")
return Record(id=record_id, fields={"payload": (payload, hlc)}).to_dict()
class TestLatestPayloadSkipsManual:
def test_manual_only_log_yields_no_session(self) -> None:
log = {"m": _manual_record_dict("manual:1", _manual_payload())}
assert _workout_sync._latest_payload(json.dumps(log)) is None
def test_returns_session_even_when_a_later_manual_exists(self) -> None:
log = {
"s": _record_json({"succeeded": True}, wall_time_ms=100),
"m": _manual_record_dict("manual:1", _manual_payload(), wall_time_ms=999),
}
assert _workout_sync._latest_payload(json.dumps(log)) == {"succeeded": True}
class TestIsManualPayload:
def test_true_for_manual_kind(self) -> None:
assert _workout_sync._is_manual_payload({"kind": "manual_workout"}) is True
def test_false_for_session_or_non_dict(self) -> None:
assert _workout_sync._is_manual_payload({"succeeded": True}) is False
assert _workout_sync._is_manual_payload("not-a-dict") is False
class TestManualRecords:
def test_returns_only_manual_records(self) -> None:
log = {
"s": _record_json({"succeeded": True}),
"m": _manual_record_dict("manual:1", _manual_payload()),
}
result = _workout_sync._manual_records(json.dumps(log))
assert list(result) == ["manual:1"]
def test_skips_records_without_a_payload_field(self) -> None:
no_payload = Record(
id="a",
fields={"other": (1, Hlc(wall_time_ms=1, counter=0, node_id="phone"))},
)
log = {"a": no_payload.to_dict()}
assert _workout_sync._manual_records(json.dumps(log)) == {}
def test_raises_type_error_when_top_level_is_not_an_object(self) -> None:
with pytest.raises(TypeError, match="not a JSON object"):
_workout_sync._manual_records(json.dumps([1, 2, 3]))
def _multi_device_client(device_logs: dict[str, object]) -> MagicMock:
client = MagicMock()
client.list_directory.return_value = list(device_logs)
def _get(path: str) -> object:
device = path.split("/")[-2]
value = device_logs[device]
if isinstance(value, Exception):
raise value
return value
client.get_file_text.side_effect = _get
return client
class TestPullAllManualRecords:
def test_returns_empty_when_no_token(self) -> None:
assert _workout_sync.pull_all_manual_records() == []
def test_returns_empty_when_listing_fails(self) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = MagicMock()
client.list_directory.side_effect = GitHubSyncError("offline")
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
assert _workout_sync.pull_all_manual_records() == []
def test_merges_manual_records_across_devices(self) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client(
{
"phone": json.dumps(
{"a": _manual_record_dict("manual:a", _manual_payload())}
),
"pc": json.dumps(
{"b": _manual_record_dict("manual:b", _manual_payload())}
),
}
)
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert sorted(rid for rid, _ in result) == ["manual:a", "manual:b"]
def test_skips_missing_and_corrupt_device_logs(self) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client(
{
"phone": json.dumps(
{"a": _manual_record_dict("manual:a", _manual_payload())}
),
"gone": GitHubSyncError("404"),
"empty": None,
"corrupt": "{not json",
}
)
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert [rid for rid, _ in result] == ["manual:a"]
def test_dedups_same_id_keeping_highest_clock(self) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client(
{
"phone": json.dumps(
{
"a": _manual_record_dict(
"manual:a",
_manual_payload(cost="OLD"),
wall_time_ms=100,
)
}
),
"pc": json.dumps(
{
"a": _manual_record_dict(
"manual:a",
_manual_payload(cost="NEW"),
wall_time_ms=200,
)
}
),
}
)
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert len(result) == 1
assert result[0][1]["cost"] == "NEW"
def test_ignores_a_lower_clock_duplicate_seen_later(self) -> None:
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
client = _multi_device_client(
{
"phone": json.dumps(
{
"a": _manual_record_dict(
"manual:a",
_manual_payload(cost="NEW"),
wall_time_ms=200,
)
}
),
"pc": json.dumps(
{
"a": _manual_record_dict(
"manual:a",
_manual_payload(cost="OLD"),
wall_time_ms=100,
)
}
),
}
)
with patch.object(_workout_sync, "GitHubSyncClient", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert len(result) == 1
assert result[0][1]["cost"] == "NEW"

View File

@ -6,10 +6,6 @@ import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/http_server_service.dart';
import 'package:workout_app/services/storage_service.dart';
// coverage:ignore-start
// App bootstrap: permission request, DB init, and a real listening socket —
// platform-channel work that can't run on the CI test host. The pieces it wires
// up are unit-tested individually; the entry point itself is not.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await BackupService.instance.requestStoragePermission();
@ -18,7 +14,6 @@ void main() async {
await HttpServerService.instance.start();
runApp(const WorkoutApp());
}
// coverage:ignore-end
/// Root widget that bootstraps the app with Material 3 dark theming.
///

View File

@ -1,378 +0,0 @@
/// Manual (off-app) workout model, validation, and sync-record building.
///
/// Mirrors the Python `screen_locker._manual_workout` module
/// (`ManualWorkoutDraft`, `validate_manual_workout`, `build_entry` /
/// `build_sync_payload`, `manual_sync_record_id`). The payload wire format is
/// pinned by a cross-language fixture shared with the Python side
/// (`test/models/manual_workout_test.dart` and its twin
/// `test_manual_workout.py::TestSyncWireFormat`) — keep the two in lockstep.
library;
import 'package:crdt_sync/crdt_sync.dart';
// ── Shared constants ─────────────────────────────────────────────────────────
// Hand-maintained mirror of the Python source of truth in
// `screen_locker/_constants.py` (the `MANUAL_WORKOUT_*` values); the two
// languages can't share a file, so the cross-language payload fixture (see the
// model test and its Python twin) is the tripwire that catches drift.
/// Max manual workouts allowed in any rolling 7-day window.
const int kManualWorkoutBudgetPer7Days = 2;
/// Max manual workouts allowed in any rolling 30-day window.
const int kManualWorkoutBudgetPer30Days = 5;
/// Minimum session length, in minutes, for a manual workout to count.
const int kManualWorkoutMinDurationMinutes = 20;
/// Minimum characters for the "other sport" activity description.
const int kManualWorkoutDescriptionMinChars = 40;
/// Minimum characters required in each reflection field.
const int kManualWorkoutReflectionMinChars = 20;
/// Lowest valid RPE (rate of perceived exertion).
const int kManualWorkoutRpeMin = 1;
/// Highest valid RPE (rate of perceived exertion).
const int kManualWorkoutRpeMax = 10;
/// Record `kind` discriminator marking a manual-workout sync record.
///
/// A StrongLifts session payload has no `kind`; the ingesting PC routes on this
/// value before any session logic, so a manual can never be stamped verified.
const String kManualWorkoutSyncKind = 'manual_workout';
/// Internal sport code for table tennis (structured score fields).
const String kSportTableTennis = 'table_tennis';
/// Internal sport code for any other sport (free-text activity fields).
const String kSportOther = 'other';
/// The sport codes a manual workout may use.
const List<String> kSportChoices = [kSportTableTennis, kSportOther];
/// Human labels for the sport codes, in menu order.
const Map<String, String> kSportLabels = {
kSportTableTennis: 'Table tennis',
kSportOther: 'Other',
};
/// User-supplied evidence fields for a manual (unverified) workout.
///
/// Fields shared by every sport come first; the sport-specific groups follow —
/// only the group matching [sport] is validated/persisted.
class ManualWorkoutDraft {
/// Creates a manual-workout draft.
const ManualWorkoutDraft({
required this.sport,
required this.startTime,
required this.endTime,
required this.locationName,
required this.transportMethod,
required this.cost,
required this.rpe,
required this.wentWell,
required this.toImprove,
required this.overallFeeling,
this.reservationPhone = '',
this.techniquesPracticed = '',
this.warmUpMinutes = '',
this.painOrInjury = 'none',
this.matchesWon = 0,
this.matchesLost = 0,
this.setsWon = 0,
this.setsLost = 0,
this.racket = '',
this.balls = '',
this.activityTypeOther = '',
this.activityDetails = '',
this.equipment = '',
});
/// Sport code (see [kSportChoices]).
final String sport;
/// Start time as `HH:MM`.
final String startTime;
/// End time as `HH:MM`.
final String endTime;
/// Where the session happened.
final String locationName;
/// How the user travelled there.
final String transportMethod;
/// Session cost (free text, e.g. `40 PLN`).
final String cost;
/// Rate of perceived exertion (1-10).
final int rpe;
/// Reflection: what went well.
final String wentWell;
/// Reflection: what to improve.
final String toImprove;
/// Reflection: overall feeling.
final String overallFeeling;
/// Optional reservation phone number.
final String reservationPhone;
/// Optional techniques/focus areas practised.
final String techniquesPracticed;
/// Optional warm-up duration (free text).
final String warmUpMinutes;
/// Pain or injury notes (defaults to `none`).
final String painOrInjury;
/// Table tennis: matches won.
final int matchesWon;
/// Table tennis: matches lost.
final int matchesLost;
/// Table tennis: sets won.
final int setsWon;
/// Table tennis: sets lost.
final int setsLost;
/// Table tennis: racket used.
final String racket;
/// Table tennis: balls used.
final String balls;
/// Other sport: what activity it was.
final String activityTypeOther;
/// Other sport: description of what was done.
final String activityDetails;
/// Other sport: equipment used.
final String equipment;
}
int? _parseHhmm(String value) {
final match = RegExp(r'^(\d{1,2}):(\d{2})$').firstMatch(value.trim());
if (match == null) return null;
final hours = int.parse(match.group(1)!);
final minutes = int.parse(match.group(2)!);
if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null;
return hours * 60 + minutes;
}
/// Minutes between start and end, or null if unparsable / not end-after-start.
double? durationMinutes(ManualWorkoutDraft draft) {
final start = _parseHhmm(draft.startTime);
final end = _parseHhmm(draft.endTime);
if (start == null || end == null || end <= start) return null;
return (end - start).toDouble();
}
/// Returns an error message if [draft] is invalid, else null.
///
/// Ports `validate_manual_workout`: required fields, HH:MM with end after
/// start, minimum duration, RPE range, per-sport rules, and reflection length.
String? validateManualWorkout(ManualWorkoutDraft draft) {
if (!kSportChoices.contains(draft.sport)) return 'Please choose a sport';
final required = <String, String>{
'Start time': draft.startTime,
'End time': draft.endTime,
'Location name': draft.locationName,
'Transport method': draft.transportMethod,
'Cost': draft.cost,
};
for (final entry in required.entries) {
if (entry.value.trim().isEmpty) return '${entry.key} is required';
}
final duration = durationMinutes(draft);
if (duration == null) {
return 'Start/end time must be valid HH:MM, with end after start';
}
if (duration < kManualWorkoutMinDurationMinutes) {
return 'Session must be at least $kManualWorkoutMinDurationMinutes '
'minutes (currently ${duration.toStringAsFixed(0)})';
}
if (draft.rpe < kManualWorkoutRpeMin || draft.rpe > kManualWorkoutRpeMax) {
return 'RPE must be between $kManualWorkoutRpeMin '
'and $kManualWorkoutRpeMax';
}
final sportError = draft.sport == kSportTableTennis
? _validateTableTennis(draft)
: _validateOtherSport(draft);
if (sportError != null) return sportError;
final reflections = <String, String>{
'What went well': draft.wentWell,
'What to improve': draft.toImprove,
'Overall feeling': draft.overallFeeling,
};
for (final entry in reflections.entries) {
final length = entry.value.trim().length;
if (length < kManualWorkoutReflectionMinChars) {
return '${entry.key} must be at least $kManualWorkoutReflectionMinChars '
'characters (currently $length)';
}
}
return null;
}
String? _validateTableTennis(ManualWorkoutDraft draft) {
final scores = <String, int>{
'Matches won': draft.matchesWon,
'Matches lost': draft.matchesLost,
'Sets won': draft.setsWon,
'Sets lost': draft.setsLost,
};
for (final entry in scores.entries) {
if (entry.value < 0) return '${entry.key} cannot be negative';
}
if (draft.matchesWon + draft.matchesLost == 0) {
return 'Enter at least one match played (won + lost)';
}
if (draft.racket.trim().isEmpty) return 'Racket is required';
if (draft.balls.trim().isEmpty) return 'Balls are required';
return null;
}
String? _validateOtherSport(ManualWorkoutDraft draft) {
if (draft.activityTypeOther.trim().isEmpty) {
return 'Activity type is required';
}
final length = draft.activityDetails.trim().length;
if (length < kManualWorkoutDescriptionMinChars) {
return 'What was done must be at least '
'$kManualWorkoutDescriptionMinChars characters (currently $length)';
}
return null;
}
/// Builds the persisted `workout_data` dict for a validated draft.
///
/// Byte-for-byte equivalent of the Python `build_entry`.
Map<String, Object?> buildEntry(ManualWorkoutDraft draft) {
final duration = durationMinutes(draft);
final activityLabel = draft.sport == kSportTableTennis
? 'table tennis'
: draft.activityTypeOther.trim();
final entry = <String, Object?>{
'type': kManualWorkoutSyncKind,
'source': '$activityLabel at ${draft.locationName.trim()}',
'sport': draft.sport,
'activity_type': activityLabel,
'start_time': draft.startTime.trim(),
'end_time': draft.endTime.trim(),
'duration_minutes': duration != null ? duration.toStringAsFixed(1) : '',
'location_name': draft.locationName.trim(),
'transport_method': draft.transportMethod.trim(),
'cost': draft.cost.trim(),
'reservation_phone': draft.reservationPhone.trim(),
'rpe': draft.rpe,
'techniques_practiced': draft.techniquesPracticed.trim(),
'warm_up_minutes': draft.warmUpMinutes.trim(),
'pain_or_injury': draft.painOrInjury.trim(),
'went_well': draft.wentWell.trim(),
'to_improve': draft.toImprove.trim(),
'overall_feeling': draft.overallFeeling.trim(),
};
if (draft.sport == kSportTableTennis) {
entry.addAll(<String, Object?>{
'matches_won': draft.matchesWon,
'matches_lost': draft.matchesLost,
'sets_won': draft.setsWon,
'sets_lost': draft.setsLost,
'racket': draft.racket.trim(),
'balls': draft.balls.trim(),
});
} else {
entry.addAll(<String, Object?>{
'activity_details': draft.activityDetails.trim(),
'equipment': draft.equipment.trim(),
});
}
return entry;
}
/// Builds the cross-device sync payload: [buildEntry] + `kind` + `date`.
Map<String, Object?> buildSyncPayload(ManualWorkoutDraft draft, String date) {
return <String, Object?>{
...buildEntry(draft),
'kind': kManualWorkoutSyncKind,
'date': date,
};
}
/// The stable crdt-sync record id for a manual workout.
///
/// Format: `manual:<date>T<HH:MM>`.
String manualSyncRecordId(String date, String startTime) =>
'manual:${date}T${startTime.trim()}';
/// Builds the crdt-sync [Record] for a manual workout, stamped with [hlc].
Record buildManualRecord(
ManualWorkoutDraft draft,
String date, {
required Hlc hlc,
}) {
return Record(
id: manualSyncRecordId(date, draft.startTime),
fields: {'payload': (buildSyncPayload(draft, date), hlc)},
);
}
/// Manual-workout counts in the rolling 7-/30-day windows (the shared budget).
class ManualBudget {
/// Creates a budget snapshot.
const ManualBudget({required this.week, required this.month});
/// Manual workouts in the last 7 days.
final int week;
/// Manual workouts in the last 30 days.
final int month;
/// Whether either window has reached its limit.
bool get exhausted =>
week >= kManualWorkoutBudgetPer7Days ||
month >= kManualWorkoutBudgetPer30Days;
}
/// Counts manual-workout [payloads] falling in the rolling 7-/30-day windows.
///
/// Each payload's own `date` (YYYY-MM-DD) is the window key, so both devices
/// compute the same shared budget over the merged record set.
ManualBudget countManualBudget(
Iterable<Map<String, dynamic>> payloads,
DateTime now,
) {
final today = DateTime(now.year, now.month, now.day);
var week = 0;
var month = 0;
for (final payload in payloads) {
final dateStr = payload['date'];
if (dateStr is! String) continue;
final date = DateTime.tryParse(dateStr);
if (date == null) continue;
final days = today
.difference(DateTime(date.year, date.month, date.day))
.inDays;
if (days < 0) continue;
if (days < 7) week++;
if (days < 30) month++;
}
return ManualBudget(week: week, month: month);
}

View File

@ -51,12 +51,7 @@ class _HistoryScreenState extends State<HistoryScreen> {
}
ExerciseState? state;
if (_selected != _kTotal) {
// Unreachable in practice: _load only runs from initState, where
// _selected is still _kTotal; exercise selection goes through
// _pickExercise, which loads its own state.
// coverage:ignore-start
state = await StorageService.instance.getExerciseState(_selected);
// coverage:ignore-end
}
if (mounted) {
setState(() {

View File

@ -5,7 +5,6 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/screens/history_screen.dart';
import 'package:workout_app/screens/manual_workout_screen.dart';
import 'package:workout_app/screens/settings_screen.dart';
import 'package:workout_app/screens/workout_screen.dart';
import 'package:workout_app/services/http_server_service.dart';
@ -109,15 +108,6 @@ class _HomeScreenState extends State<HomeScreen> {
style: TextStyle(color: Colors.white),
),
actions: [
IconButton(
icon: const Icon(Icons.edit_note, color: Colors.white),
tooltip: 'Log manual workout',
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => const ManualWorkoutScreen(),
),
),
),
IconButton(
icon: const Icon(Icons.history, color: Colors.white),
onPressed: () => Navigator.of(context).push(
@ -153,7 +143,7 @@ class _HomeScreenState extends State<HomeScreen> {
onResume: () => _openWorkout(resume: true),
),
const SizedBox(height: 20),
ServerAddressTile(addresses: _serverAddresses),
_ServerAddressTile(addresses: _serverAddresses),
],
),
),
@ -278,14 +268,9 @@ class _WorkoutCard extends StatelessWidget {
}
}
/// Displays the LAN addresses the workout HTTP server is reachable at, or a
/// "Server not started" placeholder when none are available. Public so the
/// empty-address fallback can be exercised in a widget test.
class ServerAddressTile extends StatelessWidget {
/// Creates a tile listing [addresses] (may be empty).
const ServerAddressTile({required this.addresses, super.key});
class _ServerAddressTile extends StatelessWidget {
const _ServerAddressTile({required this.addresses});
/// LAN addresses the server is reachable at; empty when not started.
final List<String> addresses;
@override

View File

@ -1,308 +0,0 @@
/// Form for logging a manual (off-app) workout that syncs to the PC.
///
/// Mirrors the PC screen-locker manual-workout form: the same fields, the same
/// validation ([validateManualWorkout]), and the same rolling budget
/// (2/week, 5/month) computed over the merged cross-device record set. On
/// submit it builds the shared sync payload and pushes it to the phone's device
/// log; the PC ingests it as a counted `manual_workout`.
library;
import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter/material.dart';
import 'package:workout_app/models/manual_workout.dart';
import 'package:workout_app/services/workout_sync_service.dart';
/// A screen that logs an off-app workout and syncs it to the PC.
class ManualWorkoutScreen extends StatefulWidget {
/// Creates the manual-workout form. [syncService]/[clock] are injectable for
/// tests; production uses a real [WorkoutSyncService] and [DateTime.now].
const ManualWorkoutScreen({super.key, this.syncService, this.clock});
/// Sync service used to read the budget and push the workout.
final WorkoutSyncService? syncService;
/// Returns "now"; defaults to [DateTime.now].
final DateTime Function()? clock;
@override
State<ManualWorkoutScreen> createState() => _ManualWorkoutScreenState();
}
class _ManualWorkoutScreenState extends State<ManualWorkoutScreen> {
late final WorkoutSyncService _sync =
widget.syncService ?? WorkoutSyncService();
DateTime Function() get _clock => widget.clock ?? DateTime.now;
final _fields = <String, TextEditingController>{
for (final key in [
'start_time',
'end_time',
'location_name',
'transport_method',
'cost',
'reservation_phone',
'techniques_practiced',
'warm_up_minutes',
'pain_or_injury',
'matches_won',
'matches_lost',
'sets_won',
'sets_lost',
'racket',
'balls',
'activity_type_other',
'activity_details',
'equipment',
'went_well',
'to_improve',
'overall_feeling',
])
key: TextEditingController(),
};
String _sport = kSportTableTennis;
double _rpe = 5;
String? _error;
bool _submitting = false;
ManualBudget? _budget;
bool _budgetLoaded = false;
@override
void initState() {
super.initState();
unawaited(_loadBudget());
}
@override
void dispose() {
for (final c in _fields.values) {
c.dispose();
}
super.dispose();
}
Future<void> _loadBudget() async {
final payloads = await _sync.readMergedManualPayloads();
if (!mounted) return;
setState(() {
_budget = countManualBudget(payloads, _clock());
_budgetLoaded = true;
});
}
int _int(String key) => int.tryParse(_fields[key]!.text.trim()) ?? 0;
String _str(String key) => _fields[key]!.text;
ManualWorkoutDraft _draft() => ManualWorkoutDraft(
sport: _sport,
startTime: _str('start_time'),
endTime: _str('end_time'),
locationName: _str('location_name'),
transportMethod: _str('transport_method'),
cost: _str('cost'),
rpe: _rpe.round(),
wentWell: _str('went_well'),
toImprove: _str('to_improve'),
overallFeeling: _str('overall_feeling'),
reservationPhone: _str('reservation_phone'),
techniquesPracticed: _str('techniques_practiced'),
warmUpMinutes: _str('warm_up_minutes'),
painOrInjury: _str('pain_or_injury').trim().isEmpty
? 'none'
: _str('pain_or_injury'),
matchesWon: _int('matches_won'),
matchesLost: _int('matches_lost'),
setsWon: _int('sets_won'),
setsLost: _int('sets_lost'),
racket: _str('racket'),
balls: _str('balls'),
activityTypeOther: _str('activity_type_other'),
activityDetails: _str('activity_details'),
equipment: _str('equipment'),
);
Future<void> _submit() async {
final draft = _draft();
final error = validateManualWorkout(draft);
if (error != null) {
setState(() => _error = error);
return;
}
setState(() {
_error = null;
_submitting = true;
});
final now = _clock();
final date =
'${now.year.toString().padLeft(4, '0')}-'
'${now.month.toString().padLeft(2, '0')}-'
'${now.day.toString().padLeft(2, '0')}';
await _sync.pushManual(
buildManualRecord(draft, date, hlc: Hlc.newTick('phone')),
);
if (!mounted) return;
Navigator.of(context).pop(true);
}
@override
Widget build(BuildContext context) {
final budget = _budget;
final exhausted = budget?.exhausted ?? false;
return Scaffold(
backgroundColor: Colors.grey.shade900,
appBar: AppBar(
backgroundColor: Colors.grey.shade800,
title: const Text(
'Log Manual Workout',
style: TextStyle(color: Colors.white),
),
),
body: !_budgetLoaded
? const Center(child: CircularProgressIndicator())
: ListView(
padding: const EdgeInsets.all(16),
children: [
_budgetBanner(budget!),
if (exhausted)
const Padding(
padding: EdgeInsets.only(top: 8),
child: Text(
'Manual-workout budget exhausted for this window.',
style: TextStyle(color: Color(0xFFFF4444)),
),
)
else ...[
_section('Basics'),
_sportDropdown(),
_text('start_time', 'Start time (HH:MM)'),
_text('end_time', 'End time (HH:MM)'),
_section('Location & logistics'),
_text('location_name', 'Location name'),
_text('transport_method', 'How did you get there?'),
_text('cost', 'Cost (e.g. 40 PLN)'),
_text('reservation_phone', 'Reservation phone (optional)'),
_section('Activity details'),
..._sportFields(),
_rpeSlider(),
_text('techniques_practiced', 'Techniques (optional)'),
_text('warm_up_minutes', 'Warm-up (optional)'),
_text('pain_or_injury', 'Pain or injury (optional)'),
_section('Reflection'),
_text('went_well', 'What went well', lines: 3),
_text('to_improve', 'What to improve', lines: 3),
_text('overall_feeling', 'Overall feeling', lines: 3),
if (_error != null)
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(
_error!,
style: const TextStyle(color: Color(0xFFFF4444)),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: ElevatedButton(
onPressed: _submitting ? null : _submit,
child: const Text('SUBMIT'),
),
),
],
],
),
);
}
List<Widget> _sportFields() {
if (_sport == kSportTableTennis) {
return [
_text('matches_won', 'Matches won'),
_text('matches_lost', 'Matches lost'),
_text('sets_won', 'Sets won'),
_text('sets_lost', 'Sets lost'),
_text('racket', 'Racket used'),
_text('balls', 'Balls used'),
];
}
return [
_text('activity_type_other', 'What sport/activity'),
_text('activity_details', 'What was done', lines: 3),
_text('equipment', 'Equipment (optional)'),
];
}
Widget _budgetBanner(ManualBudget budget) => Text(
'Manual: ${budget.week}/$kManualWorkoutBudgetPer7Days this week · '
'${budget.month}/$kManualWorkoutBudgetPer30Days this month',
style: const TextStyle(color: Color(0xFF88CCFF), fontSize: 16),
);
Widget _section(String title) => Padding(
padding: const EdgeInsets.only(top: 16, bottom: 4),
child: Text(
title,
style: const TextStyle(
color: Color(0xFF88CCFF),
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
);
Widget _sportDropdown() => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: DropdownButton<String>(
value: _sport,
dropdownColor: Colors.grey.shade800,
style: const TextStyle(color: Colors.white),
isExpanded: true,
items: [
for (final entry in kSportLabels.entries)
DropdownMenuItem(value: entry.key, child: Text(entry.value)),
],
onChanged: (value) {
if (value != null) setState(() => _sport = value);
},
),
);
Widget _rpeSlider() => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
Text(
'RPE ${_rpe.round()}',
style: const TextStyle(color: Colors.white),
),
Expanded(
child: Slider(
value: _rpe,
min: kManualWorkoutRpeMin.toDouble(),
max: kManualWorkoutRpeMax.toDouble(),
divisions: kManualWorkoutRpeMax - kManualWorkoutRpeMin,
label: '${_rpe.round()}',
onChanged: (value) => setState(() => _rpe = value),
),
),
],
),
);
Widget _text(String key, String label, {int lines = 1}) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: TextField(
key: Key('mw_$key'),
controller: _fields[key],
maxLines: lines,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: label,
labelStyle: TextStyle(color: Colors.grey.shade400),
filled: true,
fillColor: Colors.grey.shade800,
border: const OutlineInputBorder(),
),
),
);
}

View File

@ -301,11 +301,7 @@ class _WorkoutScreenState extends State<WorkoutScreen> {
Future<void> _onBreakFinished() async {
await _audio.play(AssetSource('sounds/break_end.mp3')).catchError((_) {});
if (await Vibration.hasVibrator()) {
// Android/iOS-only: hasVibrator() returns false on the Linux test host
// (no Platform.isAndroid/isIOS), so this body never runs there.
// coverage:ignore-start
unawaited(Vibration.vibrate(duration: 800));
// coverage:ignore-end
}
setState(() {
_breakForExIdx = -1;

View File

@ -55,10 +55,6 @@ class BackupService {
// ── Permission ─────────────────────────────────────────────────────────────
// coverage:ignore-start
// Thin wrappers over the permission_handler platform channel — Android
// runtime permissions that can't be meaningfully exercised on the test host.
/// Returns true if the app has MANAGE_EXTERNAL_STORAGE.
Future<bool> hasStoragePermission() async {
return Permission.manageExternalStorage.isGranted;
@ -68,10 +64,10 @@ class BackupService {
///
/// Returns true once granted.
Future<bool> requestStoragePermission() async {
final status = await Permission.manageExternalStorage.request();
final status =
await Permission.manageExternalStorage.request();
return status.isGranted;
}
// coverage:ignore-end
// ── Export ─────────────────────────────────────────────────────────────────
@ -137,12 +133,8 @@ class BackupService {
if (!f.existsSync()) return null;
final token = await f.readAsString();
return token.isEmpty ? null : token;
// coverage:ignore-start
// Defensive: a present, readable token file is the norm; a portable way
// to make readAsString throw here (unreadable file) isn't available.
} on Exception {
return null;
}
// coverage:ignore-end
}
}

View File

@ -10,7 +10,6 @@ library;
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:workout_app/services/sync_service.dart';
@ -68,26 +67,14 @@ class HttpServerService {
/// HTTP endpoint is populated even before the next workout is completed.
Future<void> _loadFromDisk() async {
final candidates = <String>[kSyncFilePath];
// External storage is Android-only; getExternalStorageDirectory() throws an
// UnsupportedError (not an Exception) on other platforms (desktop / test
// host), so guard the call rather than trying to catch it.
// coverage:ignore-start
// Android-only: getExternalStorageDirectory is unavailable on the Linux
// test host, so this block can't be exercised in CI.
if (Platform.isAndroid) {
try {
final dir = await getExternalStorageDirectory();
if (dir != null) candidates.add('${dir.path}/workout_result.json');
} on Exception {
// Ignore; the /sdcard path is tried first.
}
// coverage:ignore-end
try {
final dir = await getExternalStorageDirectory();
if (dir != null) candidates.add('${dir.path}/workout_result.json');
} on Exception {
// Ignore; the /sdcard path is tried first.
}
for (final path in candidates) {
final file = File(path);
// coverage:ignore-start
// Only reachable when a candidate file exists — i.e. on a real device
// with /sdcard (or Android external storage). Not present on the host.
if (file.existsSync()) {
try {
_latestJson = await file.readAsString();
@ -96,15 +83,9 @@ class HttpServerService {
// Try next path.
}
}
// coverage:ignore-end
}
}
/// Clears the cached workout JSON (test seam so the "no data yet" HTTP
/// response can be exercised after other tests have set it).
@visibleForTesting
void resetForTesting() => _latestJson = null;
Future<void> _serve() async {
final server = _server;
if (server == null) return;

View File

@ -73,32 +73,22 @@ class StorageService {
/// Resets the singleton so [init] can be called again in tests.
///
/// Defaults to an in-memory database so each test starts with a clean
/// slate and file-based data from other tests does not leak in. Pass a
/// file [dbPath] to exercise on-disk paths (e.g. schema migrations, which
/// need a persisted DB opened twice at different versions).
/// Also switches to an in-memory database so each test starts with a clean
/// slate and file-based data from other tests does not leak in.
@visibleForTesting
static void resetForTesting({String dbPath = ':memory:'}) {
static void resetForTesting() {
_instance = null;
_testDbPath = dbPath;
_testDbPath = ':memory:';
}
Future<void> _open() async {
final dbPath =
_testDbPath ??
// coverage:ignore-start
p.join(await getDatabasesPath(), 'workout_app.db');
// coverage:ignore-end
_testDbPath ?? p.join(await getDatabasesPath(), 'workout_app.db');
_db = await openDatabase(
dbPath,
version: 3,
onCreate: _createSchema,
onUpgrade: _migrateSchema,
// In tests resetForTesting() reopens a ':memory:' DB per test; sqflite's
// default singleInstance would hand back the same cached in-memory DB, so
// data would pile up across tests. Disable it so each test gets a fresh
// empty DB. Production keeps the default single shared instance.
singleInstance: _testDbPath == null,
);
await _seedDefaultsIfNeeded();
}
@ -312,11 +302,7 @@ class StorageService {
for (final ex in template) {
final state = await getExerciseState(ex.name);
if (state == null) {
// Defensive: _seedDefaultsIfNeeded guarantees every template exercise
// has a state row, so this branch is unreachable in practice.
// coverage:ignore-start
result.add(ex);
// coverage:ignore-end
} else {
result.add(ex.copyWith(weight: state.weight, reps: state.reps));
}

View File

@ -29,24 +29,16 @@ class SyncService {
// Fallback: app-specific external directory (still ADB accessible).
}
// External storage is Android-only; getExternalStorageDirectory() throws
// an UnsupportedError (not an Exception) elsewhere, so guard the call.
// coverage:ignore-start
// Android-only: getExternalStorageDirectory is unavailable on the Linux
// test host, so this block can't be exercised in CI.
if (Platform.isAndroid) {
try {
final dir = await getExternalStorageDirectory();
if (dir != null) {
final file = File('${dir.path}/workout_result.json');
await file.writeAsString(json);
return SyncResult(success: true, path: file.path);
}
} on Exception {
// Fallback failed.
try {
final dir = await getExternalStorageDirectory();
if (dir != null) {
final file = File('${dir.path}/workout_result.json');
await file.writeAsString(json);
return SyncResult(success: true, path: file.path);
}
} on Exception {
// Fallback failed.
}
// coverage:ignore-end
return const SyncResult(
success: false,

View File

@ -6,7 +6,6 @@ import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:workout_app/models/manual_workout.dart';
import 'package:workout_app/models/workout_session.dart';
import 'package:workout_app/services/sync_settings.dart';
@ -86,87 +85,4 @@ class WorkoutSyncService {
client.close();
}
}
/// Pushes a pre-built manual-workout [record] to `devices/phone/log.json`,
/// merging with whatever this device has already pushed. Same swallow-on-
/// failure contract as [push].
Future<void> pushManual(Record record) async {
final settings = await SyncSettings.load();
if (!settings.isConfigured) return;
final client = GitHubClient(
owner: owner,
repo: repo,
token: settings.token,
httpClient: _httpClient,
);
try {
const path = '$_pathPrefix/$_deviceId/$_logFilename';
final existingText = await client.getFileText(path);
final existingLog = existingText == null
? <String, Record>{}
: _decode(existingText);
final localLog = mergeLogs(existingLog, {record.id: record});
await syncLog(
client: client,
deviceId: _deviceId,
pathPrefix: _pathPrefix,
localLog: localLog,
encode: _encode,
decode: _decode,
);
} on GitHubSyncError catch (error) {
debugPrint('WorkoutSyncService.pushManual failed: $error');
} finally {
client.close();
}
}
/// Returns every device's manual-workout payloads, merged and deduped by id
/// (highest HLC wins), for computing the shared budget. Pull-only — unlike
/// [pushManual] it never writes, so showing the budget can't mutate the repo.
/// Returns an empty list if sync isn't configured or the repo is unreachable.
Future<List<Map<String, dynamic>>> readMergedManualPayloads() async {
final settings = await SyncSettings.load();
if (!settings.isConfigured) return const [];
final client = GitHubClient(
owner: owner,
repo: repo,
token: settings.token,
httpClient: _httpClient,
);
try {
final merged = <String, Record>{};
for (final device in await client.listDirectory(_pathPrefix)) {
final text = await client.getFileText('$_pathPrefix/$device/$_logFilename');
if (text == null) continue;
_mergeManualRecords(_decode(text), merged);
}
return merged.values
.map((r) => (r.fields['payload']!.$1! as Map).cast<String, dynamic>())
.toList();
} on GitHubSyncError catch (error) {
debugPrint('WorkoutSyncService.readMergedManualPayloads failed: $error');
return const [];
} finally {
client.close();
}
}
static void _mergeManualRecords(Log log, Map<String, Record> into) {
for (final entry in log.entries) {
final field = entry.value.fields['payload'];
if (field == null) continue;
final payload = field.$1;
if (payload is! Map ||
payload['kind'] != kManualWorkoutSyncKind) {
continue;
}
final existing = into[entry.key];
if (existing == null || existing.fields['payload']!.$2 < field.$2) {
into[entry.key] = entry.value;
}
}
}
}

View File

@ -1,270 +0,0 @@
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/manual_workout.dart';
// Builds a VALID table-tennis draft; override individual fields per test.
ManualWorkoutDraft _tt({
String sport = kSportTableTennis,
String startTime = '18:00',
String endTime = '19:30',
String locationName = 'Solec',
String transportMethod = 'bike',
String cost = '40 PLN',
int rpe = 6,
String wentWell = 'Served consistently and moved feet well',
String toImprove = 'Backhand topspin needs more consistency',
String overallFeeling = 'Felt strong focused and in good rhythm',
int matchesWon = 3,
int matchesLost = 1,
int setsWon = 7,
int setsLost = 4,
String racket = 'Butterfly',
String balls = 'Nittaku 3-star',
}) => ManualWorkoutDraft(
sport: sport,
startTime: startTime,
endTime: endTime,
locationName: locationName,
transportMethod: transportMethod,
cost: cost,
rpe: rpe,
wentWell: wentWell,
toImprove: toImprove,
overallFeeling: overallFeeling,
matchesWon: matchesWon,
matchesLost: matchesLost,
setsWon: setsWon,
setsLost: setsLost,
racket: racket,
balls: balls,
);
// Builds a VALID "other sport" draft; override individual fields per test.
ManualWorkoutDraft _other({
String activityTypeOther = 'squash',
String activityDetails =
'Full-court squash drills and three practice games total',
String equipment = 'racket, goggles',
}) => ManualWorkoutDraft(
sport: kSportOther,
startTime: '09:00',
endTime: '10:00',
locationName: 'Squash club',
transportMethod: 'car',
cost: '30 PLN',
rpe: 5,
wentWell: 'Moved well and kept long rallies going',
toImprove: 'Need to volley earlier off the back wall',
overallFeeling: 'Tired but satisfied with the effort',
activityTypeOther: activityTypeOther,
activityDetails: activityDetails,
equipment: equipment,
);
// The cross-language wire fixture — an IDENTICAL literal lives in the Python
// suite (test_manual_workout.py::TestSyncWireFormat). Neither side's own
// round-trip test catches a key-name/format drift from the other; this shared
// literal on both sides does. Change one, change the other.
const _wireDate = '2026-07-13';
const _wirePayload = <String, Object?>{
'type': 'manual_workout',
'source': 'table tennis at Solec',
'sport': 'table_tennis',
'activity_type': 'table tennis',
'start_time': '18:00',
'end_time': '19:30',
'duration_minutes': '90.0',
'location_name': 'Solec',
'transport_method': 'bike',
'cost': '40 PLN',
'reservation_phone': '600100200',
'rpe': 6,
'techniques_practiced': 'topspin serve',
'warm_up_minutes': '10',
'pain_or_injury': 'none',
'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',
'kind': 'manual_workout',
'date': '2026-07-13',
};
void main() {
group('cross-language wire format', () {
// Matches the _wire draft used to produce _wirePayload on the Python side.
final wireDraft = _tt(
// These optional fields aren't in _tt's parameter list; set via a fresh
// draft below so the fixture is exact.
);
test('buildSyncPayload matches the shared fixture', () {
const draft = ManualWorkoutDraft(
sport: kSportTableTennis,
startTime: '18:00',
endTime: '19:30',
locationName: 'Solec',
transportMethod: 'bike',
cost: '40 PLN',
rpe: 6,
wentWell: 'Served consistently and moved feet well',
toImprove: 'Backhand topspin needs more consistency',
overallFeeling: 'Felt strong focused and in good rhythm',
reservationPhone: '600100200',
techniquesPracticed: 'topspin serve',
warmUpMinutes: '10',
matchesWon: 3,
matchesLost: 1,
setsWon: 7,
setsLost: 4,
racket: 'Butterfly',
balls: 'Nittaku 3-star',
);
expect(buildSyncPayload(draft, _wireDate), _wirePayload);
});
test('record id is stable and prefixed', () {
expect(manualSyncRecordId(_wireDate, '18:00'), 'manual:2026-07-13T18:00');
});
test('buildManualRecord wraps the payload under a manual id', () {
final record = buildManualRecord(
wireDraft,
_wireDate,
hlc: Hlc.newTick('phone'),
);
expect(record.id, 'manual:2026-07-13T18:00');
expect(record.fields['payload']!.$1, buildSyncPayload(wireDraft, _wireDate));
});
});
group('validateManualWorkout', () {
test('valid table tennis returns null', () {
expect(validateManualWorkout(_tt()), isNull);
});
test('valid other sport returns null', () {
expect(validateManualWorkout(_other()), isNull);
});
test('rejects an unknown sport', () {
expect(validateManualWorkout(_tt(sport: 'badminton')), isNotNull);
});
for (final field in ['start', 'end', 'location', 'transport', 'cost']) {
test('rejects blank $field', () {
final draft = switch (field) {
'start' => _tt(startTime: ' '),
'end' => _tt(endTime: ' '),
'location' => _tt(locationName: ' '),
'transport' => _tt(transportMethod: ' '),
_ => _tt(cost: ' '),
};
expect(validateManualWorkout(draft), isNotNull);
});
}
test('rejects a bad time format', () {
expect(validateManualWorkout(_tt(startTime: 'noon')), isNotNull);
});
test('rejects end not after start', () {
expect(
validateManualWorkout(_tt(startTime: '14:00', endTime: '12:00')),
isNotNull,
);
});
test('rejects an out-of-range hour', () {
expect(validateManualWorkout(_tt(startTime: '25:00')), isNotNull);
});
test('rejects a too-short session', () {
expect(
validateManualWorkout(_tt(startTime: '12:00', endTime: '12:05')),
isNotNull,
);
});
test('rejects an out-of-range RPE', () {
expect(validateManualWorkout(_tt(rpe: 0)), isNotNull);
expect(validateManualWorkout(_tt(rpe: 11)), isNotNull);
});
test('rejects a short reflection', () {
expect(validateManualWorkout(_tt(wentWell: 'ok')), isNotNull);
});
});
group('table tennis validation', () {
test('rejects a negative score', () {
expect(validateManualWorkout(_tt(matchesWon: -1)), isNotNull);
});
test('rejects zero matches played', () {
expect(
validateManualWorkout(_tt(matchesWon: 0, matchesLost: 0)),
isNotNull,
);
});
test('requires a racket', () {
expect(validateManualWorkout(_tt(racket: ' ')), isNotNull);
});
test('requires balls', () {
expect(validateManualWorkout(_tt(balls: ' ')), isNotNull);
});
});
group('other sport validation', () {
test('requires an activity type', () {
expect(validateManualWorkout(_other(activityTypeOther: ' ')), isNotNull);
});
test('requires a long-enough description', () {
expect(validateManualWorkout(_other(activityDetails: 'short')), isNotNull);
});
});
group('buildEntry', () {
test('table tennis carries score fields and a table-tennis label', () {
final entry = buildEntry(_tt());
expect(entry['activity_type'], 'table tennis');
expect(entry['matches_lost'], 1);
expect(entry['source'], 'table tennis at Solec');
});
test('other sport carries description/equipment and its own label', () {
final entry = buildEntry(_other());
expect(entry['activity_type'], 'squash');
expect(entry['activity_details'], contains('squash'));
expect(entry['equipment'], 'racket, goggles');
});
test('duration is empty for an unparsable time', () {
expect(buildEntry(_tt(startTime: 'bogus'))['duration_minutes'], '');
});
test('strips whitespace from fields', () {
final entry = buildEntry(_tt(locationName: ' Solec ', racket: ' pro '));
expect(entry['location_name'], 'Solec');
expect(entry['racket'], 'pro');
});
});
group('durationMinutes', () {
test('returns minutes for a valid range', () {
expect(durationMinutes(_tt(startTime: '12:00', endTime: '13:30')), 90.0);
});
test('returns null for an unparsable time', () {
expect(durationMinutes(_tt(startTime: 'noon')), isNull);
});
});
}

View File

@ -3,7 +3,6 @@ import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/screens/history_screen.dart';
import 'package:workout_app/services/storage_service.dart';
@ -28,28 +27,6 @@ void main() {
Widget _wrap() => const MaterialApp(home: HistoryScreen());
// Seed a workout. DB writes must run on the real event loop: the widget-test
// zone fakes async, so a sqflite-ffi write in the test body hangs (then the
// isolate crashes on shutdown). runAsync gives the write the real loop.
Future<void> _seed(
WidgetTester tester,
String json, {
String date = '2024-06-01',
String type = 'A',
int duration = 1800,
bool succeeded = true,
}) async {
await tester.runAsync(
() => StorageService.instance.saveSession(
date: date,
workoutType: type,
durationSeconds: duration,
succeeded: succeeded,
json: json,
),
);
}
testWidgets('shows Progress app bar', (tester) async {
await _pump(tester, _wrap());
expect(find.text('Progress'), findsOneWidget);
@ -76,7 +53,13 @@ void main() {
},
],
});
await _seed(tester, json);
await StorageService.instance.saveSession(
date: '2024-06-01',
workoutType: 'A',
durationSeconds: 1800,
succeeded: true,
json: json,
);
await _pump(tester, _wrap());
expect(find.textContaining('Workout A'), findsWidgets);
});
@ -96,14 +79,26 @@ void main() {
},
],
});
await _seed(tester, json);
await StorageService.instance.saveSession(
date: '2024-06-01',
workoutType: 'A',
durationSeconds: 1800,
succeeded: true,
json: json,
);
await _pump(tester, _wrap());
expect(find.textContaining('Total'), findsOneWidget);
});
testWidgets('calendar prev/next month navigation works', (tester) async {
final json = jsonEncode({'exercises': []});
await _seed(tester, json);
await StorageService.instance.saveSession(
date: '2024-06-01',
workoutType: 'A',
durationSeconds: 1800,
succeeded: true,
json: json,
);
await _pump(tester, _wrap());
await tester.tap(find.byIcon(Icons.chevron_right).first);
await tester.pump();
@ -114,14 +109,26 @@ void main() {
testWidgets('session tile shows succeeded checkmark', (tester) async {
final json = jsonEncode({'exercises': []});
await _seed(tester, json);
await StorageService.instance.saveSession(
date: '2024-06-01',
workoutType: 'A',
durationSeconds: 1800,
succeeded: true,
json: json,
);
await _pump(tester, _wrap());
expect(find.byIcon(Icons.check_circle), findsWidgets);
});
testWidgets('session tile shows cancel icon on failure', (tester) async {
final json = jsonEncode({'exercises': []});
await _seed(tester, json, duration: 900, succeeded: false);
await StorageService.instance.saveSession(
date: '2024-06-01',
workoutType: 'A',
durationSeconds: 900,
succeeded: false,
json: json,
);
await _pump(tester, _wrap());
expect(find.byIcon(Icons.cancel), findsWidgets);
});
@ -129,7 +136,13 @@ void main() {
testWidgets('session duration over 1 hour formats with h prefix',
(tester) async {
final json = jsonEncode({'exercises': []});
await _seed(tester, json, duration: 3700);
await StorageService.instance.saveSession(
date: '2024-06-01',
workoutType: 'A',
durationSeconds: 3700,
succeeded: true,
json: json,
);
await _pump(tester, _wrap());
expect(find.textContaining('1h'), findsOneWidget);
});
@ -149,131 +162,15 @@ void main() {
],
});
for (var i = 1; i <= 3; i++) {
await _seed(tester, json, date: '2024-06-0$i');
await StorageService.instance.saveSession(
date: '2024-06-0$i',
workoutType: 'A',
durationSeconds: 1800,
succeeded: true,
json: json,
);
}
await _pump(tester, _wrap());
expect(find.byType(HistoryScreen), findsOneWidget);
});
// JSON for one session containing [name] at [weight].
String _exerciseSessionJson(
String name,
double weight, {
required bool ok,
required bool warmup,
required bool withSets,
}) {
return jsonEncode({
'exercises': [
{
'name': name,
'targetSets': 3,
'targetReps': 5,
'targetWeight': weight,
'warmupDone': warmup,
'succeeded': ok,
'sets': withSets
? [
{
'targetReps': 5,
'doneReps': 5,
'weight': weight,
'succeeded': true,
},
{
'targetReps': 5,
'doneReps': 4,
'weight': weight,
'succeeded': false,
},
]
: <Map<String, dynamic>>[],
},
],
});
}
testWidgets('selecting an exercise shows the drill-down view', (tester) async {
// Use a real progression-tracked exercise so getExerciseState is non-null
// and the streak stats card renders. Three distinct weights on three dates
// give the weight chart >= 2 points with a real range (painter fully runs).
final name = workoutA.first.name;
await _seed(
tester,
_exerciseSessionJson(name, 20, ok: true, warmup: true, withSets: true),
date: '2024-06-01',
);
await _seed(
tester,
_exerciseSessionJson(name, 22.5, ok: false, warmup: false, withSets: false),
date: '2024-06-08',
succeeded: false,
);
await _seed(
tester,
_exerciseSessionJson(name, 25, ok: true, warmup: true, withSets: true),
date: '2024-06-15',
);
await _pump(tester, _wrap());
// Open the dropdown and pick the exercise; _pickExercise awaits a DB read,
// and the menu open/close animation runs on real timers under runAsync, so
// drive the whole interaction on the real loop.
await tester.runAsync(() async {
await tester.tap(find.byType(DropdownButton<String>));
await Future<void>.delayed(const Duration(milliseconds: 400));
await tester.pump();
await tester.tap(find.text(name).last);
await Future<void>.delayed(const Duration(milliseconds: 400));
await tester.pump();
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
// Exercise view rendered: chart + streak stats card near the top.
expect(find.text('WEIGHT OVER TIME'), findsOneWidget);
expect(find.textContaining('more to'), findsWidgets);
// Exercise-view calendar month nav (covers its onPrev/onNext closures).
await tester.tap(find.byIcon(Icons.chevron_right).first);
await tester.pump();
await tester.tap(find.byIcon(Icons.chevron_left).first);
await tester.pump();
// The session list + name label sit below the fold; scroll to build them.
await tester.scrollUntilVisible(
find.text(name.toUpperCase()),
300,
scrollable: find.byType(Scrollable).first,
);
expect(find.text(name.toUpperCase()), findsOneWidget);
// Session tiles: warmup marker and reps summary both present.
expect(find.textContaining('warmup'), findsWidgets);
expect(find.textContaining('reps:'), findsWidgets);
});
testWidgets('chart handles two points on the same date (tRange == 0)',
(tester) async {
// Two sessions on the SAME date give the total chart two points that share
// a timestamp, exercising the painter's tRange == 0 (centre-x) branch.
String vol(double w) => jsonEncode({
'exercises': [
{
'name': 'Squat',
'targetSets': 3,
'targetReps': 5,
'targetWeight': w,
'warmupDone': false,
'succeeded': true,
'sets': <Map<String, dynamic>>[],
},
],
});
await _seed(tester, vol(20), date: '2024-06-01');
await _seed(tester, vol(40), date: '2024-06-01');
await _pump(tester, _wrap());
expect(find.byType(HistoryScreen), findsOneWidget);
expect(find.text('WEIGHT OVER TIME').evaluate(), isEmpty); // total view
});
}

View File

@ -1,13 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/screens/home_screen.dart';
import 'package:workout_app/screens/workout_screen.dart';
import 'package:workout_app/services/storage_service.dart';
import '../fake_secure_storage.dart';
void main() {
setUpAll(() {
sqfliteFfiInit();
@ -68,16 +64,12 @@ void main() {
final dateStr =
'${today.year}-${today.month.toString().padLeft(2, '0')}'
'-${today.day.toString().padLeft(2, '0')}';
// DB writes need the real event loop (the widget-test zone fakes async and
// would hang sqflite-ffi); run the seed inside runAsync.
await tester.runAsync(
() => StorageService.instance.saveSession(
date: dateStr,
workoutType: 'A',
durationSeconds: 1800,
succeeded: true,
json: '{"exercises":[]}',
),
await StorageService.instance.saveSession(
date: dateStr,
workoutType: 'A',
durationSeconds: 1800,
succeeded: true,
json: '{"exercises":[]}',
);
await _pump(tester, _wrap());
expect(find.text('Done for today!'), findsOneWidget);
@ -87,111 +79,4 @@ void main() {
await _pump(tester, _wrap());
expect(find.text('HTTP sync (no ADB needed)'), findsOneWidget);
});
testWidgets('manual-workout icon navigates to the manual form', (tester) async {
installFakeSecureStorage(); // ManualWorkoutScreen loads its sync budget
await _pump(tester, _wrap());
await tester.tap(find.byIcon(Icons.edit_note));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(find.text('Log Manual Workout'), findsOneWidget);
});
testWidgets('starting a workout navigates to the workout screen',
(tester) async {
await _pump(tester, _wrap());
await tester.tap(find.text('Start Workout A'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(find.textContaining('Workout A'), findsWidgets);
});
testWidgets('an active session auto-resumes into the workout screen',
(tester) async {
await tester.runAsync(
() => StorageService.instance.saveActiveSession({
'workoutType': 'A',
'startTime': DateTime.now().toIso8601String(),
'exercises': <dynamic>[],
}),
);
await _pump(tester, _wrap());
await tester.pump(const Duration(milliseconds: 300));
// The post-frame auto-resume pushed the workout screen.
expect(find.textContaining('Workout A'), findsWidgets);
});
testWidgets('active session shows Resume, returns (98) and re-enters (153)',
(tester) async {
// A fully-formed active session so WorkoutScreen restores cleanly (its
// _restoreFromSaved expects startTimeMs + per-exercise tapped/doneReps).
await tester.runAsync(
() => StorageService.instance.saveActiveSession({
'workoutType': 'A',
'startTimeMs': DateTime.now().millisecondsSinceEpoch,
'tapped': [for (final e in workoutA) List<bool>.filled(e.sets, false)],
'doneReps': [for (final e in workoutA) List<int>.filled(e.sets, e.reps)],
'warmupTapped': List<bool>.filled(workoutA.length, false),
}),
);
// Drive the whole first-load + post-frame auto-resume push on the real loop
// (auto-resume awaits getCurrentExercises, which hangs under FakeAsync).
await tester.runAsync(() async {
await tester.pumpWidget(_wrap());
await Future<void>.delayed(const Duration(milliseconds: 300));
await tester.pump(); // fire the post-frame auto-resume callback
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(find.byType(WorkoutScreen), findsOneWidget);
// Return to home; auto-resume is now consumed so the Resume button shows.
await tester.runAsync(() async {
tester.state<NavigatorState>(find.byType(Navigator).last).pop();
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(find.byType(WorkoutScreen), findsNothing);
expect(find.text('Resume Workout'), findsOneWidget);
// Tapping Resume invokes onResume -> _openWorkout(resume:true) (line 153).
await tester.runAsync(() async {
await tester.tap(find.text('Resume Workout'));
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(find.byType(WorkoutScreen), findsOneWidget);
});
testWidgets('returning from settings reloads the home screen',
(tester) async {
installFakeSecureStorage(); // SettingsScreen reads the sync token on init
await _pump(tester, _wrap());
await tester.tap(find.byIcon(Icons.settings));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(find.text('Settings'), findsOneWidget);
// Pop back; the trailing _load() (line 135) needs the real loop for DB I/O.
await tester.runAsync(() async {
tester.state<NavigatorState>(find.byType(Navigator).last).pop();
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(find.text('Workout Tracker'), findsOneWidget);
});
testWidgets('ServerAddressTile shows a placeholder when no addresses',
(tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(body: ServerAddressTile(addresses: <String>[])),
),
);
expect(find.text('Server not started'), findsOneWidget);
});
}

View File

@ -1,157 +0,0 @@
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/manual_workout.dart';
import 'package:workout_app/screens/manual_workout_screen.dart';
import 'package:workout_app/services/workout_sync_service.dart';
class _FakeSync extends WorkoutSyncService {
_FakeSync({this.payloads = const []});
final List<Map<String, dynamic>> payloads;
Record? pushed;
@override
Future<List<Map<String, dynamic>>> readMergedManualPayloads() async =>
payloads;
@override
Future<void> pushManual(Record record) async {
pushed = record;
}
}
DateTime _fixedNow() => DateTime(2026, 7, 13, 20);
Future<void> _pump(WidgetTester tester, Widget child) async {
// Tall viewport so the whole (long) form is laid out — a ListView only builds
// children within the viewport, so off-screen widgets aren't findable.
tester.view.physicalSize = const Size(500, 2600);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(MaterialApp(home: child));
await tester.pumpAndSettle(); // let the budget future resolve
}
Future<void> _fillValidTt(WidgetTester tester) async {
Future<void> enter(String key, String value) =>
tester.enterText(find.byKey(Key('mw_$key')), value);
await enter('start_time', '18:00');
await enter('end_time', '19:30');
await enter('location_name', 'Solec');
await enter('transport_method', 'bike');
await enter('cost', '40 PLN');
await enter('matches_won', '3');
await enter('matches_lost', '1');
await enter('sets_won', '7');
await enter('sets_lost', '4');
await enter('racket', 'Butterfly');
await enter('balls', 'Nittaku');
await enter('pain_or_injury', 'sore knee');
await enter('went_well', 'Served consistently and moved feet well');
await enter('to_improve', 'Backhand topspin needs more consistency');
await enter('overall_feeling', 'Felt strong focused and in good rhythm');
}
void main() {
testWidgets('shows the form and budget when not exhausted', (tester) async {
await _pump(
tester,
ManualWorkoutScreen(syncService: _FakeSync(), clock: _fixedNow),
);
expect(find.text('Log Manual Workout'), findsOneWidget);
expect(find.text('SUBMIT'), findsOneWidget);
expect(find.textContaining('0/2 this week'), findsOneWidget);
});
testWidgets('hides the form when the budget is exhausted', (tester) async {
final payloads = [
{'kind': 'manual_workout', 'date': '2026-07-12'},
{'kind': 'manual_workout', 'date': '2026-07-13'},
];
await _pump(
tester,
ManualWorkoutScreen(
syncService: _FakeSync(payloads: payloads),
clock: _fixedNow,
),
);
expect(find.textContaining('budget exhausted'), findsOneWidget);
expect(find.text('SUBMIT'), findsNothing);
});
testWidgets('shows a validation error and does not push', (tester) async {
final sync = _FakeSync();
await _pump(
tester,
ManualWorkoutScreen(syncService: sync, clock: _fixedNow),
);
await tester.tap(find.text('SUBMIT'));
await tester.pump();
expect(find.textContaining('is required'), findsOneWidget);
expect(sync.pushed, isNull);
});
testWidgets('valid table-tennis workout pushes and pops', (tester) async {
final sync = _FakeSync();
await _pump(
tester,
ManualWorkoutScreen(syncService: sync, clock: _fixedNow),
);
await _fillValidTt(tester);
await tester.tap(find.text('SUBMIT'));
await tester.pumpAndSettle();
expect(sync.pushed, isNotNull);
expect(sync.pushed!.id, 'manual:2026-07-13T18:00');
final payload = sync.pushed!.fields['payload']!.$1! as Map;
expect(payload['kind'], 'manual_workout');
expect(payload['matches_won'], 3);
});
testWidgets('switching sport reveals the other-sport fields', (tester) async {
await _pump(
tester,
ManualWorkoutScreen(syncService: _FakeSync(), clock: _fixedNow),
);
expect(find.byKey(const Key('mw_matches_won')), findsOneWidget);
await tester.tap(find.byType(DropdownButton<String>));
await tester.pumpAndSettle();
await tester.tap(find.text('Other').last);
await tester.pumpAndSettle();
expect(find.byKey(const Key('mw_activity_type_other')), findsOneWidget);
expect(find.byKey(const Key('mw_matches_won')), findsNothing);
});
testWidgets('RPE slider updates the label', (tester) async {
await _pump(
tester,
ManualWorkoutScreen(syncService: _FakeSync(), clock: _fixedNow),
);
expect(find.text('RPE 5'), findsOneWidget);
await tester.drag(find.byType(Slider), const Offset(300, 0));
await tester.pump();
expect(find.text('RPE 5'), findsNothing);
});
testWidgets('other-sport validation error pushes nothing', (tester) async {
final sync = _FakeSync();
await _pump(
tester,
ManualWorkoutScreen(syncService: sync, clock: _fixedNow),
);
await tester.tap(find.byType(DropdownButton<String>));
await tester.pumpAndSettle();
await tester.tap(find.text('Other').last);
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('mw_start_time')), '18:00');
await tester.enterText(find.byKey(const Key('mw_end_time')), '19:30');
await tester.enterText(find.byKey(const Key('mw_location_name')), 'Club');
await tester.enterText(find.byKey(const Key('mw_transport_method')), 'car');
await tester.enterText(find.byKey(const Key('mw_cost')), '30');
await tester.tap(find.text('SUBMIT'));
await tester.pump();
expect(find.textContaining('Activity type is required'), findsOneWidget);
expect(sync.pushed, isNull);
});
}

View File

@ -114,10 +114,7 @@ void main() {
await _pump(tester, _wrap());
final firstName = workoutA.first.name;
// DB reads need the real event loop (the widget-test zone fakes async).
final state = await tester.runAsync(
() => StorageService.instance.getExerciseState(firstName),
);
final state = await StorageService.instance.getExerciseState(firstName);
final before = state!.weight;
await tester.tap(find.byIcon(Icons.add).first);
@ -130,10 +127,7 @@ void main() {
await _pump(tester, _wrap());
final firstName = workoutA.first.name;
// DB reads need the real event loop (the widget-test zone fakes async).
final state = await tester.runAsync(
() => StorageService.instance.getExerciseState(firstName),
);
final state = await StorageService.instance.getExerciseState(firstName);
final before = state!.weight;
await tester.tap(find.byIcon(Icons.remove).first);
@ -165,10 +159,8 @@ void main() {
});
testWidgets('Reset dialog confirms and resets data', (tester) async {
await tester.runAsync(
() => StorageService.instance
.setExerciseWeight(workoutA.first.name, 99.0),
);
await StorageService.instance
.setExerciseWeight(workoutA.first.name, 99.0);
await _pump(tester, _wrap());
await tester.tap(find.text('Reset defaults'));
@ -180,9 +172,8 @@ void main() {
});
await tester.pump();
final state = await tester.runAsync(
() => StorageService.instance.getExerciseState(workoutA.first.name),
);
final state =
await StorageService.instance.getExerciseState(workoutA.first.name);
expect(state!.weight, workoutA.first.weight);
});
@ -377,212 +368,4 @@ void main() {
await tester.pump();
});
});
testWidgets('changing a success threshold persists it', (tester) async {
await _pump(tester, _wrap());
final label = find.text('↑ Increase after N successes').first;
await tester.scrollUntilVisible(
label,
300,
scrollable: find.byType(Scrollable),
);
// The circles (1-5) live in the same Row as the label; tap the "5" circle.
final row = find.ancestor(of: label, matching: find.byType(Row)).first;
final five = find.descendant(of: row, matching: find.text('5')).first;
// The row can sit below the 800x600 test fold — bring the circle fully in.
await tester.ensureVisible(five);
await tester.pumpAndSettle();
// _onThresholdChanged awaits a DB write, so drive it on the real loop.
await tester.runAsync(() async {
await tester.tap(five);
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
final states = await tester.runAsync(
() => StorageService.instance.getAllExerciseStates(),
);
expect(states!.any((s) => s.successThreshold == 5), isTrue);
// Also exercise the fail-threshold path (onFailChanged closure).
final failLabel = find.text('↓ Decrease after N failures').first;
await tester.ensureVisible(failLabel);
await tester.pumpAndSettle();
final failRow =
find.ancestor(of: failLabel, matching: find.byType(Row)).first;
final failFour = find.descendant(of: failRow, matching: find.text('4')).first;
await tester.ensureVisible(failFour);
await tester.pumpAndSettle();
await tester.runAsync(() async {
await tester.tap(failFour);
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
final states2 = await tester.runAsync(
() => StorageService.instance.getAllExerciseStates(),
);
expect(states2!.any((s) => s.failThreshold == 4), isTrue);
});
testWidgets('weight change is debounced then written to storage', (
tester,
) async {
await _pump(tester, _wrap());
final name = workoutA.first.name;
final before = (await tester.runAsync(
() => StorageService.instance.getExerciseState(name),
))!.weight;
// Tapping "+" schedules a 600ms debounce Timer; running the tap and the
// wait on the real loop lets the timer fire and setExerciseWeight complete.
await tester.runAsync(() async {
await tester.tap(find.byIcon(Icons.add).first);
await Future<void>.delayed(const Duration(milliseconds: 800));
});
await tester.pump();
final after = (await tester.runAsync(
() => StorageService.instance.getExerciseState(name),
))!.weight;
expect(after, before + kWeightIncrement);
});
testWidgets('device flow: shows a message when the token cannot be saved', (
tester,
) async {
// Throwing secure storage makes SyncSettings.save() fail.
installFakeSecureStorage(throwing: true);
final mock = MockClient((req) async {
if (req.url.path.contains('device/code')) {
return http.Response(
jsonEncode({
'device_code': 'dev123',
'user_code': 'WXYZ-1234',
'verification_uri': 'https://github.com/login/device',
'interval': 0,
'expires_in': 900,
}),
200,
);
}
if (req.url.path.contains('oauth/access_token')) {
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
}
return http.Response(
jsonEncode({'content': base64Encode(utf8.encode('{}'))}),
200,
);
});
await tester.runAsync(() async {
await tester.pumpWidget(_wrap(httpClient: mock));
await Future<void>.delayed(const Duration(milliseconds: 300));
await tester.pump();
await _scrollToGitHubSync(tester);
await tester.tap(find.text('Connect GitHub'));
await _pumpUntil(
tester,
() =>
find.textContaining('could not save the token').evaluate().isNotEmpty,
);
expect(
find.textContaining('could not save the token'),
findsOneWidget,
);
});
});
testWidgets('device flow: shows a message when verification fails', (
tester,
) async {
final mock = MockClient((req) async {
if (req.url.path.contains('device/code')) {
return http.Response(
jsonEncode({
'device_code': 'dev123',
'user_code': 'WXYZ-1234',
'verification_uri': 'https://github.com/login/device',
'interval': 0,
'expires_in': 900,
}),
200,
);
}
if (req.url.path.contains('oauth/access_token')) {
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
}
// The post-connect verification GET fails → GitHubSyncError.
return http.Response('boom', 500);
});
await tester.runAsync(() async {
await tester.pumpWidget(_wrap(httpClient: mock));
await Future<void>.delayed(const Duration(milliseconds: 300));
await tester.pump();
await _scrollToGitHubSync(tester);
await tester.tap(find.text('Connect GitHub'));
await _pumpUntil(
tester,
() => find.textContaining('could not verify').evaluate().isNotEmpty,
);
expect(find.textContaining('could not verify'), findsOneWidget);
});
});
testWidgets('device flow: renders the pending "verifying" status', (
tester,
) async {
final mock = MockClient((req) async {
if (req.url.path.contains('device/code')) {
return http.Response(
jsonEncode({
'device_code': 'dev123',
'user_code': 'WXYZ-1234',
'verification_uri': 'https://github.com/login/device',
'interval': 0,
'expires_in': 900,
}),
200,
);
}
if (req.url.path.contains('oauth/access_token')) {
return http.Response(jsonEncode({'access_token': 'gho_test'}), 200);
}
// Hold the verification in-flight so the pending status tile is
// observable before it resolves to success.
await Future<void>.delayed(const Duration(milliseconds: 600));
return http.Response(
jsonEncode({'content': base64Encode(utf8.encode('{}'))}),
200,
);
});
await tester.runAsync(() async {
await tester.pumpWidget(_wrap(httpClient: mock));
await Future<void>.delayed(const Duration(milliseconds: 300));
await tester.pump();
await _scrollToGitHubSync(tester);
await tester.tap(find.text('Connect GitHub'));
await _pumpUntil(
tester,
() => find.textContaining('verifying').evaluate().isNotEmpty,
);
// Pending tile (spinner + white70 status colour) is now on screen.
expect(find.textContaining('verifying'), findsOneWidget);
await _pumpUntil(
tester,
() =>
find
.textContaining('Connected and verified')
.evaluate()
.isNotEmpty,
);
expect(find.textContaining('Connected and verified'), findsOneWidget);
});
});
}

View File

@ -2,32 +2,14 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/exercise.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/screens/workout_screen.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/widgets/break_banner.dart';
import 'package:workout_app/widgets/exercise_tile.dart';
import 'package:workout_app/widgets/rep_circle.dart';
import 'package:workout_app/widgets/workout_summary_dialog.dart';
import '../fake_audio_platform.dart';
import '../fake_secure_storage.dart';
/// A saved state with every set of the two [_exercises] tapped as done.
Map<String, dynamic> _completeSaved() => {
'workoutType': 'A',
'startTimeMs': DateTime.now().millisecondsSinceEpoch,
'tapped': [
[true, true, true],
[true, true, true],
],
'doneReps': [
[5, 5, 5],
[5, 5, 5],
],
'warmupTapped': [false, false],
};
const _exercises = [
Exercise(name: 'Squat', sets: 3, reps: 5, weight: 20.0),
Exercise(name: 'Press', sets: 3, reps: 5, weight: 15.0),
@ -173,179 +155,4 @@ void main() {
await _pump(tester, _wrap(type: 'B'));
expect(find.textContaining('Workout B'), findsOneWidget);
});
// Interaction taps trigger `unawaited(_saveActiveSession())` (a sqflite write)
// and start `Timer.periodic` breaks. Dispatching them inside runAsync keeps
// those on the real loop, so they complete/cancel instead of lingering as
// FakeAsync "pending timers" that fail the test.
Future<void> _tapReal(WidgetTester tester, Finder f) async {
await tester.runAsync(() async {
await tester.tap(f);
await Future<void>.delayed(const Duration(milliseconds: 100));
});
await tester.pump();
}
// tester.longPress() does internal fake-clock pumps that conflict with
// runAsync, so drive a manual gesture whose hold exceeds the long-press
// timeout on the real clock (keeping the resulting DB write on the real loop).
Future<void> _longPressReal(WidgetTester tester, Finder f) async {
final center = tester.getCenter(f);
await tester.runAsync(() async {
final gesture = await tester.startGesture(center);
await Future<void>.delayed(const Duration(milliseconds: 700));
await gesture.up();
await Future<void>.delayed(const Duration(milliseconds: 100));
});
await tester.pump();
}
testWidgets('tapping a set starts a break which Skip cancels', (tester) async {
await _pump(tester, _wrap());
await _tapReal(tester, find.byType(RepCircle).first);
expect(find.byType(BreakBanner), findsOneWidget);
// Success break (5 done >= 5 target).
expect(find.textContaining('well done'), findsOneWidget);
await _tapReal(tester, find.text('Skip'));
expect(find.byType(BreakBanner), findsNothing);
});
testWidgets('tapping warmup starts a warmup break', (tester) async {
await _pump(tester, _wrap());
await _tapReal(tester, find.byIcon(Icons.fitness_center).first);
expect(find.textContaining('Warmup rest'), findsOneWidget);
});
testWidgets('re-tapping a set decrements reps and recomputes the break',
(tester) async {
await _pump(tester, _wrap());
final circle = find.byType(RepCircle).first;
await _tapReal(tester, circle); // done=5 -> success break
expect(find.textContaining('well done'), findsOneWidget);
await _tapReal(tester, circle); // done 5 -> 4, below target -> fail break
expect(find.textContaining('keep going'), findsOneWidget);
});
testWidgets('long-pressing a set resets it and cancels its break',
(tester) async {
await _pump(tester, _wrap());
final circle = find.byType(RepCircle).first;
await _tapReal(tester, circle);
expect(find.byType(BreakBanner), findsOneWidget);
await _longPressReal(tester, circle);
expect(find.byType(BreakBanner), findsNothing);
});
testWidgets('finishing a completed workout saves and shows the summary',
(tester) async {
await _pump(tester, _wrap(savedState: _completeSaved()));
// Drive the whole flow on the real loop: _confirmFinish's showDialog await
// resumes into _finishWorkout in the same zone, and _finishWorkout does
// several sqflite writes that would hang under FakeAsync.
await tester.runAsync(() async {
await tester.tap(find.widgetWithText(TextButton, 'Finish'));
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pump();
expect(find.text('Finish workout?'), findsOneWidget);
// The dialog's Finish button is the last 'Finish' in the tree.
await tester.tap(find.widgetWithText(TextButton, 'Finish').last);
await Future<void>.delayed(const Duration(milliseconds: 800));
await tester.pump();
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(find.byType(WorkoutSummaryDialog), findsOneWidget);
});
testWidgets('confirming Reset clears the active session', (tester) async {
await tester.runAsync(
() => StorageService.instance.saveActiveSession({
'workoutType': 'A',
'startTimeMs': DateTime.now().millisecondsSinceEpoch,
'tapped': [
[false, false, false],
[false, false, false],
],
'doneReps': [
[5, 5, 5],
[5, 5, 5],
],
'warmupTapped': [false, false],
}),
);
await _pump(tester, _wrap());
// Opening the confirm dialog does no DB work.
await tester.tap(find.text('Reset'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(find.text('Reset workout?'), findsOneWidget);
// Confirm: clearActiveSession is a DB write, so run on the real loop.
// (The dialog's Reset button is the last 'Reset' in the tree.)
await tester.runAsync(() async {
await tester.tap(find.widgetWithText(TextButton, 'Reset').last);
await Future<void>.delayed(const Duration(milliseconds: 300));
});
await tester.pump();
final session = await tester.runAsync(
() => StorageService.instance.loadActiveSession(),
);
expect(session, isNull); // reset cleared the persisted session
});
testWidgets('changing a threshold in the workout persists it', (tester) async {
// A real exercise has a progression-state row, so _onThresholdChanged's
// state-update branch runs (and the write actually lands).
final name = workoutA.first.name;
await _pump(tester, _wrap(exercises: [workoutA.first]));
// The success stepper's "+" is the first Icons.add in the single tile.
await _tapReal(tester, find.byIcon(Icons.add).first);
final state = await tester.runAsync(
() => StorageService.instance.getExerciseState(name),
);
expect(state!.successThreshold, 4); // default 3 -> +1
});
testWidgets('restores an in-progress break and finishes it', (tester) async {
final now = DateTime.now();
final saved = {
'workoutType': 'A',
'startTimeMs': now.millisecondsSinceEpoch,
'tapped': [
[true, false, false],
[false, false, false],
],
'doneReps': [
[5, 5, 5],
[5, 5, 5],
],
'warmupTapped': [false, false],
'breakForExIdx': 0,
'breakForSetIdx': 0,
'breakLabel': 'Rest',
'breakDurationSecs': 180,
'breakEndMs': now.add(const Duration(seconds: 2)).millisecondsSinceEpoch,
};
await _pump(tester, _wrap(savedState: saved));
expect(find.byType(BreakBanner), findsOneWidget); // break restored
// The break timer is a real periodic timer (initState ran under _pump's
// runAsync). Wait out its ~2s remaining so _tickBreak reaches 0 and
// _onBreakFinished (sound + vibration) runs on the real loop.
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(seconds: 3));
await tester.pump();
});
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(find.byType(BreakBanner), findsNothing);
});
}

View File

@ -1,5 +1,3 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/http_server_service.dart';
@ -42,34 +40,5 @@ void main() {
test('kWorkoutServerPort has expected value', () {
expect(kWorkoutServerPort, 8765);
});
test('start swallows a bind failure when the port is taken', () async {
final blocker = await ServerSocket.bind(
InternetAddress.anyIPv4,
kWorkoutServerPort,
);
// Binding fails (SocketException) but start() must not throw.
await HttpServerService.instance.start();
await blocker.close();
});
test('serves the latest workout over HTTP', () async {
HttpServerService.instance.resetForTesting();
await HttpServerService.instance.start();
final client = HttpClient();
Future<int> get(String path) async {
final req = await client.get('localhost', kWorkoutServerPort, path);
final resp = await req.close();
await resp.drain<void>();
return resp.statusCode;
}
expect(await get('/workout'), 404); // no data yet
HttpServerService.instance.latestWorkout = '{"workout_type":"A"}';
expect(await get('/workout'), 200);
expect(await get('/other'), 404); // unknown path
client.close();
});
});
}

View File

@ -1,10 +1,6 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/storage_service.dart';
StorageService get _svc => StorageService.instance;
@ -320,159 +316,4 @@ void main() {
final b = await StorageService.init();
expect(identical(a, b), isTrue);
});
// ── Schema migration (v1 → v3) ──────────────────────────────────────────────
test('migrates a v1 database up to v3 on open', () async {
// A v1 DB predates the threshold columns and the settings/active_session
// tables — build one on disk, then open it through StorageService (v3) so
// _migrateSchema runs both the <2 and <3 upgrade blocks.
final dir = await Directory.systemTemp.createTemp('mw_migrate');
final dbFile = p.join(dir.path, 'old.db');
final oldDb = await databaseFactory.openDatabase(
dbFile,
options: OpenDatabaseOptions(
version: 1,
onCreate: (db, _) async {
await db.execute(
'CREATE TABLE exercise_state ('
'name TEXT PRIMARY KEY, weight REAL NOT NULL, reps INTEGER NOT NULL, '
'success_streak INTEGER NOT NULL DEFAULT 0, '
'fail_streak INTEGER NOT NULL DEFAULT 0, max_weight REAL NOT NULL)',
);
},
),
);
await oldDb.close();
StorageService.resetForTesting(dbPath: dbFile);
await StorageService.init();
// <3 block created the settings table (getNextWorkoutType reads it) …
expect(await _svc.getNextWorkoutType(), 'A');
// … and the <2 block added the threshold columns (defaulted to 3/2).
final st = await _svc.getExerciseState(workoutA.first.name);
expect(st, isNotNull);
expect(st!.successThreshold, 3);
expect(st.failThreshold, 2);
await dir.delete(recursive: true);
});
// ── Progression at the weight cap ───────────────────────────────────────────
test('applyProgression bumps reps (not weight) once at max weight', () async {
final name = workoutA.first.name;
final maxW = (await _svc.getExerciseState(name))!.maxWeight;
// Pin the working weight at the cap; streaks reset to 0.
await _svc.setExerciseWeight(name, maxW);
final startReps = (await _svc.getExerciseState(name))!.reps;
// Default success threshold is 3 — three straight successes trigger a
// progression, which at the cap increments reps instead of weight.
final today = DateTime.now();
for (var i = 0; i < 3; i++) {
await _svc.applyProgression(
succeededExercises: {name: true},
lastWorkoutDate: today,
);
}
final st = (await _svc.getExerciseState(name))!;
expect(st.weight, maxW); // weight stayed capped
expect(st.reps, startReps + 1); // reps incremented instead
});
// ── Restore from backup ─────────────────────────────────────────────────────
group('restoreFromBackupIfNeeded', () {
late Directory tmp;
setUp(() {
tmp = Directory.systemTemp.createTempSync('mw_restore');
BackupService.baseDirForTesting = tmp.path;
});
tearDown(() {
BackupService.baseDirForTesting = kBackupDir;
tmp.deleteSync(recursive: true);
});
test('returns early and does not restore when the DB has data', () async {
await _svc.saveSession(
date: '2026-07-10',
workoutType: 'A',
durationSeconds: 60,
succeeded: true,
json: '{}',
);
// A backup that would add a second history row if (wrongly) applied.
await BackupService.instance.export({
'workout_history': [
{
'date': '2000-01-01',
'workout_type': 'B',
'duration_seconds': 1,
'succeeded': 0,
'json': '{}',
},
],
});
await _svc.restoreFromBackupIfNeeded();
// Early-return path: existing history is untouched, backup ignored.
final hist = await _svc.getWorkoutHistory();
expect(hist.length, 1);
expect(hist.first['date'], '2026-07-10');
});
test('restores exercise_state, history and settings when empty', () async {
await BackupService.instance.export({
'exercise_state': [
{
'name': 'Dumbbell Lunge',
'weight': 42.5,
'reps': 9,
'success_streak': 0,
'fail_streak': 0,
'max_weight': 100.0,
'success_threshold': 3,
'fail_threshold': 2,
},
],
'workout_history': [
{
'date': '2026-07-01',
'workout_type': 'A',
'duration_seconds': 120,
'succeeded': 1,
'json': '{}',
},
],
'settings': [
{'key': 'last_workout_type', 'value': 'A'},
],
});
await _svc.restoreFromBackupIfNeeded();
// Settings restored: last was A → next is B.
expect(await _svc.getNextWorkoutType(), 'B');
// History restored.
final hist = await _svc.getWorkoutHistory();
expect(hist.length, 1);
expect(hist.first['date'], '2026-07-01');
// Exercise state overwritten from the backup.
final st = await _svc.getExerciseState('Dumbbell Lunge');
expect(st!.weight, 42.5);
});
test('does nothing when the DB is empty and no backup exists', () async {
// No export() call → readBackup returns null → early return after the
// has-data check.
await _svc.restoreFromBackupIfNeeded();
expect(await _svc.getWorkoutHistory(), isEmpty);
});
});
}

View File

@ -63,7 +63,7 @@ void main() {
// The HTTP server must be updated regardless of file write success.
expect(
HttpServerService.instance.latestWorkout,
contains('"workout_type": "A"'),
contains('"workout_type":"A"'),
);
});

View File

@ -145,137 +145,4 @@ void main() {
completes,
);
});
Record _manual(String id, String cost, int wallMs) => Record(
id: id,
fields: {
'payload': (
{'kind': 'manual_workout', 'date': '2026-07-13', 'cost': cost},
Hlc(wallTimeMs: wallMs, counter: 0, nodeId: 'phone'),
),
},
);
test('pushManual does nothing without a token', () async {
installFakeSecureStorage();
final (:httpClient, :putCalls) = _mockGitHub();
await WorkoutSyncService(
httpClient: httpClient,
).pushManual(_manual('manual:x', '40', 1000));
expect(putCalls, isEmpty);
});
test('pushManual pushes when nothing has been synced yet', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final (:httpClient, :putCalls) = _mockGitHub(
contentResponses: {'screen-locker-sync/devices': _response(200, [])},
);
await WorkoutSyncService(
httpClient: httpClient,
).pushManual(_manual('manual:2026-07-13T18:00', '40', 1000));
expect(putCalls.single.path, 'screen-locker-sync/devices/phone/log.json');
});
test('pushManual merges onto an existing log', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final existing = jsonEncode({
'manual:old': _manual('manual:old', '20', 1000).toJson(),
});
final (:httpClient, :putCalls) = _mockGitHub(
contentResponses: {
'screen-locker-sync/devices': _response(200, []),
'screen-locker-sync/devices/phone/log.json': _fileContaining(existing),
},
);
await WorkoutSyncService(
httpClient: httpClient,
).pushManual(_manual('manual:2026-07-13T18:00', '40', 2000));
final pushedLog =
jsonDecode(
utf8.decode(
base64.decode(putCalls.single.body['content'] as String),
),
)
as Map<String, dynamic>;
expect(
pushedLog.keys,
containsAll(['manual:old', 'manual:2026-07-13T18:00']),
);
});
test('pushManual swallows a sync error', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final httpClient = http_testing.MockClient(
(request) async => http.Response('', 500),
);
await expectLater(
WorkoutSyncService(
httpClient: httpClient,
).pushManual(_manual('manual:x', '40', 1000)),
completes,
);
});
test('readMergedManualPayloads is empty without a token', () async {
installFakeSecureStorage();
final (:httpClient, putCalls: _) = _mockGitHub();
expect(
await WorkoutSyncService(
httpClient: httpClient,
).readMergedManualPayloads(),
isEmpty,
);
});
test('readMergedManualPayloads merges manuals and skips the rest', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final session = Record(
id: 's',
fields: {
'payload': ({'workout_type': 'A'}, Hlc(wallTimeMs: 1000, counter: 0, nodeId: 'phone')),
},
);
final noPayload = Record(
id: 'np',
fields: {'other': (1, Hlc(wallTimeMs: 1000, counter: 0, nodeId: 'phone'))},
);
final phoneLog = jsonEncode({
'manual:a': _manual('manual:a', 'NEW', 2000).toJson(),
's': session.toJson(),
'np': noPayload.toJson(),
});
final pcLog = jsonEncode({
// Same id, older clock -> must lose to phone's newer copy.
'manual:a': _manual('manual:a', 'OLD', 1000).toJson(),
});
final (:httpClient, putCalls: _) = _mockGitHub(
contentResponses: {
'screen-locker-sync/devices': _response(200, [
{'name': 'phone'},
{'name': 'pc'},
{'name': 'empty'}, // its log.json 404s -> skipped
]),
'screen-locker-sync/devices/phone/log.json': _fileContaining(phoneLog),
'screen-locker-sync/devices/pc/log.json': _fileContaining(pcLog),
},
);
final payloads = await WorkoutSyncService(
httpClient: httpClient,
).readMergedManualPayloads();
expect(payloads, hasLength(1));
expect(payloads.single['cost'], 'NEW');
});
test('readMergedManualPayloads swallows a sync error', () async {
installFakeSecureStorage(initial: {'sync.token': 'tok'});
final httpClient = http_testing.MockClient(
(request) async => http.Response('', 500),
);
expect(
await WorkoutSyncService(
httpClient: httpClient,
).readMergedManualPayloads(),
isEmpty,
);
});
}

View File

@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/main.dart';
import 'package:workout_app/services/http_server_service.dart';
import 'package:workout_app/services/storage_service.dart';
void main() {
@ -24,24 +23,4 @@ void main() {
await tester.pump();
expect(find.text('Workout Tracker'), findsOneWidget);
});
testWidgets('app-lifecycle changes drive the HTTP server', (tester) async {
await tester.runAsync(() async {
await tester.pumpWidget(const WorkoutApp());
await Future<void>.delayed(const Duration(milliseconds: 100));
// A valid forward transition path that visits every handled state.
for (final state in const [
AppLifecycleState.resumed,
AppLifecycleState.inactive,
AppLifecycleState.hidden,
AppLifecycleState.paused,
AppLifecycleState.detached,
]) {
tester.binding.handleAppLifecycleStateChanged(state);
await Future<void>.delayed(const Duration(milliseconds: 5));
}
await HttpServerService.instance.stop();
});
await tester.pump();
});
}