Fix run-mode gates: logs, file caps, coverage

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZB8QEaFVQoa8CjuAw
This commit is contained in:
Krzysztof Rudnicki 2026-11-17 22:35:32 +01:00
parent 2137152729
commit 9ba2f46c23
16 changed files with 614 additions and 481 deletions

View File

@ -163,6 +163,10 @@ while IFS= read -r dart_file; do
# whitespace, so a wrapped `export 'x' if (...) 'y';` statement (the
# platform-gate barrel shape) becomes matchable on one logical line
# regardless of how it's line-wrapped in source.
# A file that opts out wholesale is dropped from lcov by flutter itself.
if grep -qE '^// coverage:ignore-file' "$dart_file"; then
continue
fi
code_only=$(grep -vE '^[[:space:]]*(///|//|$)' "$dart_file" | tr '\n' ' ' | tr -s ' ')
if [[ $code_only =~ $barrel_pattern ]]; then
continue

View File

@ -97,6 +97,7 @@ class FileRunCheckpointStore implements RunCheckpointStore {
}
return RunCheckpoint.fromJson(json);
} on FormatException catch (e) {
log('RunCheckpointStore: corrupt checkpoint (${e.message})', level: 1000);
await _moveAside(e);
return null;
}

View File

@ -60,6 +60,7 @@ extension RunRecorderPersistence on RunRecorder {
);
return true;
} on Object catch (e, stack) {
debugPrint('RunRecorder: restore failed ($e)');
logRestoreFailed(e, stack);
await _sub?.cancel();
_sub = null;

View File

@ -134,6 +134,7 @@ class RunView extends ChangeNotifier {
await completer.future.timeout(timeout);
return true;
} on TimeoutException {
debugPrint('RunView: condition not met within $timeout');
return false;
} finally {
removeListener(check);

View File

@ -54,11 +54,11 @@ class FakeStore implements RunCheckpointStore {
int clears = 0;
/// Makes [save] throw.
bool failSave = false;
bool saveFails = false;
@override
Future<void> save(RunCheckpoint c) async {
if (failSave) throw Exception('disk full');
if (saveFails) throw Exception('disk full');
saves++;
held = c;
}

View File

@ -0,0 +1,74 @@
/// Shared rig of the run recorder persistence tests.
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'run_test_fixtures.dart';
final DateTime persistT0 = DateTime.utc(2026, 11, 9, 12);
/// A recorder plus everything it reports, on a clock the test moves.
class PersistHost {
PersistHost({
ManualPositionSource? source,
DateTime? at,
Duration autoEnd = const Duration(hours: 5),
}) : source = source ?? ManualPositionSource(),
now = at ?? persistT0 {
recorder = RunRecorder(
sourceFor: () => this.source,
onKilometre: km.add,
onSuggestFinish: suggestions.add,
onAutoEnd: () => autoEnds++,
onCheckpoint: checkpoints.add,
clock: () => now,
autoEndAfter: autoEnd,
);
}
final ManualPositionSource source;
late final RunRecorder recorder;
DateTime now;
final km = <int>[];
final suggestions = <RunSuggestion>[];
final checkpoints = <RunCheckpoint>[];
int autoEnds = 0;
/// Finishes inside `testWidgets`, where awaiting a stream cancel hangs the
/// fake-async zone: it runs in the real one instead.
Future<RunTrack?> finishAfter(WidgetTester tester) async =>
await tester.runAsync<RunTrack?>(recorder.finish);
/// Delivers [fixes]; inside `testWidgets` pass the tester, whose pump
/// drains the queue where a real-time `pumpEventQueue` would hang.
Future<void> feed(Iterable<GpsFix> fixes, {WidgetTester? tester}) async {
for (final fix in fixes) {
source.controller.add(fix);
}
await (tester?.pump() ?? pumpEventQueue());
}
}
RunCheckpoint viaJson(RunCheckpoint c) => RunCheckpoint.fromJson(
jsonDecode(jsonEncode(c.toJson())) as Map<String, Object?>,
);
Future<RunCheckpoint> checkpointAfter(int fixes, {bool pause = false}) async {
final h = PersistHost();
await h.recorder.start();
await h.feed(straightRun(fixes));
if (pause) h.recorder.pause();
final c = h.recorder.checkpoint()!;
await h.recorder.finish();
h.recorder.dispose();
return viaJson(c);
}
class ThrowingSource extends ManualPositionSource {
@override
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) =>
throw StateError('provider gone');
}

View File

@ -0,0 +1,46 @@
/// Shared rig of the run watchdog tests.
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_watchdog.dart';
import 'run_test_fixtures.dart';
final DateTime watchdogStart = DateTime.utc(2026, 11, 9, 12);
class WatchdogRig {
WatchdogRig({this.autoEnd = const Duration(hours: 5)}) {
dog = RunWatchdog(
clock: () => now,
onSuggest: suggestions.add,
onAutoEnd: () => autoEnds++,
autoEndAfter: autoEnd,
);
}
final Duration autoEnd;
late final RunWatchdog dog;
DateTime now = watchdogStart;
final suggestions = <RunSuggestion>[];
int autoEnds = 0;
double metres = 0;
void advance(Duration d) {
now = now.add(d);
dog.check();
}
/// [minutes] minutes with a fresh, motionless fix every minute.
void idle(int minutes) {
for (var i = 0; i < minutes; i++) {
now = now.add(const Duration(minutes: 1));
fix();
dog.check();
}
}
/// An accepted fix at the current clock, [stepM] further on.
void fix({double stepM = 0, int secondsIntoRun = 0}) {
metres += stepM;
dog.onFix(fixAt(secondsIntoRun, metres), FixVerdict.accepted, metres);
}
}

View File

@ -0,0 +1,90 @@
// The run outlives the screen: nothing but the finish button plus its confirm
// modal ends it. Checks (a) leaving or replacing the screen never stops an
// active run, (b) finishing needs the modal's red check, (c) the app opens on
// the live run.
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_landing.dart';
import '../fake_audio_platform.dart';
import '../run_persist_rig.dart';
import '_run_screen_helpers.dart';
void main() {
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
installFakeAudioPlatform();
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
StorageService.resetForTesting();
await StorageService.init();
});
Future<void> startRun(WidgetTester tester, PersistRig rig) async {
await tapKey(tester, 'run_start');
rig.engine.addFix();
await tester.pumpAndSettle();
}
group('(c) the app opens on the run', () {
testWidgets('coming back to the front lands on the run again', (
tester,
) async {
final rig = PersistRig();
RunScreen.defaultControllerFactory = rig.build;
addTearDown(() => RunScreen.defaultControllerFactory = null);
await rig.host.cmd('start');
var owed = false;
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: RunLanding(
owed: () async => owed,
child: const SizedBox(key: Key('home')),
),
),
);
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsNothing);
owed = true;
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsOneWidget);
// Already on the run: another resume does not stack a second one.
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsOneWidget);
});
testWidgets('with no run owed home stays home', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: RunLanding(
owed: () async => false,
child: const SizedBox(key: Key('home')),
),
),
);
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
expect(key('home'), findsOneWidget);
});
});
}

