diff --git a/lib/providers/workout_logs_notifier.dart b/lib/providers/workout_logs_notifier.dart index 682e2d2db..c67cdcecb 100644 --- a/lib/providers/workout_logs_notifier.dart +++ b/lib/providers/workout_logs_notifier.dart @@ -17,13 +17,28 @@ */ import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:wger/models/workouts/log.dart'; import 'package:wger/providers/workout_logs_repository.dart'; +part 'workout_logs_notifier.g.dart'; + final workoutLogProvider = Provider((ref) { return WorkoutLogMutations(ref.read(workoutLogRepositoryProvider)); }); +/// Streams the past logs for [exerciseId] within [routineId], newest first. +@riverpod +Stream> pastExerciseLogs( + Ref ref, { + required int routineId, + required int exerciseId, +}) { + return ref + .read(workoutLogRepositoryProvider) + .watchLogsByExerciseDrift(routineId: routineId, exerciseId: exerciseId); +} + class WorkoutLogMutations { final WorkoutLogRepository _repo; diff --git a/lib/providers/workout_logs_notifier.g.dart b/lib/providers/workout_logs_notifier.g.dart new file mode 100644 index 000000000..c6d314d22 --- /dev/null +++ b/lib/providers/workout_logs_notifier.g.dart @@ -0,0 +1,116 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'workout_logs_notifier.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Streams the past logs for [exerciseId] within [routineId], newest first. +/// +/// Reads the local `workout_log` table directly, so a set logged during a +/// workout shows up immediately, independent of the gym-mode routine snapshot. + +@ProviderFor(pastExerciseLogs) +final pastExerciseLogsProvider = PastExerciseLogsFamily._(); + +/// Streams the past logs for [exerciseId] within [routineId], newest first. +/// +/// Reads the local `workout_log` table directly, so a set logged during a +/// workout shows up immediately, independent of the gym-mode routine snapshot. + +final class PastExerciseLogsProvider + extends + $FunctionalProvider>, List, Stream>> + with $FutureModifier>, $StreamProvider> { + /// Streams the past logs for [exerciseId] within [routineId], newest first. + /// + /// Reads the local `workout_log` table directly, so a set logged during a + /// workout shows up immediately, independent of the gym-mode routine snapshot. + PastExerciseLogsProvider._({ + required PastExerciseLogsFamily super.from, + required ({int routineId, int exerciseId}) super.argument, + }) : super( + retry: null, + name: r'pastExerciseLogsProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$pastExerciseLogsHash(); + + @override + String toString() { + return r'pastExerciseLogsProvider' + '' + '$argument'; + } + + @$internal + @override + $StreamProviderElement> $createElement($ProviderPointer pointer) => + $StreamProviderElement(pointer); + + @override + Stream> create(Ref ref) { + final argument = this.argument as ({int routineId, int exerciseId}); + return pastExerciseLogs( + ref, + routineId: argument.routineId, + exerciseId: argument.exerciseId, + ); + } + + @override + bool operator ==(Object other) { + return other is PastExerciseLogsProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$pastExerciseLogsHash() => r'e2345fbf5c2bcbaa81a673d39212a59099de5424'; + +/// Streams the past logs for [exerciseId] within [routineId], newest first. +/// +/// Reads the local `workout_log` table directly, so a set logged during a +/// workout shows up immediately, independent of the gym-mode routine snapshot. + +final class PastExerciseLogsFamily extends $Family + with + $FunctionalFamilyOverride< + Stream>, + ({int routineId, int exerciseId}) + > { + PastExerciseLogsFamily._() + : super( + retry: null, + name: r'pastExerciseLogsProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + /// Streams the past logs for [exerciseId] within [routineId], newest first. + /// + /// Reads the local `workout_log` table directly, so a set logged during a + /// workout shows up immediately, independent of the gym-mode routine snapshot. + + PastExerciseLogsProvider call({ + required int routineId, + required int exerciseId, + }) => PastExerciseLogsProvider._( + argument: (routineId: routineId, exerciseId: exerciseId), + from: this, + ); + + @override + String toString() => r'pastExerciseLogsProvider'; +} diff --git a/lib/providers/workout_logs_repository.dart b/lib/providers/workout_logs_repository.dart index 3393dd4e6..a667fb5b0 100644 --- a/lib/providers/workout_logs_repository.dart +++ b/lib/providers/workout_logs_repository.dart @@ -20,7 +20,7 @@ * Repository for body weight network operations. */ -import 'package:drift/drift.dart' show BooleanExpressionOperators; +import 'package:drift/drift.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:wger/models/workouts/log.dart'; @@ -33,15 +33,58 @@ final workoutLogRepositoryProvider = Provider((ref) { return WorkoutLogRepository(db); }); -/// Write-side access to the local `workout_log` table. Reading logs happens -/// through `WorkoutSessionRepository.watchAllDrift`, which joins logs onto -/// their parent session. +/// Local access to the `workout_log` table: writes (add/update/delete) plus a +/// per-exercise read stream. Reading logs grouped under their parent session +/// happens through `WorkoutSessionRepository.watchAllDrift`. class WorkoutLogRepository { final _logger = Logger('WorkoutLogRepository'); final DriftPowersyncDatabase _db; WorkoutLogRepository(this._db); + /// Streams the logs for a single exercise within a routine, newest first, + /// with their repetition and weight units attached. + Stream> watchLogsByExerciseDrift({ + required int routineId, + required int exerciseId, + }) { + _logger.finer('Watching local logs for routine $routineId, exercise $exerciseId'); + + final query = + _db.select(_db.workoutLogTable).join([ + leftOuterJoin( + _db.routineRepetitionUnitTable, + _db.routineRepetitionUnitTable.id.equalsExp(_db.workoutLogTable.repetitionsUnitId), + ), + leftOuterJoin( + _db.routineWeightUnitTable, + _db.routineWeightUnitTable.id.equalsExp(_db.workoutLogTable.weightUnitId), + ), + ]) + ..where( + _db.workoutLogTable.routineId.equals(routineId) & + _db.workoutLogTable.exerciseId.equals(exerciseId), + ) + ..orderBy([ + OrderingTerm(expression: _db.workoutLogTable.date, mode: OrderingMode.desc), + ]); + + return query.watch().map((rows) { + return rows.map((row) { + final log = row.readTable(_db.workoutLogTable); + final repetitionUnit = row.readTableOrNull(_db.routineRepetitionUnitTable); + if (repetitionUnit != null) { + log.repetitionUnit = repetitionUnit; + } + final weightUnit = row.readTableOrNull(_db.routineWeightUnitTable); + if (weightUnit != null) { + log.weightUnit = weightUnit; + } + return log; + }).toList(); + }); + } + Future deleteLocalDrift(String id) async { _logger.finer('Deleting local workout log entry $id'); await (_db.delete(_db.workoutLogTable)..where((t) => t.id.equals(id))).go(); diff --git a/lib/widgets/routines/gym_mode/log_page.dart b/lib/widgets/routines/gym_mode/log_page.dart index 2f01ad4ff..7c90ae845 100644 --- a/lib/widgets/routines/gym_mode/log_page.dart +++ b/lib/widgets/routines/gym_mode/log_page.dart @@ -33,6 +33,7 @@ import 'package:wger/providers/plate_weights.dart'; import 'package:wger/providers/workout_logs_notifier.dart'; import 'package:wger/screens/settings_plates_screen.dart'; import 'package:wger/widgets/core/core.dart'; +import 'package:wger/widgets/core/error.dart'; import 'package:wger/widgets/routines/forms/repetitions.dart'; import 'package:wger/widgets/routines/forms/rir.dart'; import 'package:wger/widgets/routines/forms/weight.dart'; @@ -71,6 +72,15 @@ class LogPage extends ConsumerWidget { } final setConfigData = slotEntryPage.setConfigData!; + // Past logs come straight from the local DB (not the gym-mode routine + // snapshot) so a set logged during this workout shows up right away. + final pastLogs = ref.watch( + pastExerciseLogsProvider( + routineId: gymState.routine.id!, + exerciseId: setConfigData.exerciseId, + ), + ); + // Mark done sets final decorationStyle = slotEntryPage.logDone ? TextDecoration.lineThrough @@ -125,13 +135,7 @@ class LogPage extends ConsumerWidget { if (slotEntryPage.setConfigData!.comment.isNotEmpty) Text(slotEntryPage.setConfigData!.comment, textAlign: TextAlign.center), const SizedBox(height: 10), - Expanded( - child: (gymState.routine.filterLogsByExercise(setConfigData.exerciseId).isNotEmpty) - ? LogsPastLogsWidget( - pastLogs: gymState.routine.filterLogsByExercise(setConfigData.exerciseId), - ) - : Container(), - ), + Expanded(child: _buildPastLogs(pastLogs)), Padding( padding: const EdgeInsets.all(10), @@ -152,6 +156,19 @@ class LogPage extends ConsumerWidget { ], ); } + + /// Renders the previous logs for this exercise + Widget _buildPastLogs(AsyncValue> pastLogs) { + if (pastLogs.hasError) { + _logger.warning('Could not load past logs', pastLogs.error, pastLogs.stackTrace); + // Scroll-wrap so the indicator fits this slim slot instead of overflowing. + return SingleChildScrollView( + child: StreamErrorIndicator(pastLogs.error!, stacktrace: pastLogs.stackTrace), + ); + } + final logs = pastLogs.value ?? const []; + return logs.isEmpty ? const SizedBox.shrink() : LogsPastLogsWidget(pastLogs: logs); + } } class LogsPlatesWidget extends ConsumerWidget { diff --git a/test/routine/gym_mode/gym_mode_test.dart b/test/routine/gym_mode/gym_mode_test.dart index ef2279f8e..4a8f96c9f 100644 --- a/test/routine/gym_mode/gym_mode_test.dart +++ b/test/routine/gym_mode/gym_mode_test.dart @@ -37,6 +37,7 @@ import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/routines_notifier.dart'; import 'package:wger/providers/routines_repository.dart'; import 'package:wger/providers/trophy_repository.dart'; +import 'package:wger/providers/workout_logs_repository.dart'; import 'package:wger/providers/workout_session_repository.dart'; import 'package:wger/screens/gym_mode.dart'; import 'package:wger/screens/routine_screen.dart'; @@ -54,7 +55,13 @@ import '../../../test_data/routines.dart'; import '../../fake_connectivity.dart'; import 'gym_mode_test.mocks.dart'; -@GenerateMocks([WorkoutSessionRepository, ExerciseRepository, RoutinesRepository, TrophyRepository]) +@GenerateMocks([ + WorkoutSessionRepository, + ExerciseRepository, + RoutinesRepository, + TrophyRepository, + WorkoutLogRepository, +]) void main() { installFakeConnectivity(); @@ -66,6 +73,7 @@ void main() { final mockSessionRepo = MockWorkoutSessionRepository(); final mockExerciseRepo = MockExerciseRepository(); final mockRoutinesRepo = MockRoutinesRepository(); + final mockLogRepo = MockWorkoutLogRepository(); setUp(() { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); @@ -89,6 +97,18 @@ void main() { when( mockRoutinesRepo.fetchAndSetRoutineFullServer(any), ).thenAnswer((_) async => testRoutine); + + // Past logs on the log page come from this stream (per exercise). Reuse the + // test routine's logs so the assertions on previous entries keep working. + when( + mockLogRepo.watchLogsByExerciseDrift( + routineId: anyNamed('routineId'), + exerciseId: anyNamed('exerciseId'), + ), + ).thenAnswer((invocation) { + final exerciseId = invocation.namedArguments[#exerciseId] as int; + return Stream.value(testRoutine.filterLogsByExercise(exerciseId)); + }); }); Widget renderGymMode({ @@ -102,6 +122,7 @@ void main() { routinesRepositoryProvider.overrideWithValue(mockRoutinesRepo), exerciseRepositoryProvider.overrideWithValue(mockExerciseRepo), workoutSessionRepositoryProvider.overrideWithValue(mockSessionRepo), + workoutLogRepositoryProvider.overrideWithValue(mockLogRepo), ...extraOverrides, // The repetition + weight unit catalogues are tiny direct-Drift // stream providers, overriding them inline is the established diff --git a/test/routine/gym_mode/gym_mode_test.mocks.dart b/test/routine/gym_mode/gym_mode_test.mocks.dart index 2c3cabe39..5251508e9 100644 --- a/test/routine/gym_mode/gym_mode_test.mocks.dart +++ b/test/routine/gym_mode/gym_mode_test.mocks.dart @@ -18,6 +18,7 @@ import 'package:wger/models/trophies/user_trophy.dart' as _i25; import 'package:wger/models/trophies/user_trophy_progression.dart' as _i26; import 'package:wger/models/workouts/base_config.dart' as _i6; import 'package:wger/models/workouts/day.dart' as _i3; +import 'package:wger/models/workouts/log.dart' as _i28; import 'package:wger/models/workouts/repetition_unit.dart' as _i21; import 'package:wger/models/workouts/routine.dart' as _i2; import 'package:wger/models/workouts/session.dart' as _i10; @@ -29,6 +30,7 @@ import 'package:wger/providers/exercise_repository.dart' as _i11; import 'package:wger/providers/exercises_notifier.dart' as _i15; import 'package:wger/providers/routines_repository.dart' as _i19; import 'package:wger/providers/trophy_repository.dart' as _i22; +import 'package:wger/providers/workout_logs_repository.dart' as _i27; import 'package:wger/providers/workout_session_repository.dart' as _i8; // ignore_for_file: type=lint @@ -47,26 +49,32 @@ import 'package:wger/providers/workout_session_repository.dart' as _i8; // ignore_for_file: invalid_use_of_internal_member class _FakeRoutine_0 extends _i1.SmartFake implements _i2.Routine { - _FakeRoutine_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeRoutine_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDay_1 extends _i1.SmartFake implements _i3.Day { - _FakeDay_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeDay_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSlot_2 extends _i1.SmartFake implements _i4.Slot { - _FakeSlot_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeSlot_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSlotEntry_3 extends _i1.SmartFake implements _i5.SlotEntry { - _FakeSlotEntry_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeSlotEntry_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeBaseConfig_4 extends _i1.SmartFake implements _i6.BaseConfig { - _FakeBaseConfig_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); + _FakeBaseConfig_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeWgerBaseProvider_5 extends _i1.SmartFake implements _i7.WgerBaseProvider { +class _FakeWgerBaseProvider_5 extends _i1.SmartFake + implements _i7.WgerBaseProvider { _FakeWgerBaseProvider_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -74,7 +82,8 @@ class _FakeWgerBaseProvider_5 extends _i1.SmartFake implements _i7.WgerBaseProvi /// A class which mocks [WorkoutSessionRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockWorkoutSessionRepository extends _i1.Mock implements _i8.WorkoutSessionRepository { +class MockWorkoutSessionRepository extends _i1.Mock + implements _i8.WorkoutSessionRepository { MockWorkoutSessionRepository() { _i1.throwOnMissingStub(this); } @@ -118,7 +127,8 @@ class MockWorkoutSessionRepository extends _i1.Mock implements _i8.WorkoutSessio /// A class which mocks [ExerciseRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockExerciseRepository extends _i1.Mock implements _i11.ExerciseRepository { +class MockExerciseRepository extends _i1.Mock + implements _i11.ExerciseRepository { MockExerciseRepository() { _i1.throwOnMissingStub(this); } @@ -206,7 +216,8 @@ class MockExerciseRepository extends _i1.Mock implements _i11.ExerciseRepository /// A class which mocks [RoutinesRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockRoutinesRepository extends _i1.Mock implements _i19.RoutinesRepository { +class MockRoutinesRepository extends _i1.Mock + implements _i19.RoutinesRepository { MockRoutinesRepository() { _i1.throwOnMissingStub(this); } @@ -513,3 +524,54 @@ class MockTrophyRepository extends _i1.Mock implements _i22.TrophyRepository { ) as _i9.Future>); } + +/// A class which mocks [WorkoutLogRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWorkoutLogRepository extends _i1.Mock + implements _i27.WorkoutLogRepository { + MockWorkoutLogRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i9.Stream> watchLogsByExerciseDrift({ + required int? routineId, + required int? exerciseId, + }) => + (super.noSuchMethod( + Invocation.method(#watchLogsByExerciseDrift, [], { + #routineId: routineId, + #exerciseId: exerciseId, + }), + returnValue: _i9.Stream>.empty(), + ) + as _i9.Stream>); + + @override + _i9.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i9.Future.value(), + returnValueForMissingStub: _i9.Future.value(), + ) + as _i9.Future); + + @override + _i9.Future updateLocalDrift(_i28.Log? log) => + (super.noSuchMethod( + Invocation.method(#updateLocalDrift, [log]), + returnValue: _i9.Future.value(), + returnValueForMissingStub: _i9.Future.value(), + ) + as _i9.Future); + + @override + _i9.Future addLocalDrift(_i28.Log? log) => + (super.noSuchMethod( + Invocation.method(#addLocalDrift, [log]), + returnValue: _i9.Future.value(), + returnValueForMissingStub: _i9.Future.value(), + ) + as _i9.Future); +} diff --git a/test/routine/routine_logs_screen_test.mocks.dart b/test/routine/routine_logs_screen_test.mocks.dart index 0d80a5b9f..49f3cd969 100644 --- a/test/routine/routine_logs_screen_test.mocks.dart +++ b/test/routine/routine_logs_screen_test.mocks.dart @@ -30,7 +30,8 @@ import 'package:wger/providers/workout_logs_repository.dart' as _i9; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member -class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { +class _FakeWgerBaseProvider_0 extends _i1.SmartFake + implements _i2.WgerBaseProvider { _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -131,11 +132,26 @@ class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { /// A class which mocks [WorkoutLogRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockWorkoutLogRepository extends _i1.Mock implements _i9.WorkoutLogRepository { +class MockWorkoutLogRepository extends _i1.Mock + implements _i9.WorkoutLogRepository { MockWorkoutLogRepository() { _i1.throwOnMissingStub(this); } + @override + _i5.Stream> watchLogsByExerciseDrift({ + required int? routineId, + required int? exerciseId, + }) => + (super.noSuchMethod( + Invocation.method(#watchLogsByExerciseDrift, [], { + #routineId: routineId, + #exerciseId: exerciseId, + }), + returnValue: _i5.Stream>.empty(), + ) + as _i5.Stream>); + @override _i5.Future deleteLocalDrift(String? id) => (super.noSuchMethod( diff --git a/test/routine/workout_logs_repository_test.dart b/test/routine/workout_logs_repository_test.dart index 1335d7ec1..2bc2d3cc5 100644 --- a/test/routine/workout_logs_repository_test.dart +++ b/test/routine/workout_logs_repository_test.dart @@ -58,6 +58,15 @@ void main() { Future> readLogs() => db.select(db.workoutLogTable).get(); Future> readSessions() => db.select(db.workoutSessionTable).get(); + Future seedUnits() async { + await db + .into(db.routineRepetitionUnitTable) + .insert(RoutineRepetitionUnitTableCompanion.insert(id: 1, name: 'Repetitions')); + await db + .into(db.routineWeightUnitTable) + .insert(RoutineWeightUnitTableCompanion.insert(id: 1, name: 'kg')); + } + group('addLocalDrift, log already has a sessionId', () { test('inserts the log without touching the session table', () async { final log = makeLog(sessionId: 'existing-session'); @@ -177,4 +186,73 @@ void main() { expect(await readLogs(), hasLength(1)); }); }); + + group('watchLogsByExerciseDrift', () { + test('emits an empty list when nothing matches', () async { + expect(await repo.watchLogsByExerciseDrift(routineId: 100, exerciseId: 1).first, isEmpty); + }); + + test('returns only logs for the given routine and exercise', () async { + await seedUnits(); + await db + .into(db.workoutLogTable) + .insert(makeLog(exerciseId: 1, routineId: 100).toCompanion()); + // Different exercise, same routine. + await db + .into(db.workoutLogTable) + .insert(makeLog(exerciseId: 2, routineId: 100).toCompanion()); + // Same exercise, different routine. + await db + .into(db.workoutLogTable) + .insert(makeLog(exerciseId: 1, routineId: 999).toCompanion()); + + final logs = await repo.watchLogsByExerciseDrift(routineId: 100, exerciseId: 1).first; + + expect(logs, hasLength(1)); + expect(logs.single.exerciseId, 1); + expect(logs.single.routineId, 100); + }); + + test('sorts by date descending', () async { + await seedUnits(); + // Tag each row with a distinct weight so the order can be asserted without + // depending on the timezone the date converter reads back in. + await db + .into(db.workoutLogTable) + .insert(makeLog(date: DateTime.utc(2026, 4, 14), weight: 14).toCompanion()); + await db + .into(db.workoutLogTable) + .insert(makeLog(date: DateTime.utc(2026, 4, 16), weight: 16).toCompanion()); + await db + .into(db.workoutLogTable) + .insert(makeLog(date: DateTime.utc(2026, 4, 15), weight: 15).toCompanion()); + + final logs = await repo.watchLogsByExerciseDrift(routineId: 100, exerciseId: 1).first; + + expect(logs.map((l) => l.weight).toList(), [16, 15, 14]); + }); + + test('attaches the repetition and weight unit to each log', () async { + await seedUnits(); + await db.into(db.workoutLogTable).insert(makeLog().toCompanion()); + + final logs = await repo.watchLogsByExerciseDrift(routineId: 100, exerciseId: 1).first; + + expect(logs.single.repetitionsUnitObj?.name, 'Repetitions'); + expect(logs.single.weightUnitObj?.name, 'kg'); + }); + + test('re-emits when a matching log is added', () async { + await seedUnits(); + final stream = repo.watchLogsByExerciseDrift(routineId: 100, exerciseId: 1); + final emissions = >[]; + final sub = stream.listen(emissions.add); + + await db.into(db.workoutLogTable).insert(makeLog().toCompanion()); + await pumpEventQueue(); + + expect(emissions.last, hasLength(1)); + await sub.cancel(); + }); + }); } diff --git a/test/widgets/routines/gym_mode/log_page_test.dart b/test/widgets/routines/gym_mode/log_page_test.dart index 6ede5aecd..9fdf8ffb4 100644 --- a/test/widgets/routines/gym_mode/log_page_test.dart +++ b/test/widgets/routines/gym_mode/log_page_test.dart @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -33,6 +35,7 @@ import 'package:wger/models/workouts/slot_data.dart'; import 'package:wger/providers/gym_state.dart'; import 'package:wger/providers/gym_state_notifier.dart'; import 'package:wger/providers/workout_logs_repository.dart'; +import 'package:wger/widgets/core/error.dart'; import 'package:wger/widgets/routines/gym_mode/log_page.dart'; import '../../../../test_data/exercises.dart'; @@ -53,6 +56,17 @@ void main() { testExercises = getTestExercises(); mockWorkoutLogRepo = MockWorkoutLogRepository(); when(mockWorkoutLogRepo.addLocalDrift(any)).thenAnswer((_) async {}); + // Past logs on the page come from this stream (per exercise); reuse the + // test routine's logs so the previous-entries assertions keep working. + when( + mockWorkoutLogRepo.watchLogsByExerciseDrift( + routineId: anyNamed('routineId'), + exerciseId: anyNamed('exerciseId'), + ), + ).thenAnswer((invocation) { + final exerciseId = invocation.namedArguments[#exerciseId] as int; + return Stream.value(testdata.getTestRoutine().filterLogsByExercise(exerciseId)); + }); container = ProviderContainer.test( overrides: [workoutLogRepositoryProvider.overrideWithValue(mockWorkoutLogRepo)], ); @@ -164,6 +178,27 @@ void main() { expect(find.byType(SnackBar), findsOneWidget); }); + testWidgets('shows an error indicator when past logs fail to load', (tester) async { + // Error via a stream event (not a build throw), so riverpod surfaces it + // as state instead of scheduling a retry timer. + final controller = StreamController>(); + addTearDown(controller.close); + when( + mockWorkoutLogRepo.watchLogsByExerciseDrift( + routineId: anyNamed('routineId'), + exerciseId: anyNamed('exerciseId'), + ), + ).thenAnswer((_) => controller.stream); + + seedLogPage(testdata.getTestRoutine()); + await pumpLogPage(tester); + + controller.addError(Exception('boom')); + await tester.pumpAndSettle(); + + expect(find.byType(StreamErrorIndicator), findsOneWidget); + }); + testWidgets('save button persists the entered reps/weight with slot/routine/iteration', ( tester, ) async { diff --git a/test/widgets/routines/gym_mode/log_page_test.mocks.dart b/test/widgets/routines/gym_mode/log_page_test.mocks.dart index 88f640048..14b8dbdb8 100644 --- a/test/widgets/routines/gym_mode/log_page_test.mocks.dart +++ b/test/widgets/routines/gym_mode/log_page_test.mocks.dart @@ -27,11 +27,26 @@ import 'package:wger/providers/workout_logs_repository.dart' as _i2; /// A class which mocks [WorkoutLogRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogRepository { +class MockWorkoutLogRepository extends _i1.Mock + implements _i2.WorkoutLogRepository { MockWorkoutLogRepository() { _i1.throwOnMissingStub(this); } + @override + _i3.Stream> watchLogsByExerciseDrift({ + required int? routineId, + required int? exerciseId, + }) => + (super.noSuchMethod( + Invocation.method(#watchLogsByExerciseDrift, [], { + #routineId: routineId, + #exerciseId: exerciseId, + }), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + @override _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod(