Adapt run host to the real recorder API

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
This commit is contained in:
Krzysztof Rudnicki 2026-11-17 21:08:45 +01:00
parent 218632fd0e
commit cfc2cd553a
22 changed files with 345 additions and 128 deletions

View File

@ -36,9 +36,6 @@ class _PulsingFinishState extends State<_PulsingFinish>
void _sync() {
if (widget.pulsing && !_pulse.isAnimating) {
_pulse.repeat(reverse: true);
} else if (!widget.pulsing && _pulse.isAnimating) {
_pulse.value = 1;
_pulse.stop();
}
}

View File

@ -118,7 +118,7 @@ class FlutterForegroundRunClient implements ForegroundRunClient {
/// The UI's link to the host in the service isolate.
// coverage:ignore-start
class ServiceRunLink implements RunLink {
class ServiceRunLink implements RunHostLink {
/// Listens for the host's messages until [close].
ServiceRunLink() {
FlutterForegroundTask.addTaskDataCallback(_onData);

View File

@ -57,13 +57,15 @@ class RunController extends ChangeNotifier {
late final IdleLocation _idle;
final ForegroundRunClient _service;
final RunLink _link;
final RunHostLink _link;
final Future<bool> Function() _soundOn;
late final StreamSubscription<Map<Object?, Object?>> _sub;
RunServiceState _serviceState = RunServiceState.none;
bool _disposed = false;
bool _attachGaveUp = false;
Timer? _pauseTimer;
Completer<void>? _pauseDone;
/// The host never answered the screen's questions: nothing is there.
bool get attachGaveUp => _attachGaveUp;
@ -109,15 +111,13 @@ class RunController extends ChangeNotifier {
Future<void> attach() async {
for (var i = 0; i < 8 && !view.synced && !_disposed; i++) {
_hello();
await Future<void>.delayed(i == 0 ? Duration.zero : retryEvery);
await _pause(i == 0 ? Duration.zero : retryEvery);
}
if (!view.synced && !_disposed) {
_attachGaveUp = true;
_serviceState = RunServiceState.none;
} else if (view.phase.isActive && !_serviceState.isUp) {
_serviceState = RunServiceState.running;
}
notifyListeners();
if (!_disposed) notifyListeners();
}
/// Asks for access, starts the service, begins recording. A run that is
@ -157,18 +157,26 @@ class RunController extends ChangeNotifier {
await _until(
() => view.phase == RunPhase.finished && view.done,
);
if (view.phase == RunPhase.finished) {
_serviceState = RunServiceState.none;
if (view.phase == RunPhase.finished && !_disposed) {
if (_serviceState.isUp) _serviceState = RunServiceState.none;
notifyListeners();
}
}
/// Waits [length], or until [dispose] (so no timer outlives the screen).
Future<void> _pause(Duration length) {
final done = Completer<void>();
_pauseTimer = Timer(length, done.complete);
_pauseDone = done;
return done.future;
}
void _hello() => _link.send({'cmd': RunCmd.hello});
void _onMessage(Map<Object?, Object?> message) {
if (!isRunMessage(message)) return;
view.apply(message);
if (view.phase.isActive && !_serviceState.isUp) {
if (view.phase.isActive && _serviceState == RunServiceState.none) {
_serviceState = RunServiceState.running;
}
}
@ -240,6 +248,8 @@ class RunController extends ChangeNotifier {
@override
void dispose() {
_disposed = true;
_pauseTimer?.cancel();
if (_pauseDone case final done? when !done.isCompleted) done.complete();
unawaited(_sub.cancel());
unawaited(_idle.dispose());
unawaited(_link.close());

View File

@ -17,6 +17,7 @@ import 'package:workout_app/services/run_checkpoint_store.dart';
import 'package:workout_app/services/run_engine.dart';
import 'package:workout_app/services/run_host_port.dart';
import 'package:workout_app/services/run_notification.dart';
import 'package:workout_app/services/run_phase.dart';
import 'package:workout_app/services/run_wire.dart';
export 'package:workout_app/services/run_host_port.dart';
@ -57,9 +58,6 @@ class RunHost {
({bool stored, String reason})? _saved;
String _lastCopy = '';
/// The live engine, if any (tests read it).
RunEngine? get engine => _engine;
/// Resumes the run the checkpoint describes. False when there is none (the
/// caller then has nothing to host).
Future<bool> restoreFromStore() async {
@ -137,7 +135,13 @@ class RunHost {
// A second "start" can never restart a live run: it only re-syncs.
return _emit(full: true);
}
final engine = _fresh();
// The idle engine a "hello" made is reused; anything else starts clean.
final engine = current != null && current.phase == RunPhase.idle
? current
: _fresh();
// The controller already drew the first notification (zeros).
final zero = runNotificationCopy(metres: 0, movingSeconds: 0);
_lastCopy = '${zero.title}|${zero.body}';
cues.soundOn = message['sound'] as bool? ?? true;
engine.setPaceTarget(message['paceTarget'] as int?);
await engine.start();

View File

@ -5,14 +5,13 @@ import 'dart:async';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/foreground_run_client.dart';
import 'package:workout_app/services/run_checkpoint.dart';
import 'package:workout_app/services/run_checkpoint_store.dart';
import 'package:workout_app/services/run_engine.dart';
import 'package:workout_app/services/run_host.dart';
/// A conversation with the host. Closing it only hangs up: it never touches
/// the run.
abstract interface class RunLink {
abstract interface class RunHostLink {
/// The host's snapshots (see `run_wire.dart`).
Stream<Map<Object?, Object?>> get messages;
@ -30,7 +29,7 @@ class LoopbackRunPort implements RunHostPort {
LoopbackRunPort(this._client);
final ForegroundRunClient _client;
final _out = StreamController<Map<Object?, Object?>>.broadcast(sync: true);
final _out = StreamController<Map<Object?, Object?>>.broadcast();
/// What the host sends.
Stream<Map<Object?, Object?>> get messages => _out.stream;
@ -39,19 +38,22 @@ class LoopbackRunPort implements RunHostPort {
void send(Map<String, Object?> message) => _out.add(message);
@override
Future<void> notify({required String title, required String text}) =>
_client.update(title: title, text: text);
Future<void> notify({required String title, required String text}) async {
if (_client.isSupported) await _client.update(title: title, text: text);
}
@override
Future<void> stopService() => _client.stop();
Future<void> stopService() async {
if (_client.isSupported) await _client.stop();
}
@override
void launchApp() {}
}
/// A [RunLink] to a host in this very isolate: Linux, the tests, and any
/// A [RunHostLink] to a host in this very isolate: Linux, the tests, and any
/// platform with no foreground service.
class LoopbackRunLink implements RunLink {
class LoopbackRunLink implements RunHostLink {
/// Creates a link to [host]; [port] is the one the host was built with.
LoopbackRunLink(this.host, this._port);
@ -87,18 +89,3 @@ class LoopbackRunLink implements RunLink {
@override
Future<void> close() async {}
}
/// A checkpoint kept in memory: enough where nothing can kill the process
/// separately from the UI.
class MemoryRunCheckpointStore implements RunCheckpointStore {
RunCheckpoint? _held;
@override
Future<void> save(RunCheckpoint c) async => _held = c;
@override
Future<RunCheckpoint?> load() async => _held;
@override
Future<void> clear() async => _held = null;
}

View File

@ -0,0 +1,69 @@
/// A [RunController] over the real recorder behind the in-process host.
library;
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_test/flutter_test.dart' show addTearDown;
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_engine_recorder.dart';
import 'package:workout_app/services/run_host.dart';
import 'package:workout_app/services/run_link.dart';
import 'fake_run_service.dart';
import 'run_test_fixtures.dart';
/// Builds the controller; the host (which keeps a watchdog timer while a run
/// is active) is released at the end of the test.
RunController buildRunController({
required ManualPositionSource source,
PositionSource Function()? idleSourceFor,
FeedbackCues? cues,
FakeForegroundRunClient? service,
RunSaveFn? save,
List<RunTrack>? saved,
}) {
final client = service ?? FakeForegroundRunClient();
final link = LoopbackRunLink.build(
client: client,
engineFactory: recorderEngineFactory(() => source),
cues: cues ?? FeedbackCues(AudioPlayer()),
save:
save ??
(track) async {
saved?.add(track);
return (stored: true, reason: 'saved');
},
);
addTearDown(link.host.dispose);
return RunController(
idleSourceFor: idleSourceFor ?? () => source,
service: client,
link: link,
soundOn: () async => true,
retryEvery: const Duration(milliseconds: 1),
);
}
/// A link to nobody: commands vanish and nothing ever answers.
class SilentLink implements RunHostLink {
@override
Stream<Map<Object?, Object?>> get messages => const Stream.empty();
@override
void send(Map<String, Object?> command) {}
@override
Future<void> close() async {}
}
/// A controller whose host is down.
RunController buildSilentController() => RunController(
idleSourceFor: ManualPositionSource.new,
service: FakeForegroundRunClient(isSupported: false),
link: SilentLink(),
soundOn: () async => true,
hostTimeout: const Duration(milliseconds: 50),
retryEvery: const Duration(milliseconds: 1),
);

View File

@ -4,10 +4,9 @@ library;
import 'dart:async';
import 'package:flutter_test/flutter_test.dart' show WidgetTester;
import 'package:flutter_test/flutter_test.dart' show WidgetTester, addTearDown;
import 'package:material_ui/material_ui.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_link.dart';
import 'package:workout_app/ui/theme.dart';
@ -27,6 +26,7 @@ class PersistRig {
: service = FakeForegroundRunClient(isSupported: supported) {
port = LoopbackRunPort(service);
host = HostRig(hostPort: port);
addTearDown(host.host.dispose);
link = _RigLink(this);
}
@ -40,7 +40,7 @@ class PersistRig {
late final LoopbackRunPort port;
/// The link every controller gets.
late final RunLink link;
late final RunHostLink link;
/// Controllers built, oldest first.
final controllers = <RunController>[];
@ -92,7 +92,7 @@ class PersistRig {
}
/// Sends commands to the rig's host and relays its snapshots.
class _RigLink implements RunLink {
class _RigLink implements RunHostLink {
_RigLink(this._rig);
final PersistRig _rig;

View File

@ -11,14 +11,17 @@ import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/pace_target_store.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_engine_recorder.dart';
import 'package:workout_app/services/run_link.dart';
import 'package:workout_app/ui/theme.dart';
import 'package:workout_app/widgets/run_map_slot.dart';
import '../fake_run_service.dart';
import '../fake_run_uploader.dart';
import '../run_test_fixtures.dart';
import '../widgets/_run_map_fixtures.dart';
import '_run_screen_helpers.dart';
export '_run_screen_helpers.dart';
/// Everything a test needs to drive and inspect one screen.
class RunHarness {
@ -42,17 +45,28 @@ class RunHarness {
final settingsOpened = <int>[];
final navigator = GlobalKey<NavigatorState>();
RunController build() => RunController(
sourceFor: () => source,
service: service,
cues: cues,
save: (track) async {
await saveGate?.future;
if (saveThrows) throw Exception('disk full');
saved.add(track);
return const RunSaveResult(stored: true, reason: 'saved');
},
);
RunController build() {
final link = LoopbackRunLink.build(
client: service,
engineFactory: recorderEngineFactory(() => source),
cues: cues,
save: (track) async {
await saveGate?.future;
if (saveThrows) throw Exception('disk full');
saved.add(track);
return (stored: true, reason: 'saved');
},
);
// The run outlives the screen, so the test ends it (the recorder keeps a
// watchdog timer).
addTearDown(link.host.dispose);
return RunController(
idleSourceFor: () => source,
service: service,
link: link,
soundOn: () async => true,
);
}
Widget app() => MaterialApp(
navigatorKey: navigator,

View File

@ -51,3 +51,18 @@ Future<void> tapKey(WidgetTester tester, String id) async {
);
await tester.pumpAndSettle();
}
/// Taps finish and the modal's red check, the only way a run ends.
Future<void> tapFinish(WidgetTester tester) async {
await tapKey(tester, 'run_finish');
await tester.tap(key('run_finish_confirm'));
// The host finishes on the real event loop (a stream cancel and messages
// between the screen and the host); give it turns, then settle the frames.
for (var i = 0; i < 3; i++) {
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await tester.pump();
}
await tester.pumpAndSettle();
}

View File

@ -49,6 +49,8 @@ void main() {
rig.engine.addFix();
await pumpHome(tester, app(openRun: true, openWorkout: true));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
await tester.pump(const Duration(milliseconds: 400));
expect(find.byType(RunScreen), findsOneWidget);

View File

@ -96,7 +96,7 @@ void main() {
await tapKey(tester, 'run_start');
expect(find.byType(PolylineLayer), findsNothing);
await h.run(tester, 5, from: 10);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
expect(h.saved.single.points, hasLength(5));
});
}

View File

@ -61,7 +61,7 @@ void main() {
await tapKey(tester, 'run_pause');
_expectFits(tester);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
_expectFits(tester);
});

View File

@ -31,7 +31,7 @@ void main() {
await tapKey(tester, 'run_start');
// 3 m/s is 10.8 km/h: over any walking cap, fine for the running filter.
await h.run(tester, 30);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
final track = h.saved.single;
expect(track.sport, RunSport.running);

View File

@ -4,8 +4,13 @@
// 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';
@ -13,7 +18,18 @@ import '../run_persist_rig.dart';
import '_run_screen_helpers.dart';
void main() {
setUp(installFakeAudioPlatform);
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');
@ -74,7 +90,7 @@ void main() {
expect(key('run_pause'), findsOneWidget, reason: 'live run, not idle');
expect(key('run_start'), findsNothing);
// A start command from the new controller is refused by the host.
await rig.controllers.last.start();
await tester.runAsync(rig.controllers.last.start);
expect(rig.host.engines, hasLength(1));
expect(engine.starts, 1);
expect(engine.phase, RunPhase.recording);
@ -91,8 +107,10 @@ void main() {
// A rebuilt controller (what "new run" makes) asking to start.
final second = rig.build();
await second.attach();
await second.start();
await tester.runAsync(() async {
await second.attach();
await second.start();
});
expect(rig.host.engines, hasLength(1));
expect(engine.phase, RunPhase.recording);
@ -208,7 +226,8 @@ void main() {
expect(key('run_finish_dialog'), findsOneWidget);
expect(rig.engine.phase, RunPhase.recording);
await tapKey(tester, 'run_finish_cancel');
await tester.tap(key('run_finish_cancel'));
await tester.pump(const Duration(milliseconds: 400));
expect(rig.engine.phase, RunPhase.recording);
expect(key('run_finish_dialog'), findsNothing);
});
@ -226,6 +245,7 @@ void main() {
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(),
home: RunLanding(
owed: () async => owed,
child: const SizedBox(key: Key('home')),

View File

@ -44,7 +44,7 @@ void main() {
final h = RunHarness();
await h.pump(tester);
await tapKey(tester, 'run_start');
await tapKey(tester, 'run_finish');
await tapFinish(tester);
expect(key('run_issue_tooShort'), findsOneWidget);
expect(h.saved, isEmpty);
expect(key('run_saved_ok'), findsNothing);
@ -77,7 +77,7 @@ void main() {
await h.pump(tester);
await tapKey(tester, 'run_start');
await h.run(tester, 4);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
await tester.pumpAndSettle();
expect(key('run_saved_failed'), findsOneWidget);
expect(key('run_saved_ok'), findsNothing);

View File

@ -8,6 +8,7 @@ import 'package:shared_preferences_platform_interface/shared_preferences_async_p
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/sandbox/sandbox_run_replay.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/run_wiring.dart';
import 'package:workout_app/ui/theme.dart';
import '../fake_audio_platform.dart';
@ -21,6 +22,9 @@ void main() {
setUp(() {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
// The real wiring: the recorder behind a loopback link (no service here).
installRunWiring();
addTearDown(() => RunScreen.defaultControllerFactory = null);
installFakeAudioPlatform();
Sandbox.enabled = true;
// Fast enough that a walking replay would show within the test.

View File

@ -11,6 +11,7 @@ import 'package:workout_app/models/run_record.dart';
import 'package:workout_app/models/run_track.dart';
import 'package:workout_app/sandbox/sandbox.dart';
import 'package:workout_app/screens/run_screen.dart';
import 'package:workout_app/services/run_wiring.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/ui/theme.dart';
@ -30,6 +31,9 @@ void main() {
setUp(() async {
SharedPreferencesAsyncPlatform.instance =
InMemorySharedPreferencesAsync.empty();
// The real wiring: the recorder behind a loopback link (no service here).
installRunWiring();
addTearDown(() => RunScreen.defaultControllerFactory = null);
StorageService.resetForTesting();
await StorageService.init();
installFakeAudioPlatform();
@ -82,6 +86,9 @@ void main() {
last = shown;
}
await tester.tap(key('run_finish'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
await tester.tap(key('run_finish_confirm'));
await Future<void>.delayed(const Duration(milliseconds: 500));
runs = await StorageService.instance.listRuns();
});

View File

@ -70,7 +70,7 @@ void main() {
await tapKey(tester, 'run_resume');
expect(key('run_pause'), findsOneWidget);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
await tester.pumpAndSettle();
expect(key('run_saved_ok'), findsOneWidget);
expect(h.saved.single.points, hasLength(8));
@ -87,7 +87,7 @@ void main() {
await tapKey(tester, 'run_start');
await h.run(tester, 4);
await tapKey(tester, 'run_pause');
await tapKey(tester, 'run_finish');
await tapFinish(tester);
expect(key('run_saved_ok'), findsOneWidget);
});
@ -98,7 +98,7 @@ void main() {
await h.pump(tester);
await tapKey(tester, 'run_start');
await h.run(tester, 4);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
await tapKey(tester, 'run_again');
expect(key('run_start'), findsOneWidget);
@ -106,7 +106,7 @@ void main() {
expect(key('run_saved_ok'), findsNothing);
await tapKey(tester, 'run_start');
await tapKey(tester, 'run_finish');
await tapFinish(tester);
await tester.pumpAndSettle();
await tapKey(tester, 'run_close');
await tester.pumpAndSettle();
@ -130,7 +130,7 @@ void main() {
await tester.pumpAndSettle();
expect(find.byType(RunScreen), findsOneWidget);
await tapKey(tester, 'run_finish');
await tapFinish(tester);
await tester.pumpAndSettle();
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
@ -164,9 +164,10 @@ void main() {
await tapKey(tester, 'run_start');
await h.run(tester, 4);
await tester.tap(key('run_finish'));
await tapKey(tester, 'run_finish');
await tester.tap(key('run_finish_confirm'));
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 20)),
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await tester.pump();
expect(key('run_saving'), findsOneWidget);
@ -175,7 +176,7 @@ void main() {
gate.complete();
await tester.runAsync(
() => Future<void>.delayed(const Duration(milliseconds: 20)),
() => Future<void>.delayed(const Duration(milliseconds: 100)),
);
await tester.pumpAndSettle();
expect(key('run_saving'), findsNothing);

View File

@ -180,11 +180,23 @@ void main() {
// That makes a startup reaper the only thing standing between a crash and a
// notification counting down a workout that ended hours ago.
group('stopStaleBreakService', () {
test('never stops the service while a run is owed', () async {
client.running = true;
final stopped = await stopStaleBreakService(
client,
hasActiveWorkout: () async => false,
runIsOwed: () async => true,
);
expect(stopped, isFalse);
expect(client.calls, isNot(contains('stop')));
});
test('stops a service whose workout no longer exists', () async {
client.running = true;
final stopped = await stopStaleBreakService(
client,
hasActiveWorkout: () async => false,
runIsOwed: () async => false,
);
expect(stopped, isTrue);
expect(client.calls, contains('stop'));
@ -197,6 +209,7 @@ void main() {
final stopped = await stopStaleBreakService(
client,
hasActiveWorkout: () async => true,
runIsOwed: () async => false,
);
expect(stopped, isFalse);
expect(client.calls, isNot(contains('stop')));
@ -209,6 +222,7 @@ void main() {
await stopStaleBreakService(
client,
hasActiveWorkout: () async => false,
runIsOwed: () async => false,
),
isFalse,
);
@ -223,6 +237,7 @@ void main() {
await stopStaleBreakService(
client,
hasActiveWorkout: () async => false,
runIsOwed: () async => false,
),
isFalse,
);

View File

@ -6,11 +6,11 @@ import 'package:workout_app/services/feedback_cues.dart';
import 'package:workout_app/services/pace_band.dart';
import 'package:workout_app/services/position_source.dart';
import 'package:workout_app/services/run_controller.dart';
import 'package:workout_app/services/run_recorder.dart';
import 'package:workout_app/services/run_saver.dart';
import 'package:workout_app/services/run_phase.dart';
import '../fake_audio_platform.dart';
import '../fake_run_service.dart';
import '../run_controller_rig.dart';
import '../run_test_fixtures.dart';
class _CueSpy extends FeedbackCues {
@ -30,12 +30,11 @@ RunController _build(
PositionSource Function()? idleSourceFor,
FeedbackCues? cues,
FakeForegroundRunClient? service,
}) => RunController(
sourceFor: () => source,
}) => buildRunController(
source: source,
idleSourceFor: idleSourceFor,
service: service ?? FakeForegroundRunClient(),
cues: cues ?? _CueSpy(),
save: (_) async => const RunSaveResult(stored: true, reason: 'saved'),
service: service,
);
void main() {
@ -61,7 +60,7 @@ void main() {
await controller.watchIdle();
expect(controller.blocked, isTrue);
expect(controller.canStart, isFalse);
expect(controller.recorder.issue, RunIssue.deniedForever);
expect(controller.view.issue, RunIssue.deniedForever);
source.access = LocationAccess.granted;
await controller.recheckAccess();
@ -105,12 +104,12 @@ void main() {
final service = FakeForegroundRunClient();
final cues = _CueSpy();
final controller = _build(source, cues: cues, service: service);
controller.recorder.setPaceTarget(300);
await controller.start();
await controller.start(paceTarget: 300);
for (var i = 0; i < 12; i++) {
source.controller.add(fixAt(i * 2, i * 6.0));
}
await pumpEventQueue();
await pumpEventQueue();
expect(cues.paced, [PaceCue.tooSlow]);
expect(service.drawn.last, endsWith('5:35'));
controller.dispose();
@ -125,6 +124,7 @@ void main() {
source.controller.add(fixAt(i * 2, i * 6.0));
}
await pumpEventQueue();
await pumpEventQueue();
expect(service.drawn.last.split(' '), hasLength(2));
controller.dispose();
});

View File

@ -1,19 +1,16 @@
import 'package:audioplayers/audioplayers.dart';
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/sandbox/sandbox.dart';
import 'package:workout_app/services/feedback_cues.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_recorder.dart';
import 'package:workout_app/services/run_saver.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() {
@ -33,31 +30,19 @@ void main() {
saved = [];
});
tearDown(() => Sandbox.enabled = false);
RunController build(
ManualPositionSource source,
FakeForegroundRunClient service, {
Future<RunSaveResult> Function(RunTrack)? save,
}) => RunController(
sourceFor: () => source,
service: service,
cues: FeedbackCues(AudioPlayer()),
save:
save ??
(track) async {
saved.add(track);
return const RunSaveResult(stored: true, reason: '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);
test('starts the service after access and before the first fix', () async {
final source = ManualPositionSource();
var subscribedAtStart = -1;
@ -97,10 +82,9 @@ void main() {
ManualPositionSource(access: LocationAccess.deniedForever),
service,
);
await controller.watchIdle();
await controller.start();
expect(service.calls, isEmpty);
expect(controller.serviceState, RunServiceState.none);
expect(controller.recorder.issue, RunIssue.deniedForever);
expect(controller.view.issue, RunIssue.deniedForever);
expect(controller.active, isFalse);
controller.dispose();
});
@ -117,8 +101,8 @@ void main() {
expect(service.calls, ['has', 'request', 'start']);
expect(controller.serviceState, RunServiceState.runningHidden);
expect(service.drawn, hasLength(1));
expect(controller.recorder.livePoints.value, hasLength(3));
expect(service.drawn.first, '0.00|0:00 -:--');
expect(controller.view.livePoints.value, hasLength(3));
controller.dispose();
});
@ -131,8 +115,8 @@ void main() {
await controller.start();
await feed(source, [0, 6]);
expect(controller.serviceState, RunServiceState.failed);
expect(controller.recorder.phase, RunPhase.recording);
expect(controller.recorder.livePoints.value, hasLength(2));
expect(controller.view.phase, RunPhase.recording);
expect(controller.view.livePoints.value, hasLength(2));
await controller.finish();
expect(controller.serviceState, RunServiceState.failed);
controller.dispose();
@ -151,12 +135,11 @@ void main() {
controller.dispose();
});
test('the sandbox asks for the data-sync service type alone', () async {
Sandbox.enabled = true;
test('every start asks for the location service type', () async {
final service = FakeForegroundRunClient();
final controller = build(ManualPositionSource(), service);
await controller.start();
expect(service.starts, [false]);
expect(service.starts, [true]);
controller.dispose();
});
@ -168,7 +151,7 @@ void main() {
await feed(source, [for (var i = 0; i <= 170; i++) i * 6]);
await Future<void>.delayed(const Duration(milliseconds: 50));
expect(controller.recorder.distanceM, greaterThan(1000));
expect(controller.view.distanceM, greaterThan(1000));
expect(
audio.resumedSources.where((s) => s.contains('workout_done')),
hasLength(1),
@ -185,6 +168,7 @@ void main() {
controller
..pause()
..resume();
await pumpEventQueue();
final notified = <bool>[];
controller.addListener(() => notified.add(controller.saving));
@ -208,16 +192,15 @@ void main() {
await controller.finish();
expect(saved, isEmpty);
expect(controller.saved, isNull);
expect(controller.recorder.issue, RunIssue.tooShort);
expect(controller.view.issue, RunIssue.tooShort);
expect(service.calls.last, 'stop');
controller.dispose();
});
test('a failing save is reported, not thrown', () async {
final source = ManualPositionSource();
final controller = build(
source,
FakeForegroundRunClient(),
final controller = buildRunController(
source: source,
save: (_) async => throw Exception('disk full'),
);
await controller.start();
@ -228,13 +211,60 @@ void main() {
controller.dispose();
});
test('leaving mid-run stops the service', () async {
final source = ManualPositionSource();
final service = FakeForegroundRunClient();
final controller = build(source, service);
await controller.start();
controller.dispose();
expect(service.calls.last, 'stop');
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', () {

View File

@ -0,0 +1,42 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/run_launch.dart';
import '../fake_run_service.dart';
void main() {
test('no run owed: home as usual, the service is left alone', () async {
final client = FakeForegroundRunClient();
expect(
await resumeRunOnLaunch(owed: () async => false, client: client),
isFalse,
);
expect(client.calls, isEmpty);
});
test('a run owed opens the run and brings its service back', () async {
final client = FakeForegroundRunClient();
expect(
await resumeRunOnLaunch(owed: () async => true, client: client),
isTrue,
);
expect(client.calls, ['start']);
expect(client.starts, [true]);
});
test('a service that will not start still opens the run screen', () async {
final client = FakeForegroundRunClient(startSucceeds: false);
expect(
await resumeRunOnLaunch(owed: () async => true, client: client),
isTrue,
);
});
test('a platform without services just opens the run', () async {
final client = FakeForegroundRunClient(isSupported: false);
expect(
await resumeRunOnLaunch(owed: () async => true, client: client),
isTrue,
);
expect(client.calls, isEmpty);
});
}