View File

@ -233,55 +233,4 @@ void main() {
},
);
});
group('(c) the app opens on the run', () {
testWidgets('coming back to the front lands on the run again', (
tester,
) async {
final rig = PersistRig();
RunScreen.defaultControllerFactory = rig.build;
addTearDown(() => RunScreen.defaultControllerFactory = null);
await rig.host.cmd('start');
var owed = false;
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: RunLanding(
owed: () async => owed,
child: const SizedBox(key: Key('home')),
),
),
);
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsNothing);
owed = true;
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsOneWidget);
// Already on the run: another resume does not stack a second one.
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsOneWidget);
});
testWidgets('with no run owed home stays home', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: RunLanding(
owed: () async => false,
child: const SizedBox(key: Key('home')),
),
),
);
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pumpAndSettle();
expect(key('home'), findsOneWidget);
});
});
}

View File

@ -0,0 +1,101 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/foreground_run_client_flutter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/storage_service.dart';
import '../fake_audio_platform.dart';
import '../fake_run_service.dart';
import '../run_controller_rig.dart';
import '../run_test_fixtures.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late FakeAudioRecorder audio;
late List<RunTrack> saved;
setUpAll(() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
});
setUp(() async {
StorageService.resetForTesting();
await StorageService.init();
audio = installFakeAudioPlatform();
saved = [];
});
Future<void> feed(ManualPositionSource source, List<int> northM) async {
for (final (i, m) in northM.indexed) {
source.controller.add(fixAt(i * 2, m.toDouble()));
}
await pumpEventQueue();
await pumpEventQueue();
}
RunController build(
ManualPositionSource source,
FakeForegroundRunClient service,
) => buildRunController(source: source, service: service, saved: saved);
group('the run outlives the controller', () {
test('disposing mid-run never stops the service or the run', () async {
final source = ManualPositionSource();
final service = FakeForegroundRunClient();
final controller = build(source, service);
await controller.start();
await feed(source, [0, 6]);
controller.dispose();
expect(service.calls, isNot(contains('stop')));
expect(saved, isEmpty);
// The fix stream is still being listened to.
source.controller.add(fixAt(4, 12));
await pumpEventQueue();
});
test('a second start while a run is going changes nothing', () async {
final source = ManualPositionSource();
final service = FakeForegroundRunClient();
final controller = build(source, service);
await controller.start();
await controller.start();
expect(service.starts, hasLength(1));
expect(source.subscriptions, 1);
controller.dispose();
});
test('attach gives up when no host ever answers', () async {
final controller = buildSilentController();
await controller.attach();
expect(controller.attachGaveUp, isTrue);
expect(controller.view.synced, isFalse);
controller.dispose();
});
test('a start nobody answers times out loudly, run untouched', () async {
final controller = buildSilentController();
await controller.start();
expect(controller.active, isFalse);
controller.dispose();
});
test('a pace target change and an ack are commands', () async {
final source = ManualPositionSource();
final controller = build(source, FakeForegroundRunClient());
await controller.start(paceTarget: 330);
expect(controller.view.paceTarget, 330);
controller
..setPaceTarget(300)
..ackPrompt();
await pumpEventQueue();
expect(controller.view.paceTarget, 300);
controller.dispose();
});
});
}

View File

@ -211,62 +211,6 @@ void main() {
controller.dispose();
});
group('the run outlives the controller', () {
test('disposing mid-run never stops the service or the run', () async {
final source = ManualPositionSource();
final service = FakeForegroundRunClient();
final controller = build(source, service);
await controller.start();
await feed(source, [0, 6]);
controller.dispose();
expect(service.calls, isNot(contains('stop')));
expect(saved, isEmpty);
// The fix stream is still being listened to.
source.controller.add(fixAt(4, 12));
await pumpEventQueue();
});
test('a second start while a run is going changes nothing', () async {
final source = ManualPositionSource();
final service = FakeForegroundRunClient();
final controller = build(source, service);
await controller.start();
await controller.start();
expect(service.starts, hasLength(1));
expect(source.subscriptions, 1);
controller.dispose();
});
test('attach gives up when no host ever answers', () async {
final controller = buildSilentController();
await controller.attach();
expect(controller.attachGaveUp, isTrue);
expect(controller.view.synced, isFalse);
controller.dispose();
});
test('a start nobody answers times out loudly, run untouched', () async {
final controller = buildSilentController();
await controller.start();
expect(controller.active, isFalse);
controller.dispose();
});
test('a pace target change and an ack are commands', () async {
final source = ManualPositionSource();
final controller = build(source, FakeForegroundRunClient());
await controller.start(paceTarget: 330);
expect(controller.view.paceTarget, 330);
controller
..setPaceTarget(300)
..ackPrompt();
await pumpEventQueue();
expect(controller.view.paceTarget, 300);
controller.dispose();
});
});
test('the real client is unsupported off Android', () {
expect(FlutterForegroundRunClient().isSupported, isFalse);
expect(kRunOngoingChannelId, endsWith('_v1'));

View File

@ -0,0 +1,146 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_wire.dart';
import '../fake_audio_platform.dart';
import '../fake_run_engine.dart';
import '../run_host_rig.dart';
void main() {
setUp(installFakeAudioPlatform);
group('suggestions never end the run', () {
test('cue, glyph in the notification, run keeps recording', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine.addFix();
rig.lastHooks.onSuggest('stationary');
await pumpEventQueue();
expect(rig.cues.suggestions, 1);
expect(rig.engine.phase, RunPhase.recording);
expect(rig.port.last['suggestion'], 'stationary');
expect(rig.port.notes.last, startsWith('⏸ '));
expect(rig.saved, isEmpty);
expect(rig.port.stops, 0);
});
test('each reason has its own symbol', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
for (final (why, glyph) in [
('vehicleSpeed', '⚡'),
('gpsLost', '⌖'),
('restored', '↻'),
]) {
rig.lastHooks.onSuggest(why);
rig.engine.addFix();
expect(rig.port.notes.last, startsWith('$glyph '), reason: why);
}
});
test('a tap on the notification asks for the finish modal', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.lastHooks.onSuggest('gpsLost');
rig.host.notificationPressed();
expect(rig.port.launches, 1);
expect(rig.port.last['prompt'], isTrue);
expect(rig.engine.phase, RunPhase.recording, reason: 'still needs a tap');
await rig.cmd(RunCmd.ackPrompt);
expect(rig.port.last['prompt'], isFalse);
expect(rig.port.last['suggestion'], 'gpsLost');
});
test('a tap with no advice only opens the app', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.host.notificationPressed();
expect(rig.port.launches, 1);
expect(rig.port.last['prompt'], isFalse);
});
test('advice while finishing is dropped', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
final finishing = rig.cmd(RunCmd.finish);
rig.lastHooks.onSuggest('stationary');
await finishing;
expect(rig.cues.suggestions, 0);
});
});
group('5 h auto end', () {
test('saves like a finish and plays its own cue', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine.addFix();
rig.lastHooks.onAutoEnd();
await pumpEventQueue();
expect(rig.saved, hasLength(1));
expect(rig.cues.autoEnds, 1);
expect(rig.cues.finishes, 0);
expect(rig.store.held, isNull);
expect(rig.port.stops, 1);
});
});
group('hooks', () {
test('kilometres and pace cues reach the cues', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.lastHooks.onKilometre(1);
await pumpEventQueue();
expect(rig.cues.kilometres, [1]);
});
});
group('restoreFromStore', () {
test('false with no checkpoint, and no engine is built', () async {
final rig = HostRig();
expect(await rig.host.restoreFromStore(), isFalse);
expect(rig.engines, isEmpty);
});
test('resumes the run and tells the UI', () async {
final rig = HostRig();
rig.store.held = FakeCheckpoint(7);
expect(await rig.host.restoreFromStore(), isTrue);
expect(rig.engine.restored.single, isA<FakeCheckpoint>());
expect(rig.port.last['phase'], 'recording');
});
test(
'a checkpoint that cannot resume is kept and the issue shown',
() async {
final rig = HostRig()..restoreResult = false;
rig.store.held = FakeCheckpoint(7);
expect(await rig.host.restoreFromStore(), isTrue);
expect(rig.store.held, isNotNull);
expect(rig.port.last['issue'], 'streamError');
},
);
});
test('unknown commands are ignored', () async {
final rig = HostRig();
await rig.cmd('nonsense');
expect(rig.engines, isEmpty);
expect(rig.port.sent, isEmpty);
});
test('dispose lets go without ending anything', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.host.dispose();
expect(rig.engine.disposed, isTrue);
expect(rig.saved, isEmpty);
expect(rig.store.clears, 0);
rig.host.dispose();
});
}

View File

@ -109,7 +109,7 @@ void main() {
test('a failed checkpoint write is logged, not fatal', () async {
final rig = HostRig();
rig.store.failSave = true;
rig.store.saveFails = true;
await rig.cmd(RunCmd.start);
rig.engine.addFix();
await pumpEventQueue();
@ -191,139 +191,4 @@ void main() {
expect(rig.saved, hasLength(1));
});
});
group('suggestions never end the run', () {
test('cue, glyph in the notification, run keeps recording', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine.addFix();
rig.lastHooks.onSuggest('stationary');
await pumpEventQueue();
expect(rig.cues.suggestions, 1);
expect(rig.engine.phase, RunPhase.recording);
expect(rig.port.last['suggestion'], 'stationary');
expect(rig.port.notes.last, startsWith('⏸ '));
expect(rig.saved, isEmpty);
expect(rig.port.stops, 0);
});
test('each reason has its own symbol', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
for (final (why, glyph) in [
('vehicleSpeed', '⚡'),
('gpsLost', '⌖'),
('restored', '↻'),
]) {
rig.lastHooks.onSuggest(why);
rig.engine.addFix();
expect(rig.port.notes.last, startsWith('$glyph '), reason: why);
}
});
test('a tap on the notification asks for the finish modal', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.lastHooks.onSuggest('gpsLost');
rig.host.notificationPressed();
expect(rig.port.launches, 1);
expect(rig.port.last['prompt'], isTrue);
expect(rig.engine.phase, RunPhase.recording, reason: 'still needs a tap');
await rig.cmd(RunCmd.ackPrompt);
expect(rig.port.last['prompt'], isFalse);
expect(rig.port.last['suggestion'], 'gpsLost');
});
test('a tap with no advice only opens the app', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.host.notificationPressed();
expect(rig.port.launches, 1);
expect(rig.port.last['prompt'], isFalse);
});
test('advice while finishing is dropped', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
final finishing = rig.cmd(RunCmd.finish);
rig.lastHooks.onSuggest('stationary');
await finishing;
expect(rig.cues.suggestions, 0);
});
});
group('5 h auto end', () {
test('saves like a finish and plays its own cue', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.engine.addFix();
rig.lastHooks.onAutoEnd();
await pumpEventQueue();
expect(rig.saved, hasLength(1));
expect(rig.cues.autoEnds, 1);
expect(rig.cues.finishes, 0);
expect(rig.store.held, isNull);
expect(rig.port.stops, 1);
});
});
group('hooks', () {
test('kilometres and pace cues reach the cues', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.lastHooks.onKilometre(1);
await pumpEventQueue();
expect(rig.cues.kilometres, [1]);
});
});
group('restoreFromStore', () {
test('false with no checkpoint, and no engine is built', () async {
final rig = HostRig();
expect(await rig.host.restoreFromStore(), isFalse);
expect(rig.engines, isEmpty);
});
test('resumes the run and tells the UI', () async {
final rig = HostRig();
rig.store.held = FakeCheckpoint(7);
expect(await rig.host.restoreFromStore(), isTrue);
expect(rig.engine.restored.single, isA<FakeCheckpoint>());
expect(rig.port.last['phase'], 'recording');
});
test(
'a checkpoint that cannot resume is kept and the issue shown',
() async {
final rig = HostRig()..restoreResult = false;
rig.store.held = FakeCheckpoint(7);
expect(await rig.host.restoreFromStore(), isTrue);
expect(rig.store.held, isNotNull);
expect(rig.port.last['issue'], 'streamError');
},
);
});
test('unknown commands are ignored', () async {
final rig = HostRig();
await rig.cmd('nonsense');
expect(rig.engines, isEmpty);
expect(rig.port.sent, isEmpty);
});
test('dispose lets go without ending anything', () async {
final rig = HostRig();
await rig.cmd(RunCmd.start);
rig.host.dispose();
expect(rig.engine.disposed, isTrue);
expect(rig.saved, isEmpty);
expect(rig.store.clears, 0);
rig.host.dispose();
});
}

View File

@ -7,71 +7,13 @@ import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_recorder.dart';
import '../run_recorder_persist_rig.dart';
import '../run_test_fixtures.dart';
final DateTime _t0 = DateTime.utc(2026, 11, 9, 12);
/// A recorder plus everything it reports, on a clock the test moves.
class _Host {
_Host({
ManualPositionSource? source,
DateTime? at,
Duration autoEnd = const Duration(hours: 5),
}) : source = source ?? ManualPositionSource(),
now = at ?? _t0 {
recorder = RunRecorder(
sourceFor: () => this.source,
onKilometre: km.add,
onSuggestFinish: suggestions.add,
onAutoEnd: () => autoEnds++,
onCheckpoint: checkpoints.add,
clock: () => now,
autoEndAfter: autoEnd,
);
}
final ManualPositionSource source;
late final RunRecorder recorder;
DateTime now;
final km = <int>[];
final suggestions = <RunSuggestion>[];
final checkpoints = <RunCheckpoint>[];
int autoEnds = 0;
/// Finishes inside `testWidgets`, where awaiting a stream cancel hangs the
/// fake-async zone: it runs in the real one instead.
Future<RunTrack?> finishIn(WidgetTester tester) async =>
await tester.runAsync<RunTrack?>(recorder.finish);
/// Delivers [fixes]; inside `testWidgets` pass the tester, whose pump
/// drains the queue where a real-time `pumpEventQueue` would hang.
Future<void> feed(Iterable<GpsFix> fixes, {WidgetTester? tester}) async {
for (final fix in fixes) {
source.controller.add(fix);
}
await (tester?.pump() ?? pumpEventQueue());
}
}
RunCheckpoint _viaJson(RunCheckpoint c) => RunCheckpoint.fromJson(
jsonDecode(jsonEncode(c.toJson())) as Map<String, Object?>,
);
Future<RunCheckpoint> _checkpointAfter(int fixes, {bool pause = false}) async {
final h = _Host();
await h.recorder.start();
await h.feed(straightRun(fixes));
if (pause) h.recorder.pause();
final c = h.recorder.checkpoint()!;
await h.recorder.finish();
h.recorder.dispose();
return _viaJson(c);
}
void main() {
group('checkpoint()', () {
test('is null when idle and after finish', () async {
final h = _Host();
final h = PersistHost();
expect(h.recorder.checkpoint(), isNull);
await h.recorder.start();
expect(h.recorder.checkpoint(), isNotNull);
@ -81,12 +23,12 @@ void main() {
});
test('holds the whole recording state', () async {
final h = _Host(at: _t0.add(const Duration(minutes: 3)));
final h = PersistHost(at: persistT0.add(const Duration(minutes: 3)));
await h.recorder.start();
h.recorder.setPaceTarget(330);
await h.feed(straightRun(10));
final c = h.recorder.checkpoint()!;
expect(c.startedAt, _t0.add(const Duration(minutes: 3)));
expect(c.startedAt, persistT0.add(const Duration(minutes: 3)));
expect(c.savedAt, h.now);
expect(c.phase, RunPhase.recording);
expect(c.points, hasLength(10));
@ -99,7 +41,7 @@ void main() {
});
test('a pause is recorded with its segment break', () async {
final c = await _checkpointAfter(5, pause: true);
final c = await checkpointAfter(5, pause: true);
expect(c.phase, RunPhase.paused);
expect(c.segmentBreak, isTrue);
});
@ -107,7 +49,7 @@ void main() {
group('onCheckpoint', () {
test('fires on start, every accepted fix, pause and resume', () async {
final h = _Host();
final h = PersistHost();
await h.recorder.start();
expect(h.checkpoints, hasLength(1));
await h.feed(straightRun(3));
@ -130,8 +72,8 @@ void main() {
group('restore()', () {
test('re-enters recording with the state and tells the host', () async {
final saved = await _checkpointAfter(10);
final h = _Host(at: _t0.add(const Duration(minutes: 10)));
final saved = await checkpointAfter(10);
final h = PersistHost(at: persistT0.add(const Duration(minutes: 10)));
expect(await h.recorder.restore(saved), isTrue);
expect(h.recorder.phase, RunPhase.recording);
expect(h.recorder.seconds, 18);
@ -144,8 +86,8 @@ void main() {
});
test('the dead time is bridged and credited at a running pace', () async {
final saved = await _checkpointAfter(10); // last fix: 18 s, 54 m
final h = _Host(at: _t0.add(const Duration(minutes: 10)));
final saved = await checkpointAfter(10); // last fix: 18 s, 54 m
final h = PersistHost(at: persistT0.add(const Duration(minutes: 10)));
await h.recorder.restore(saved);
await h.feed([fixAt(318, 954)]); // 300 s later, 900 m on: 3 m/s
expect(h.recorder.distanceM, closeTo(954, 1));
@ -155,8 +97,8 @@ void main() {
});
test('a vehicle-speed gap is drawn but earns nothing', () async {
final saved = await _checkpointAfter(10);
final h = _Host(at: _t0.add(const Duration(minutes: 10)));
final saved = await checkpointAfter(10);
final h = PersistHost(at: persistT0.add(const Duration(minutes: 10)));
await h.recorder.restore(saved);
await h.feed([fixAt(78, 54 + 600)]); // 60 s, 600 m: 36 km/h
expect(h.recorder.distanceM, closeTo(54, 0.5));
@ -166,15 +108,15 @@ void main() {
});
test('kilometres already announced are not announced again', () async {
final h0 = _Host();
final h0 = PersistHost();
await h0.recorder.start();
await h0.feed(straightRun(340)); // 2 km
final saved = _viaJson(h0.recorder.checkpoint()!);
final saved = viaJson(h0.recorder.checkpoint()!);
expect(h0.km, [1, 2]);
await h0.recorder.finish();
h0.recorder.dispose();
final h = _Host(at: _t0.add(const Duration(hours: 1)));
final h = PersistHost(at: persistT0.add(const Duration(hours: 1)));
await h.recorder.restore(saved);
await h.feed([fixAt(681, 2043)]); // still km 2
expect(h.km, isEmpty);
@ -184,8 +126,8 @@ void main() {
});
test('a paused run comes back paused, ignoring fixes', () async {
final saved = await _checkpointAfter(5, pause: true);
final h = _Host(at: _t0.add(const Duration(minutes: 5)));
final saved = await checkpointAfter(5, pause: true);
final h = PersistHost(at: persistT0.add(const Duration(minutes: 5)));
expect(await h.recorder.restore(saved), isTrue);
expect(h.recorder.phase, RunPhase.paused);
await h.feed([fixAt(300, 900)]);
@ -198,24 +140,24 @@ void main() {
});
test('the pace target comes back', () async {
final h0 = _Host();
final h0 = PersistHost();
await h0.recorder.start();
h0.recorder.setPaceTarget(300);
await h0.feed(straightRun(3));
final saved = _viaJson(h0.recorder.checkpoint()!);
final saved = viaJson(h0.recorder.checkpoint()!);
h0.recorder.dispose();
final h = _Host(at: _t0.add(const Duration(minutes: 1)));
final h = PersistHost(at: persistT0.add(const Duration(minutes: 1)));
await h.recorder.restore(saved);
expect(h.recorder.coach.target, 300);
h.recorder.dispose();
});
test('a run with no fix yet restores and then records', () async {
final h0 = _Host();
final h0 = PersistHost();
await h0.recorder.start();
final saved = _viaJson(h0.recorder.checkpoint()!);
final saved = viaJson(h0.recorder.checkpoint()!);
h0.recorder.dispose();
final h = _Host(at: _t0.add(const Duration(minutes: 1)));
final h = PersistHost(at: persistT0.add(const Duration(minutes: 1)));
expect(await h.recorder.restore(saved), isTrue);
await h.feed(straightRun(3));
expect(h.recorder.livePoints.value, hasLength(3));
@ -225,8 +167,8 @@ void main() {
});
test('finishing a restored run saves one track with the bridge', () async {
final saved = await _checkpointAfter(10);
final h = _Host(at: _t0.add(const Duration(minutes: 10)));
final saved = await checkpointAfter(10);
final h = PersistHost(at: persistT0.add(const Duration(minutes: 10)));
await h.recorder.restore(saved);
await h.feed([fixAt(318, 954), fixAt(320, 960)]);
final track = (await h.recorder.finish())!;
@ -240,9 +182,9 @@ void main() {
test(
'is refused (false, issue set) when location access is gone',
() async {
final saved = await _checkpointAfter(3);
final saved = await checkpointAfter(3);
final source = ManualPositionSource(access: LocationAccess.denied);
final h = _Host(source: source);
final h = PersistHost(source: source);
expect(await h.recorder.restore(saved), isFalse);
expect(h.recorder.phase, RunPhase.idle);
expect(h.recorder.issue, RunIssue.denied);
@ -253,8 +195,8 @@ void main() {
);
test('is false when opening the source throws', () async {
final saved = await _checkpointAfter(3);
final h = _Host(source: _ThrowingSource());
final saved = await checkpointAfter(3);
final h = PersistHost(source: ThrowingSource());
expect(await h.recorder.restore(saved), isFalse);
expect(h.recorder.phase, RunPhase.idle);
expect(h.recorder.issue, RunIssue.streamError);
@ -262,8 +204,8 @@ void main() {
});
test('is false when a run is already going', () async {
final saved = await _checkpointAfter(3);
final h = _Host();
final saved = await checkpointAfter(3);
final h = PersistHost();
await h.recorder.start();
expect(await h.recorder.restore(saved), isFalse);
expect(h.recorder.phase, RunPhase.recording);
@ -273,8 +215,8 @@ void main() {
test(
'runs afterAccess (the foreground service) before listening',
() async {
final saved = await _checkpointAfter(3);
final h = _Host();
final saved = await checkpointAfter(3);
final h = PersistHost();
var served = false;
await h.recorder.restore(saved, afterAccess: () async => served = true);
expect(served, isTrue);
@ -283,8 +225,10 @@ void main() {
);
test('past 5 h of wall clock it auto-ends at once on restore', () async {
final saved = await _checkpointAfter(10);
final h = _Host(at: _t0.add(const Duration(hours: 5, seconds: 1)));
final saved = await checkpointAfter(10);
final h = PersistHost(
at: persistT0.add(const Duration(hours: 5, seconds: 1)),
);
await h.recorder.restore(saved);
expect(h.autoEnds, 1);
expect(h.suggestions, isEmpty);
@ -293,77 +237,4 @@ void main() {
h.recorder.dispose();
});
});
group('suggestions and auto end, off the timer and the clock', () {
testWidgets('no fix for 5 min suggests finishing, never ends', (
tester,
) async {
final h = _Host();
await h.recorder.start();
await h.feed(straightRun(3), tester: tester);
for (var i = 0; i < 61; i++) {
h.now = h.now.add(const Duration(seconds: 5));
await tester.pump(const Duration(seconds: 5));
}
expect(h.suggestions, [RunSuggestion.gpsLost]);
expect(h.recorder.phase, RunPhase.recording);
await h.finishIn(tester);
h.recorder.dispose();
});
testWidgets('5 h wall clock ends the run once, pauses included', (
tester,
) async {
final h = _Host(autoEnd: const Duration(minutes: 2));
await h.recorder.start();
await h.feed(straightRun(3), tester: tester);
h.recorder.pause();
for (var i = 0; i < 30; i++) {
h.now = h.now.add(const Duration(seconds: 5));
await tester.pump(const Duration(seconds: 5));
}
expect(h.autoEnds, 1);
expect(h.suggestions, isEmpty); // paused: only the auto end
expect(await h.finishIn(tester), isNotNull);
h.recorder.dispose();
});
testWidgets('finish() stops the timer: nothing fires afterwards', (
tester,
) async {
final h = _Host(autoEnd: const Duration(minutes: 1));
await h.recorder.start();
await h.feed(straightRun(3), tester: tester);
await h.finishIn(tester);
h.now = h.now.add(const Duration(hours: 1));
await tester.pump(const Duration(minutes: 10));
expect(h.autoEnds, 0);
expect(h.suggestions, isEmpty);
h.recorder.dispose();
});
test('a car (jump-rejected fixes) suggests finishing', () async {
final h = _Host();
await h.recorder.start();
await h.feed(straightRun(2));
await h.feed([for (var s = 4; s <= 100; s += 2) fixAt(s, s * 10.0)]);
expect(h.suggestions, [RunSuggestion.vehicleSpeed]);
h.recorder.dispose();
});
testWidgets('dispose cancels the watchdog timer', (tester) async {
final h = _Host(autoEnd: const Duration(seconds: 1));
await h.recorder.start();
h.now = h.now.add(const Duration(hours: 1));
h.recorder.dispose();
await tester.pump(const Duration(seconds: 30));
expect(h.autoEnds, 0);
});
});
}
class _ThrowingSource extends ManualPositionSource {
@override
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) =>
throw StateError('provider gone');
}

View File

@ -0,0 +1,78 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/gps_filter.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_recorder.dart';
import '../run_test_fixtures.dart';
import '../run_recorder_persist_rig.dart';
void main() {
group('suggestions and auto end, off the timer and the clock', () {
testWidgets('no fix for 5 min suggests finishing, never ends', (
tester,
) async {
final h = PersistHost();
await h.recorder.start();
await h.feed(straightRun(3), tester: tester);
for (var i = 0; i < 61; i++) {
h.now = h.now.add(const Duration(seconds: 5));
await tester.pump(const Duration(seconds: 5));
}
expect(h.suggestions, [RunSuggestion.gpsLost]);
expect(h.recorder.phase, RunPhase.recording);
await h.finishAfter(tester);
h.recorder.dispose();
});
testWidgets('5 h wall clock ends the run once, pauses included', (
tester,
) async {
final h = PersistHost(autoEnd: const Duration(minutes: 2));
await h.recorder.start();
await h.feed(straightRun(3), tester: tester);
h.recorder.pause();
for (var i = 0; i < 30; i++) {
h.now = h.now.add(const Duration(seconds: 5));
await tester.pump(const Duration(seconds: 5));
}
expect(h.autoEnds, 1);
expect(h.suggestions, isEmpty); // paused: only the auto end
expect(await h.finishAfter(tester), isNotNull);
h.recorder.dispose();
});
testWidgets('finish() stops the timer: nothing fires afterwards', (
tester,
) async {
final h = PersistHost(autoEnd: const Duration(minutes: 1));
await h.recorder.start();
await h.feed(straightRun(3), tester: tester);
await h.finishAfter(tester);
h.now = h.now.add(const Duration(hours: 1));
await tester.pump(const Duration(minutes: 10));
expect(h.autoEnds, 0);
expect(h.suggestions, isEmpty);
h.recorder.dispose();
});
test('a car (jump-rejected fixes) suggests finishing', () async {
final h = PersistHost();
await h.recorder.start();
await h.feed(straightRun(2));
await h.feed([for (var s = 4; s <= 100; s += 2) fixAt(s, s * 10.0)]);
expect(h.suggestions, [RunSuggestion.vehicleSpeed]);
h.recorder.dispose();
});
testWidgets('dispose cancels the watchdog timer', (tester) async {
final h = PersistHost(autoEnd: const Duration(seconds: 1));
await h.recorder.start();
h.now = h.now.add(const Duration(hours: 1));
h.recorder.dispose();
await tester.pump(const Duration(seconds: 30));
expect(h.autoEnds, 0);
});
});
}

View File

@ -4,63 +4,24 @@ import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_watchdog.dart';
import '../run_test_fixtures.dart';
final DateTime _start = DateTime.utc(2026, 11, 9, 12);
class _Rig {
_Rig({this.autoEnd = const Duration(hours: 5)}) {
dog = RunWatchdog(
clock: () => now,
onSuggest: suggestions.add,
onAutoEnd: () => autoEnds++,
autoEndAfter: autoEnd,
);
}
final Duration autoEnd;
late final RunWatchdog dog;
DateTime now = _start;
final suggestions = <RunSuggestion>[];
int autoEnds = 0;
double metres = 0;
void advance(Duration d) {
now = now.add(d);
dog.check();
}
/// [minutes] minutes with a fresh, motionless fix every minute.
void idle(int minutes) {
for (var i = 0; i < minutes; i++) {
now = now.add(const Duration(minutes: 1));
fix();
dog.check();
}
}
/// An accepted fix at the current clock, [stepM] further on.
void fix({double stepM = 0, int secondsIntoRun = 0}) {
metres += stepM;
dog.onFix(fixAt(secondsIntoRun, metres), FixVerdict.accepted, metres);
}
}
import '../run_watchdog_rig.dart';
void main() {
group('stationary (under 50 m in 10 min)', () {
test('fires after 10 idle minutes and then every 10, with no limit', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.idle(30);
expect(r.suggestions, List.filled(3, RunSuggestion.stationary));
});
test('does not fire before 10 minutes', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.idle(9);
expect(r.suggestions, isEmpty);
});
test('50 m of progress in the window stays quiet and re-arms', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.idle(4);
r.fix(stepM: 50);
r.idle(6);
@ -72,7 +33,7 @@ void main() {
});
test('nothing fires while paused, and resume restarts the window', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.idle(8);
r.dog.pause();
r.advance(const Duration(minutes: 30));
@ -87,7 +48,7 @@ void main() {
group('no GPS fix for 5 min', () {
test('fires once per loss, not before 5 minutes', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.advance(const Duration(minutes: 4, seconds: 59));
expect(r.suggestions, isEmpty);
r.advance(const Duration(seconds: 1));
@ -97,7 +58,7 @@ void main() {
});
test('a fix re-arms it', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.advance(const Duration(minutes: 5));
r.fix();
r.advance(const Duration(minutes: 5));
@ -108,7 +69,7 @@ void main() {
});
test('fixes the filter rejects as too inaccurate do not count', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.advance(const Duration(minutes: 4));
r.dog.onFix(fixAt(0, 0), FixVerdict.inaccurate, 0);
r.dog.onFix(fixAt(2, 0), FixVerdict.mocked, 0);
@ -117,7 +78,7 @@ void main() {
});
test('nothing fires while paused', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.dog.pause();
r.advance(const Duration(minutes: 20));
expect(r.suggestions, isEmpty);
@ -127,26 +88,26 @@ void main() {
group('vehicle speed (over 25 km/h for 60 s)', () {
// 10 m/s is 36 km/h. Rejected jump fixes still count: a car never
// produces an accepted fix, the filter drops it as too fast.
void drive(_Rig r, {required int seconds, required double mps}) {
void drive(WatchdogRig r, {required int seconds, required double mps}) {
for (var s = 0; s <= seconds; s += 2) {
r.dog.onFix(fixAt(s, s * mps), FixVerdict.tooFast, r.metres);
}
}
test('fires once after 60 s of it', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
drive(r, seconds: 120, mps: 10);
expect(r.suggestions, [RunSuggestion.vehicleSpeed]);
});
test('59 s is not sustained', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
drive(r, seconds: 58, mps: 10);
expect(r.suggestions, isEmpty);
});
test('slowing down resets it', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
drive(r, seconds: 50, mps: 10);
r.dog.onFix(fixAt(52, 500), FixVerdict.accepted, 0); // standing
for (var s = 54; s <= 100; s += 2) {
@ -156,13 +117,13 @@ void main() {
});
test('running speed never fires it', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
drive(r, seconds: 300, mps: 3);
expect(r.suggestions, isEmpty);
});
test('a second ride after slowing fires again', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
drive(r, seconds: 70, mps: 10);
r.dog.onFix(fixAt(72, 700), FixVerdict.accepted, 0);
for (var s = 74; s <= 200; s += 2) {
@ -175,7 +136,7 @@ void main() {
});
test('same-second fixes and mocked fixes are ignored', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.dog.onFix(fixAt(0, 0), FixVerdict.accepted, 0);
r.dog.onFix(fixAt(0, 500), FixVerdict.tooFast, 0);
r.dog.onFix(fixAt(2, 900), FixVerdict.mocked, 0);
@ -185,7 +146,7 @@ void main() {
group('auto end after 5 h of wall clock', () {
test('fires once at 5 h, pauses and gaps included', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.dog.pause();
r.advance(const Duration(hours: 4, minutes: 59));
expect(r.autoEnds, 0);
@ -196,37 +157,38 @@ void main() {
});
test('a shortened limit is honoured', () {
final r = _Rig(autoEnd: const Duration(minutes: 3))..dog.begin(_start);
final r = WatchdogRig(autoEnd: const Duration(minutes: 3))
..dog.begin(watchdogStart);
r.advance(const Duration(minutes: 3));
expect(r.autoEnds, 1);
});
test('restored past the limit ends at once, with no restore hint', () {
final r = _Rig();
r.now = _start.add(const Duration(hours: 6));
r.dog.restored(_start, paused: false, distanceM: 0);
final r = WatchdogRig();
r.now = watchdogStart.add(const Duration(hours: 6));
r.dog.restored(watchdogStart, paused: false, distanceM: 0);
expect(r.autoEnds, 1);
expect(r.suggestions, isEmpty);
});
test('restored inside the limit suggests finishing', () {
final r = _Rig();
r.now = _start.add(const Duration(hours: 1));
r.dog.restored(_start, paused: false, distanceM: 2000);
final r = WatchdogRig();
r.now = watchdogStart.add(const Duration(hours: 1));
r.dog.restored(watchdogStart, paused: false, distanceM: 2000);
expect(r.autoEnds, 0);
expect(r.suggestions, [RunSuggestion.restored]);
});
test('restored while paused stays paused: only the restore hint', () {
final r = _Rig();
r.now = _start.add(const Duration(minutes: 30));
r.dog.restored(_start, paused: true, distanceM: 0);
final r = WatchdogRig();
r.now = watchdogStart.add(const Duration(minutes: 30));
r.dog.restored(watchdogStart, paused: true, distanceM: 0);
r.advance(const Duration(hours: 1));
expect(r.suggestions, [RunSuggestion.restored]);
});
test('stop() silences everything and is safe twice', () {
final r = _Rig()..dog.begin(_start);
final r = WatchdogRig()..dog.begin(watchdogStart);
r.dog.stop();
r.dog.stop();
r.advance(const Duration(hours: 6));
@ -235,7 +197,7 @@ void main() {
});
test('fix and pause calls before begin are harmless', () {
final r = _Rig();
final r = WatchdogRig();
r.dog.pause();
r.dog.resume();
r.fix();
@ -245,13 +207,13 @@ void main() {
});
testWidgets('the timer, not a fix, drives the checks', (tester) async {
var now = _start;
var now = watchdogStart;
final suggestions = <RunSuggestion>[];
final dog = RunWatchdog(
clock: () => now,
onSuggest: suggestions.add,
onAutoEnd: () {},
)..begin(_start);
)..begin(watchdogStart);
for (var i = 0; i < 61; i++) {
now = now.add(const Duration(seconds: 5));
await tester.pump(const Duration(seconds: 5));