Offline gym log for Android. No account, no ads, no internet.
Dart androidbodybuildingdartexercisesf-droidfitnessfluttergymgym-apphealthprivacyself-hostedworkoutworkout-appworkout-tracker
Cover the new features, the backup and the shell transition with tests
InlitXdaf900b2f0cd
diff --git a/test/backup_complete_test.dart b/test/backup_complete_test.dartnew file mode 100644index 0000000..d5aa725--- /dev/null+++ b/test/backup_complete_test.dart@@ -0,0 +1,275 @@+import 'dart:io';+import 'dart:typed_data';++import 'package:archive/archive.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/catalog/exercise_catalog.dart';+import 'package:gymmane/models/note.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/services/backup_zip.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/services/media_store.dart';+import 'package:gymmane/services/progress_reminder.dart';+import 'package:gymmane/services/train_reminder.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ late Directory tmp;+ final png = Uint8List.fromList([0x89, 0x50, 0x4E, 0x47, 9, 9, 9, 9]);+ final mp4 = Uint8List.fromList(List<int>.generate(48, (i) => i));++ final bench = kExercises.firstWhere((e) => e.name == 'Barbell Bench Press');+ final squat = kExercises.firstWhere((e) => e.name == 'Barbell Front Squat');+ final pushUp = kExercises.firstWhere((e) => e.equipment == 'Bodyweight');++ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ tmp = await Directory.systemTemp.createTemp('gymmane_full');+ MediaStore.directory = tmp.path;+ ProgressReminder.instance.enabled = false;+ TrainReminder.instance.enabled = false;+ fit.resetAllData();+ });++ tearDown(() async {+ MediaStore.directory = null;+ if (tmp.existsSync()) await tmp.delete(recursive: true);+ });++ Future<String> source(String name, Uint8List bytes) async {+ final f = File('${tmp.path}/$name');+ await f.writeAsBytes(bytes, flush: true);+ return f.path;+ }++ Future<void> seedTwoYears() async {+ final start = DateTime(2024, 9, 1, 19, 30);+ for (var week = 0; week < 104; week++) {+ for (final day in [0, 3]) {+ final when = start.add(Duration(days: week * 7 + day));+ fit.sessions.add(LoggedSession(when, 3600 + week, [+ LoggedExercise(bench.id, bench.name, bench.primary, [+ LoggedSet(10, 60 + week * 0.25, rpe: 8),+ LoggedSet(8, 60 + week * 0.25),+ LoggedSet(6, 60 + week * 0.25, kind: SetKind.failure),+ ]),+ LoggedExercise(squat.id, squat.name, squat.primary, [+ LoggedSet(5, 100 + week * 0.5, kind: SetKind.warmup),+ LoggedSet(5, 100 + week * 0.5),+ ]),+ ]));+ }+ fit.bodyweight.add(BodyweightEntry(start.add(Duration(days: week * 7)), 80 - week * 0.05));+ }+ fit.sessions.sort((a, b) => a.date.compareTo(b.date));++ fit.updateProfile(name: 'InlitX', sex: 'male', ageDelta: 3, weeklyGoalDelta: 1);+ fit.setUnits('lb');+ fit.setThemeLight();+ fit.setBgDim(0.72);++ final custom = fit.addCustomExercise(+ name: 'Sentadilla búlgara', primary: 'quads', equipment: 'Bodyweight');+ await fit.attachExerciseMedia(custom, await source('custom.png', png));+ await fit.attachExerciseMedia(bench.id, await source('bench.mp4', mp4));+ await fit.setBgPhoto(await source('bg.png', png));++ fit.toggleFavorite(bench.id);+ fit.toggleRepsOnly(pushUp.id);+ fit.setExerciseRest(bench.id, 180);+ fit.toggleProgress(bench.id);+ fit.toggleAutoWarmup(squat.id);+ fit.toggleCheckin(0);++ final place = fit.addPlace('Casa', equipment: {'Barbell', 'Dumbbell'});+ fit.setActivePlace(place);+ fit.setPlatePairs(place, 20, 2);+ fit.setPlatePairs(place, 10, 3);+ fit.setPlaceBar(place, 15);++ final routine = fit.createRoutine('Push');+ fit.toggleRoutineExercise(routine, bench.id);+ fit.toggleRoutineExercise(routine, squat.id);+ fit.bumpRoutineSets(routine, bench.id, 2);+ fit.toggleChain(routine, bench.id);+ fit.setRoutineGroup(routine, 'PPL');+ fit.assignRoutineToDay(1, routine);++ fit.saveNote(+ exerciseId: bench.id,+ date: DateTime(2025, 3, 4),+ kind: NoteKind.done,+ text: 'Primer 100 limpio',+ media: [(await MediaStore.importFor('note', await source('note.png', png)))!],+ );++ for (final day in [DateTime(2025, 1, 5), DateTime(2025, 7, 5), DateTime(2026, 1, 5)]) {+ for (final pose in ['front', 'side', 'back']) {+ await fit.attachShot(day, pose, await source('$pose-${day.month}.png', png));+ }+ }+ fit.setPhotoInterval(30);+ fit.addMeasure('chest', 104);+ fit.addMeasure('arm', 38.5);+ fit.setTrainReminder(19 * 60 + 15);+ fit.setSmartReminder(true);+ fit.toggleLogRpe();+ fit.toggleAutoAdvance();+ fit.toggleFocusCard();++ fit.setProfileHandle('inlitx');+ fit.setProfileBadge('gold');+ fit.setProfilePhoto(png);+ fit.setProfileBanner(mp4);+ fit.refreshAwards(silent: true);+ await fit.addMoment(await source('moment.png', png), note: 'Primer día');+ }++ test('dos años de uso entran y salen de la copia sin perder nada', () async {+ await seedTwoYears();++ final before = {+ 'sesiones': fit.sessions.length,+ 'volumen': fit.sessions.fold<double>(0, (a, s) => a + s.volume).round(),+ 'series': fit.sessions.fold<int>(0, (a, s) => a + s.setCount),+ 'primera': fit.sessions.first.date,+ 'ultima': fit.sessions.last.date,+ 'peso': fit.bodyweight.length,+ 'notas': fit.notes.length,+ 'fotos': fit.timeline.length,+ 'medidas': fit.measures.length,+ 'propios': fit.customExercises.length,+ 'rutinas': fit.routines.length,+ 'sitios': fit.places.length,+ };+ final rpeBefore = fit.sessions.first.exercises.first.sets.first.rpe;+ final zip = await buildBackupZip();++ fit.resetAllData();+ expect(fit.sessions, isEmpty);+ expect(await restoreBackupZip(zip), isTrue);++ expect(fit.sessions.length, before['sesiones']);+ expect(fit.sessions.fold<double>(0, (a, s) => a + s.volume).round(), before['volumen']);+ expect(fit.sessions.fold<int>(0, (a, s) => a + s.setCount), before['series']);+ expect(fit.sessions.first.date, before['primera']);+ expect(fit.sessions.last.date, before['ultima']);+ expect(fit.sessions.first.exercises.first.sets.first.rpe, rpeBefore);+ expect(fit.sessions.first.exercises.last.sets.first.kind, SetKind.warmup);+ expect(fit.bodyweight.length, before['peso']);+ expect(fit.notes.length, before['notas']);+ expect(fit.timeline.length, before['fotos']);+ expect(fit.measures.length, before['medidas']);+ expect(fit.customExercises.length, before['propios']);+ expect(fit.routines.length, before['rutinas']);+ expect(fit.places.length, before['sitios']);+ });++ test('vuelven todas las fotos, los vídeos y el fondo, byte a byte', () async {+ await seedTwoYears();+ final zip = await buildBackupZip();+ fit.resetAllData();+ expect(await restoreBackupZip(zip), isTrue);++ expect(await MediaStore.readBytes(fit.mediaFor(bench.id)), mp4);+ final custom = fit.customExercises.single;+ expect(await MediaStore.readBytes(fit.mediaFor(custom.id)), png);+ expect(await MediaStore.readBytes(fit.bgPhoto!), png);+ expect(await MediaStore.readBytes(fit.notes.single.media.single), png);++ expect(fit.timeline.length, 3);+ for (final entry in fit.timeline) {+ expect(entry.shots.keys, containsAll(['front', 'side', 'back']));+ for (final pose in ['front', 'side', 'back']) {+ expect(await MediaStore.readBytes(entry.shot(pose)!), png);+ }+ }+ });++ test('las fotos del timeline van en su carpeta por fecha', () async {+ await seedTwoYears();+ final zip = await buildBackupZip();+ final names = ZipDecoder().decodeBytes(zip).files.map((f) => f.name).toList();++ expect(names, contains('timeline/2025-01-05/front.png'));+ expect(names, contains('timeline/2025-07-05/side.png'));+ expect(names, contains('timeline/2026-01-05/back.png'));+ expect(names.where((n) => n.startsWith('timeline/')).length, 9);+ expect(names.any((n) => n.startsWith('media/videos/')), isTrue);+ expect(names.any((n) => n.startsWith('media/notes/')), isTrue);+ });++ test('vuelven todos los ajustes, incluidos los nuevos', () async {+ await seedTwoYears();+ final zip = await buildBackupZip();+ fit.resetAllData();+ expect(await restoreBackupZip(zip), isTrue);++ expect(fit.units, 'lb');+ expect(fit.dark, isFalse);+ expect(fit.profile.name, 'InlitX');+ expect(fit.profile.weeklyGoal, 5);+ expect(fit.bgPattern, 'photo');+ expect(fit.bgDim, 0.72);+ expect(fit.showFocus, isFalse);+ expect(fit.autoAdvance, isFalse);+ expect(fit.logRpe, isTrue);+ expect(fit.smartReminder, isTrue);+ expect(fit.trainReminderMin, 19 * 60 + 15);+ expect(fit.photoIntervalDays, 30);+ expect(fit.favorites[bench.id], isTrue);+ expect(fit.isRepsOnly(pushUp.id), isFalse);+ expect(fit.restFor(bench.id), 180);+ expect(fit.hasProgress(bench.id), isTrue);+ expect(fit.warmsUp(squat.id), isTrue);+ expect(fit.checkins, isNotEmpty);+ });++ test('vuelven la identidad, las medallas y los momentos', () async {+ await seedTwoYears();+ final awardsBefore = fit.awards.length;+ final zip = await buildBackupZip();++ fit.resetAllData();+ expect(fit.moments, isEmpty);+ expect(await restoreBackupZip(zip), isTrue);++ expect(fit.profile.handle, 'inlitx');+ expect(fit.profile.badge, 'gold');+ expect(fit.profilePhoto, png);+ expect(fit.profileBanner, mp4);+ expect(fit.awards.length, awardsBefore);+ expect(awardsBefore, greaterThan(0));+ expect(fit.moments.single.note, 'Primer día');+ expect(File('${tmp.path}/${fit.moments.single.file}').existsSync(), isTrue,+ reason: 'la foto del momento no viajó en la copia');+ });++ test('vuelven la rutina con sus series, su cadena y su grupo, y el sitio con sus discos',+ () async {+ await seedTwoYears();+ final zip = await buildBackupZip();+ fit.resetAllData();+ expect(await restoreBackupZip(zip), isTrue);++ final routine = fit.routines.single;+ expect(routine.name, 'Push');+ expect(routine.group, 'PPL');+ expect(routine.exerciseIds, [bench.id, squat.id]);+ expect(fit.routineSets(routine, bench.id), 5);+ expect(fit.chainsToNext(routine, bench.id), isTrue);+ expect(fit.weeklyPlan[1], routine.id);++ final place = fit.places.single;+ expect(place.name, 'Casa');+ expect(place.equipment, containsAll(['Barbell', 'Dumbbell']));+ expect(fit.platePairs(place, 20), 2);+ expect(fit.platePairs(place, 10), 3);+ expect(place.bar, 15);+ expect(fit.activePlaceId, place.id);+ });+}diff --git a/test/backup_zip_test.dart b/test/backup_zip_test.dartindex abd1ba0..240f9da 100644--- a/test/backup_zip_test.dart+++ b/test/backup_zip_test.dart@@ -173,8 +173,8 @@ void main() {final zip = await buildBackupZip();final names = ZipDecoder().decodeBytes(zip).files.map((f) => f.name);- expect(names, contains('media/progress/2026-02-01-front.png'));- expect(names, contains('media/progress/2026-02-01-back.png'));+ expect(names, contains('timeline/2026-02-01/front.png'));+ expect(names, contains('timeline/2026-02-01/back.png'));fit.resetAllData();expect(await restoreBackupZip(zip), true);@@ -191,7 +191,7 @@ void main() {final zip = await buildBackupZip();final stripped = Archive();for (final f in ZipDecoder().decodeBytes(zip).files) {- if (f.name.startsWith('media/progress/')) continue;+ if (f.name.startsWith('timeline/')) continue;final bytes = f.readBytes()!;stripped.addFile(ArchiveFile.noCompress(f.name, bytes.length, bytes));}diff --git a/test/exercise_notes_test.dart b/test/exercise_notes_test.dartindex d5ad599..f807664 100644--- a/test/exercise_notes_test.dart+++ b/test/exercise_notes_test.dart@@ -7,6 +7,7 @@ import 'package:gymmane/screens/notes_screen.dart';import 'package:gymmane/state/fit_state.dart';import 'package:gymmane/theme/app_theme.dart';import 'package:gymmane/widgets/note_kit.dart';+import 'package:gymmane/widgets/ui_kit.dart';Widget _host(Widget Function() screen) => MaterialApp(theme: AppTheme.dark,@@ -78,7 +79,7 @@ void main() {expect(find.text('nota 10'), findsNothing);- await tapVisible(tester, find.text(t.notes));+ await tapVisible(tester, find.text(titleCase(t.notes)));expect(fit.route, 'notes');expect(fit.noteScope, exId);expect(fit.notesAllView, isFalse);diff --git a/test/flow_test.dart b/test/flow_test.dartindex 77776bf..6877fb0 100644--- a/test/flow_test.dart+++ b/test/flow_test.dart@@ -56,7 +56,6 @@ void main() {expect(fit.trainStep, 'select');expect(fit.selectedMuscles, suggested.muscles);- // Can proceed to review directlyfit.trainContinue();expect(fit.trainStep, 'review');expect(fit.sessionPicks, isNotEmpty);diff --git a/test/home_widgets_test.dart b/test/home_widgets_test.dartindex f2fa6eb..beaff12 100644--- a/test/home_widgets_test.dart+++ b/test/home_widgets_test.dart@@ -14,7 +14,7 @@ void main() {}for (final (name, gc) in [('dark', GymColors.dark), ('light', GymColors.light)]) {- testWidgets('the three home widgets draw in $name without overflowing', (tester) async {+ testWidgets('the four home widgets draw in $name without overflowing', (tester) async {await draw(tester, HeatmapWidgetView(gc: gc, levels: List.filled(182, 2), streak: 12));await draw(tester,StatsWidgetView(gc: gc, streak: 12, sessionsThisWeek: 3, goalPct: 75));@@ -25,6 +25,9 @@ void main() {days: 7,intensity: const {'chest': 1.0, 'back': 0.5, 'quads': 0.1},));+ await draw(tester, TodayWidgetView(gc: gc, done: true, planned: true, streak: 12));+ await draw(tester, TodayWidgetView(gc: gc, done: false, planned: true, streak: 0));+ await draw(tester, TodayWidgetView(gc: gc, done: false, planned: false, streak: 0));});}diff --git a/test/import_test.dart b/test/import_test.dartindex 29f6e5e..c3dcd18 100644--- a/test/import_test.dart+++ b/test/import_test.dart@@ -42,6 +42,59 @@ date,exercise,muscle,set,reps,weight_kg,volume_kg,est_1rm_kg2024-01-16,Barbell Bench Press,chest,1,10,60,600,80''';+const _generic = '''+Date,Exercise,Reps,Weight,RiR+2024-02-01,Bench Press,10,60,2+2024-02-01,Bench Press,8,62.5,1+2024-02-01,Squat,5,100,+''';++const _genericDe = '''+Datum;Übung;Wiederholungen;Gewicht+2024-02-02;Kniebeuge;5;100+''';++const _openGym = '''+{+ "unit": "kg",+ "routines": [],+ "customEx": [{"id": "im1", "n": "Sled Drag", "custom": true}],+ "bodyweight": [{"d": "2024-01-20", "w": 81.4, "t": 1705750000000}],+ "workouts": [+ {+ "id": "w1",+ "d": "2024-01-20",+ "start": 1705750000000,+ "end": 1705753600000,+ "name": "Push",+ "entries": [+ {"id": "0025", "sets": [+ {"w": 20, "r": 10, "done": true, "phase": "warmup"},+ {"w": 60, "r": 8, "done": true},+ {"w": 60, "r": 7, "done": true},+ {"w": 60, "r": 6, "done": false}+ ]},+ {"id": "0294", "sets": [{"w": 12, "r": 12, "done": true}]},+ {"id": "im1", "sets": [{"w": 40, "r": 20, "done": true}]},+ {"id": "9999", "sets": [{"w": 30, "r": 10, "done": true}]}+ ]+ }+ ]+}+''';++const _openGymLb = '''+{+ "unit": "lb",+ "routines": [],+ "workouts": [+ {"id": "w1", "d": "2024-01-21", "start": 1705836000000, "end": 1705836000000,+ "entries": [{"id": "0043", "sets": [{"w": 220, "r": 5, "done": true}]}]}+ ],+ "bodyweight": [{"d": "2024-01-21", "w": 180}]+}+''';+void main() {group('detección de formato', () {test('reconoce cada app', () {@@ -51,6 +104,8 @@ void main() {expect(detectFormat(_fitnotesUnits), ImportFormat.fitnotes);expect(detectFormat(_gymmane), ImportFormat.gymmane);expect(detectFormat('a,b,c\n1,2,3'), ImportFormat.unknown);+ expect(detectFormat(_generic), ImportFormat.generic);+ expect(detectFormat(_genericDe), ImportFormat.generic);expect(detectFormat(''), ImportFormat.unknown);});@@ -63,6 +118,30 @@ void main() {});});+ group('CSV genérico de cualquier app', () {+ test('agrupa por día y respeta las columnas en inglés', () {+ final r = parseImport(_generic);+ expect(r.format, ImportFormat.generic);+ expect(r.sessions.length, 1);+ final s = r.sessions.first;+ expect(s.exercises.length, 2);+ expect(s.exercises.first.name, 'Bench Press');+ expect(s.exercises.first.sets.length, 2);+ expect(s.exercises.first.sets.first.weightKg, 60);+ expect(s.exercises.last.sets.single.reps, 5);+ });++ test('lee cabeceras en otro idioma y con punto y coma', () {+ final r = parseImport(_genericDe);+ expect(r.sessions.single.exercises.single.name, 'Kniebeuge');+ expect(r.sessions.single.exercises.single.sets.single.weightKg, 100);+ });++ test('pregunta la unidad porque la columna no la dice', () {+ expect(needsUnitChoice(_generic), isTrue);+ });+ });+group('parseo', () {test('Hevy agrupa la sesión y saca la duración de start/end', () {final r = parseImport(_hevy);@@ -121,6 +200,36 @@ void main() {});});+ group('openGym', () {+ test('reconoce el backup y lo parsea', () {+ expect(detectFormat(_openGym), ImportFormat.openGym);+ expect(needsUnitChoice(_openGym), isFalse);+ final r = parseImport(_openGym);+ final s = r.sessions.single;+ expect(s.date, DateTime.fromMillisecondsSinceEpoch(1705750000000));+ expect(s.durationSec, 3600);+ expect(s.exercises.length, 3, reason: 'el ejercicio que no está en el catálogo se cae');+ expect(s.exercises.first.id, 'EIeI8Vf');+ expect(s.exercises.first.sets.length, 2,+ reason: 'fuera el calentamiento y la serie sin marcar');+ expect(s.exercises.first.sets.first.weightKg, 60);+ expect(s.exercises[1].id, 'NbVPDMW');+ expect(s.exercises.last.name, 'Sled Drag');+ expect(r.weights.single.kg, 81.4);+ });++ test('convierte a kg cuando el backup está en libras', () {+ final r = parseImport(_openGymLb);+ expect(r.sessions.single.exercises.single.sets.single.weightKg, closeTo(99.79, 0.05));+ expect(r.sessions.single.durationSec, 0);+ expect(r.weights.single.kg, closeTo(81.65, 0.05));+ });++ test('no confunde un backup de GymMane con uno de openGym', () {+ expect(detectFormat('{"sessions": [], "routines": []}'), ImportFormat.unknown);+ });+ });+group('fusión en el estado', () {setUp(() => fit.sessions.clear());diff --git a/test/live_session_test.dart b/test/live_session_test.dartindex 9535fb8..d5e551d 100644--- a/test/live_session_test.dart+++ b/test/live_session_test.dart@@ -77,10 +77,23 @@ void main() {expect(fit.sessionElapsed, frozen, reason: 'en pausa el reloj no corre ni estando muerta');});- test('the rest timer is not resurrected — that rest already happened', () {+ test('a rest still running comes back with the time it really has left', () {startAndLog();fit.startRest();- expect(fit.session!.restRemaining, isNotNull);+ final left = fit.session!.restRemaining!;++ killAndReopen();++ expect(fit.session!.restRemaining, isNotNull,+ reason: 'la alarma sigue programada, así que la cuenta tiene que seguir en pantalla');+ expect(fit.session!.restRemaining, lessThanOrEqualTo(left),+ reason: 'el descanso cuenta por reloj, no se reinicia');+ });++ test('a rest whose time already passed is not resurrected', () {+ startAndLog();+ fit.startRest();+ fit.session!.restEndsAt = DateTime.now().subtract(const Duration(seconds: 1));killAndReopen();expect(fit.session!.restRemaining, isNull);diff --git a/test/persistence_test.dart b/test/persistence_test.dartindex 66e4ca3..c9849d9 100644--- a/test/persistence_test.dart+++ b/test/persistence_test.dart@@ -22,6 +22,13 @@ void main() {fit.customExercises.clear();fit.profile = Profile();fit.setUnits('kg');+ fit.progressStep.clear();+ fit.autoWarmup.clear();+ fit.logRpe = false;+ fit.autoAdvance = true;+ fit.showFocus = true;+ fit.smartReminder = false;+ fit.trainReminderMin = null;});void fillEverything() {@@ -40,6 +47,17 @@ void main() {fit.toggleRoutineExercise(r, kFirstId);fit.assignRoutineToDay(1, r);fit.addCustomExercise(name: 'Mi ejercicio', primary: 'chest', equipment: 'Other');+ fit.toggleProgress(kFirstId);+ fit.toggleAutoWarmup(kFirstId);+ fit.toggleLogRpe();+ fit.toggleAutoAdvance();+ fit.toggleFocusCard();+ fit.setBgDim(0.72);+ fit.setTrainReminder(7 * 60 + 45);+ fit.setSmartReminder(true);+ fit.toggleChain(r, kFirstId);+ fit.setRoutineGroup(r, 'PPL');+ fit.bumpRoutineSets(r, kFirstId, 2);fit.startWorkout();fit.toggleMuscle('chest');@@ -66,6 +84,17 @@ void main() {expect(fit.weeklyPlan[1], fit.routines.single.id);expect(fit.customExercises.single.name, 'Mi ejercicio');expect(fit.sessions.single.exercises.single.sets.single.reps, 10);+ expect(fit.hasProgress(kFirstId), isTrue);+ expect(fit.warmsUp(kFirstId), isTrue);+ expect(fit.logRpe, isTrue);+ expect(fit.autoAdvance, isFalse);+ expect(fit.showFocus, isFalse);+ expect(fit.bgDim, 0.72);+ expect(fit.trainReminderMin, 7 * 60 + 45);+ expect(fit.smartReminder, isTrue);+ expect(fit.routines.single.chained, contains(kFirstId));+ expect(fit.routines.single.group, 'PPL');+ expect(fit.routineSets(fit.routines.single, kFirstId), 5);}test('everything survives a restart', () async {@@ -100,7 +129,7 @@ void main() {final empty = fit.exportJson();expect(fit.importJson(empty), true);expect(fit.sessions, isEmpty);- expect(fit.profile.name, 'InlitX');+ expect(fit.profile.name, kDefaultName);});test('old backups with the previous notes format still load', () {diff --git a/test/places_test.dart b/test/places_test.dartindex 1725916..30b2332 100644--- a/test/places_test.dart+++ b/test/places_test.dart@@ -174,6 +174,9 @@ void main() {await tester.pumpWidget(const GymManeApp());await tester.pumpAndSettle();+ await tester.tap(find.text(t.filters));+ await tester.pumpAndSettle();+expect(find.text(t.placeAll), findsOneWidget);await tester.tap(find.text('Casa'));await tester.pumpAndSettle();diff --git a/test/plan_share_test.dart b/test/plan_share_test.dartnew file mode 100644index 0000000..7ce3acb--- /dev/null+++ b/test/plan_share_test.dart@@ -0,0 +1,71 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/services/plan_share.dart';+import 'package:gymmane/state/fit_state.dart';++void main() {+ group('lectura del JSON', () {+ test('lee una rutina simple', () {+ final plans = parsePlan('{"name":"Push","exercises":["Barbell Bench Press","Push-Up"]}');+ expect(plans.length, 1);+ expect(plans.first.name, 'Push');+ expect(plans.first.items.length, 2);+ expect(plans.first.items.first.sets, isNull);+ });++ test('lee series por ejercicio y varias rutinas', () {+ final plans = parsePlan(+ '{"routines":[{"name":"A","exercises":[{"name":"Squat","sets":5}]},'+ '{"title":"B","ejercicios":[{"exercise":"Deadlift"}]}]}');+ expect(plans.length, 2);+ expect(plans.first.items.single.sets, 5);+ expect(plans.last.name, 'B');+ });++ test('aguanta la prosa y las vallas de código de una IA', () {+ final plans = parsePlan('Sure! Here you go:\n```json\n'+ '{"name":"Full body","exercises":["Squat"]}\n```\nEnjoy.');+ expect(plans.single.name, 'Full body');+ });++ test('un archivo que no es un plan devuelve nada', () {+ expect(parsePlan('hola'), isEmpty);+ expect(parsePlan('{"name":"Push"}'), isEmpty);+ });+ });++ group('importar en el estado', () {+ setUp(() => fit.resetAllData());++ test('crea la rutina, empareja los nombres y guarda las series', () {+ final result = fit.importPlan(+ '{"name":"Empuje","exercises":[{"name":"Barbell Bench Press","sets":5},'+ '{"name":"no existe este ejercicio"}]}');+ expect(result.added, 1);+ expect(result.missed, ['no existe este ejercicio']);+ expect(result.readable, isTrue);+ final routine = fit.routines.single;+ expect(routine.name, 'Empuje');+ expect(routine.exerciseIds.length, 1);+ expect(fit.routineSets(routine, routine.exerciseIds.first), 5);+ });++ test('avisa cuando no hay nada que emparejar', () {+ final result = fit.importPlan('{"name":"X","exercises":["zzzz qqqq"]}');+ expect(result.added, 0);+ expect(result.readable, isTrue);+ expect(result.missed, ['zzzz qqqq']);+ expect(fit.routines, isEmpty);+ });++ test('un archivo ilegible se distingue de uno sin coincidencias', () {+ expect(fit.importPlan('no soy json').readable, isFalse);+ });+ });++ test('la lista para la IA lleva cabecera y ejercicios', () {+ final text = fit.planRequestText();+ expect(text.contains('GymMane'), isTrue);+ expect(text.contains('Barbell Bench Press'), isTrue);+ expect(text.split('\n').length, greaterThan(50));+ });+}diff --git a/test/polish_test.dart b/test/polish_test.dartindex 189af58..b8d0b25 100644--- a/test/polish_test.dart+++ b/test/polish_test.dart@@ -64,6 +64,17 @@ void main() {expect(fit.exercisesFiltered.length, fit.allExercises.length);});+ test('the muscle filter leads with the exercises that actually train it', () {+ fit.setMuscleFilter('back');+ final list = fit.exercisesFiltered;+ expect(list, isNotEmpty);+ final firstSecondary = list.indexWhere((e) => e.primary != 'back');+ final lastPrimary = list.lastIndexWhere((e) => e.primary == 'back');+ expect(firstSecondary == -1 || firstSecondary > lastPrimary, true,+ reason: 'los de espalda van antes que los que solo la tocan de apoyo');+ fit.clearExFilters();+ });+test('search finds exercises by their Spanish name too', () {setAppLanguage('es');fit.setExSearch('sentadilla');diff --git a/test/profile_test.dart b/test/profile_test.dartnew file mode 100644index 0000000..9d96334--- /dev/null+++ b/test/profile_test.dart@@ -0,0 +1,75 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.sessions.clear();+ fit.awards.clear();+ fit.awardsSeen.clear();+ fit.profile.badge = '';+ fit.profile.handle = '';+ fit.profile.since = null;+ });++ test('the handle falls back to the name until you set your own', () {+ fit.profile.name = 'Inlitx Lifts';+ expect(fit.profileHandle, 'inlitxlifts');++ fit.setProfileHandle(' my.handle! ');+ expect(fit.profileHandle, 'my.handle');+ });++ test('the badge is a toggle, not a one-way door', () {+ fit.setProfileBadge('blue');+ expect(fit.profile.badge, 'blue');++ fit.setProfileBadge('green');+ expect(fit.profile.badge, 'green');++ fit.setProfileBadge('green');+ expect(fit.profile.badge, '', reason: 'tocar la que tienes la quita');+ });++ test('the join date comes from the first workout, not from today', () {+ final old = DateTime.now().subtract(const Duration(days: 400));+ fit.sessions.add(LoggedSession(old, 1800, const []));+ fit.persistNow();+ fit.profile.since = null;+ fit.loadFromStore();++ expect(fit.memberSince.year, old.year);+ expect(fit.memberSince.month, old.month);+ });++ test('a medal is won once and keeps the day it was won', () {+ fit.sessions.addAll([+ for (var i = 0; i < 100; i++)+ LoggedSession(DateTime.now().subtract(Duration(days: i)), 1800, const []),+ ]);+ fit.refreshAwards();++ expect(fit.hasAward(AwardId.workouts100), true);+ expect(fit.unseenAwards, contains(AwardId.workouts100));+ final won = fit.awardWonAt(AwardId.workouts100);++ fit.sessions.add(LoggedSession(DateTime.now(), 1800, const []));+ fit.refreshAwards();+ expect(fit.awardWonAt(AwardId.workouts100), won, reason: 'no se vuelve a ganar');++ fit.markAwardsSeen();+ expect(fit.unseenAwards, isEmpty);+ });++ test('a medal you have not earned reports how far along you are', () {+ expect(fit.hasAward(AwardId.sets1000), false);+ expect(fit.awardProgress(AwardId.sets1000), 0);+ expect(fit.awardGoal(AwardId.sets1000), 1000);+ });+}diff --git a/test/progress_order_test.dart b/test/progress_order_test.dartindex 15a3a3e..642c778 100644--- a/test/progress_order_test.dart+++ b/test/progress_order_test.dart@@ -7,6 +7,7 @@ import 'package:gymmane/services/local_store.dart';import 'package:gymmane/services/progress_reminder.dart';import 'package:gymmane/services/train_reminder.dart';import 'package:gymmane/state/fit_state.dart';+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';import 'package:shared_preferences/shared_preferences.dart';void main() {@@ -41,34 +42,32 @@ void main() {return tester.getTopLeft(finder.first).dy;}- testWidgets('la gráfica va primero, luego el cuerpo y luego el mapa de días',- (tester) async {+ testWidgets('the numbers come first, then the grid, then the body', (tester) async {logSessions();fit.route = 'progress';await tester.pumpWidget(const GymManeApp());await tester.pumpAndSettle();- final chart = await yOf(tester, t.totalVolume30d);+ final volume = await yOf(tester, t.tileVolume30.toUpperCase());+ final heat = await yOf(tester, t.consistency.toUpperCase());final body = await yOf(tester, t.muscleMap);- final heat = await yOf(tester, t.consistency);- expect(chart, lessThan(body));- expect(body, lessThan(heat));+ expect(volume, lessThan(heat));+ expect(heat, lessThan(body));});- testWidgets('las tarjetas sin datos se van al final', (tester) async {+ testWidgets('a card with nothing in it is not drawn at all', (tester) async {logSessions();fit.route = 'progress';await tester.pumpWidget(const GymManeApp());await tester.pumpAndSettle();- final withData = await yOf(tester, t.personalRecords);- final empty = await yOf(tester, t.measures);-- expect(withData, lessThan(empty), reason: 'las medidas vacías deberían quedar debajo');+ expect(find.text(t.measures), findsNothing, reason: 'sin medidas, no hay tarjeta de medidas');+ expect(find.text(t.setupMeasures), findsOneWidget,+ reason: 'lo que falta se cuenta una sola vez, en la tarjeta de arranque');});- testWidgets('en cuanto hay datos, la tarjeta sube', (tester) async {+ testWidgets('the card shows up as soon as there is something to show', (tester) async {logSessions();fit.addMeasure('chest', 100);fit.persistNow();@@ -76,9 +75,21 @@ void main() {await tester.pumpWidget(const GymManeApp());await tester.pumpAndSettle();- final measures = await yOf(tester, t.measures);- final timeline = await yOf(tester, t.timeline);+ expect(find.text(t.measures), findsWidgets);+ expect(find.byIcon(PhosphorIconsFill.checkCircle), findsWidgets,+ reason: 'lo ya hecho se queda listado, pero con su tic');+ });++ testWidgets('a fresh install leads with what to fill in, not with empty cards', (tester) async {+ fit.route = 'progress';+ await tester.pumpWidget(const GymManeApp());+ await tester.pumpAndSettle();++ final setup = await yOf(tester, t.setupTitle);+ final volume = await yOf(tester, t.tileVolume30.toUpperCase());- expect(measures, lessThan(timeline), reason: 'con datos, las medidas van antes que lo vacío');+ expect(setup, lessThan(volume));+ expect(find.text(t.consistency.toUpperCase()), findsNothing,+ reason: 'una rejilla vacía no dice nada a quien acaba de instalar');});}diff --git a/test/reddit_requests_test.dart b/test/reddit_requests_test.dartnew file mode 100644index 0000000..fd4add9--- /dev/null+++ b/test/reddit_requests_test.dart@@ -0,0 +1,463 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/catalog/program_templates.dart';+import 'package:gymmane/models/live_session.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ String bench() => fit.matchExerciseByName('Barbell Bench Press')!.id;++ Routine routineWith(List<String> ids) {+ final id = fit.createRoutine('Push');+ for (final ex in ids) {+ fit.toggleRoutineExercise(id, ex);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ group('ejercicios propios en la rutina', () {+ test('el que te creas aparece al montar la rutina', () {+ final id = fit.addCustomExercise(name: 'Sentadilla búlgara', primary: 'quads', equipment: 'Bodyweight');+ expect(fit.exercisesMatching('').map((e) => e.id), contains(id));+ expect(fit.exercisesMatching('bulgara').map((e) => e.id), contains(id));+ });++ test('el selector de la rutina respeta los filtros de la biblioteca', () {+ fit.setEquipmentFilter('Bodyweight');+ expect(fit.exercisesMatching('').every((e) => e.equipment == 'Bodyweight'), isTrue);+ fit.clearExFilters();+ });+ });++ group('series planificadas', () {+ test('la sesión abre con las series que pusiste en la rutina', () {+ final r = routineWith([bench()]);+ fit.bumpRoutineSets(r.id, bench(), 2);+ expect(fit.routineSets(r, bench()), 5);++ fit.startRoutine(r);+ expect(fit.session!.exercises.single.sets.length, 5);+ });++ test('quitar el ejercicio se lleva sus series', () {+ final r = routineWith([bench()]);+ fit.bumpRoutineSets(r.id, bench(), 1);+ fit.toggleRoutineExercise(r.id, bench());+ expect(r.sets, isEmpty);+ });++ test('al marcar la última serie salta al siguiente ejercicio', () async {+ final squat = fit.matchExerciseByName('Barbell Squat') ?? fit.allExercises[1];+ final r = routineWith([bench(), squat.id]);+ fit.bumpRoutineSets(r.id, bench(), -2);+ fit.startRoutine(r);++ expect(fit.session!.exercises.first.sets.length, 1);+ fit.toggleSet(0, 0);+ expect(fit.session!.currentIndex, 0, reason: 'primero se ve el tic marcado');++ await Future<void>.delayed(WorkoutState.advanceDelay + const Duration(milliseconds: 200));+ expect(fit.session!.currentIndex, 1);+ });++ test('desmarcar antes de tiempo cancela el salto', () async {+ final squat = fit.matchExerciseByName('Barbell Squat') ?? fit.allExercises[1];+ final r = routineWith([bench(), squat.id]);+ fit.bumpRoutineSets(r.id, bench(), -2);+ fit.startRoutine(r);++ fit.toggleSet(0, 0);+ fit.toggleSet(0, 0);+ await Future<void>.delayed(WorkoutState.advanceDelay + const Duration(milliseconds: 200));+ expect(fit.session!.currentIndex, 0);+ });++ test('con el salto apagado se queda donde estaba', () async {+ fit.toggleAutoAdvance();+ final squat = fit.matchExerciseByName('Barbell Squat') ?? fit.allExercises[1];+ final r = routineWith([bench(), squat.id]);+ fit.bumpRoutineSets(r.id, bench(), -2);+ fit.startRoutine(r);+ fit.toggleSet(0, 0);+ await Future<void>.delayed(WorkoutState.advanceDelay + const Duration(milliseconds: 200));+ expect(fit.session!.currentIndex, 0);+ fit.toggleAutoAdvance();+ });+ });++ group('progresión automática', () {+ void logBench(int reps, double kg, int sets) {+ final r = routineWith([bench()]);+ fit.startRoutine(r);+ final session = fit.session!;+ while (session.exercises.first.sets.length > sets) {+ session.exercises.first.sets.removeLast();+ }+ for (var i = 0; i < sets; i++) {+ fit.setSessionReps(0, i, reps);+ fit.setSessionWeight(0, i, kg);+ fit.toggleSet(0, i);+ }+ fit.finishSession();+ fit.saveAndExit();+ }++ test('sube el peso cuando cumpliste todas las repes', () {+ fit.toggleProgress(bench());+ logBench(5, 60, 3);++ final r = fit.routines.first;+ fit.startRoutine(r);+ expect(fit.session!.exercises.first.sets.first.weight, 62.5);+ });++ test('no sube si se te cayeron las repes', () {+ fit.toggleProgress(bench());+ final r = routineWith([bench()]);+ fit.startRoutine(r);+ final sets = fit.session!.exercises.first.sets;+ while (sets.length > 2) {+ sets.removeLast();+ }+ fit.setSessionReps(0, 0, 5);+ fit.setSessionWeight(0, 0, 60);+ fit.toggleSet(0, 0);+ fit.setSessionReps(0, 1, 3);+ fit.setSessionWeight(0, 1, 60);+ fit.toggleSet(0, 1);+ fit.finishSession();+ fit.saveAndExit();++ fit.startRoutine(fit.routines.first);+ expect(fit.session!.exercises.first.sets.first.weight, 60);+ });++ test('sin progresión el peso se queda como estaba', () {+ logBench(5, 60, 2);+ fit.startRoutine(fit.routines.first);+ expect(fit.session!.exercises.first.sets.first.weight, 60);+ });+ });++ group('recomendación para la próxima (issue #12)', () {+ void logBenchSets(List<(int, double)> sets) {+ final r = routineWith([bench()]);+ fit.startRoutine(r);+ final live = fit.session!.exercises.first.sets;+ while (live.length > sets.length) {+ live.removeLast();+ }+ while (live.length < sets.length) {+ fit.addSet(0);+ }+ for (var i = 0; i < sets.length; i++) {+ fit.setSessionReps(0, i, sets[i].$1);+ fit.setSessionWeight(0, i, sets[i].$2);+ fit.toggleSet(0, i);+ }+ fit.finishSession();+ fit.saveAndExit();+ }++ test('sin historial no propone nada', () {+ expect(fit.nextTarget(bench()), isNull);+ expect(fit.nextTargetLabel(bench()), isNull);+ });++ test('si cumpliste todas las repes propone subir', () {+ logBenchSets([(10, 60), (10, 60), (10, 60)]);+ final next = fit.nextTarget(bench())!;+ expect(next.up, isTrue);+ expect(next.weightKg, 62.5);+ expect(next.reps, 10);+ expect(fit.nextTargetLabel(bench()), '62.5 kg × 10');+ });++ test('si se te cayeron las repes propone repetir el peso', () {+ logBenchSets([(10, 60), (8, 60)]);+ final next = fit.nextTarget(bench())!;+ expect(next.up, isFalse);+ expect(next.weightKg, 60);+ });++ test('respeta el incremento que hayas puesto en el ejercicio', () {+ fit.toggleProgress(bench());+ fit.bumpProgressStep(bench(), 1);+ fit.bumpProgressStep(bench(), 1);+ expect(fit.progressFor(bench()), 5);+ logBenchSets([(5, 100), (5, 100)]);+ expect(fit.nextTarget(bench())!.weightKg, 105);+ });++ test('en un ejercicio sin peso propone una repe más', () {+ final pushUp = fit.matchExerciseByName('Push-Up')!.id;+ expect(fit.isRepsOnly(pushUp), isTrue);+ final r = routineWith([pushUp]);+ fit.startRoutine(r);+ final live = fit.session!.exercises.first.sets;+ while (live.length > 1) {+ live.removeLast();+ }+ fit.setSessionReps(0, 0, 12);+ fit.setSessionWeight(0, 0, 0);+ fit.toggleSet(0, 0);+ fit.finishSession();+ fit.saveAndExit();++ final next = fit.nextTarget(pushUp)!;+ expect(next.up, isTrue);+ expect(next.reps, 13);+ expect(fit.nextTargetLabel(pushUp), '13 reps');+ });+ });++ group('calentamiento pegado al ejercicio', () {+ test('la sesión abre con las series de calentamiento delante', () {+ fit.toggleAutoWarmup(bench());+ final r = routineWith([bench()]);+ fit.startRoutine(r);++ final sets = fit.session!.exercises.first.sets;+ expect(sets.first.kind, SetKind.warmup);+ expect(sets.where((s) => s.kind == SetKind.warmup).length, 3);+ expect(sets.where((s) => s.counts).length, 3);+ });+ });++ group('discos del sitio', () {+ test('la calculadora solo propone los discos que tienes', () {+ final id = fit.addPlace('Casa', equipment: {'Barbell'});+ fit.setActivePlace(id);+ fit.setPlatePairs(id, 20, 1);+ fit.setPlatePairs(id, 10, 1);++ final parts = fit.platesPerSide(100, 20);+ expect(parts.map((p) => p.weight), [20, 10]);+ expect(fit.loadableTotal(100, 20), 80);+ });++ test('sin inventario sigue proponiendo de todo', () {+ final parts = fit.platesPerSide(100, 20);+ expect(parts.first.weight, 25);+ expect(fit.loadableTotal(100, 20), 100);+ });++ test('la barra del sitio manda en el aviso del entreno', () {+ final id = fit.addPlace('Casa', equipment: {'Barbell'});+ fit.setActivePlace(id);+ fit.setPlaceBar(id, 15);+ expect(fit.defaultBar, 15);+ });+ });++ group('grupos de rutinas', () {+ test('agrupa y deja fuera las sueltas', () {+ final a = fit.createRoutine('Push');+ final b = fit.createRoutine('Pull');+ fit.createRoutine('Suelta');+ fit.setRoutineGroup(a, 'PPL');+ fit.setRoutineGroup(b, 'PPL');++ expect(fit.routineGroups, ['PPL']);+ expect(fit.routinesInGroup('PPL').length, 2);+ expect(fit.routinesInGroup('').single.name, 'Suelta');+ });++ test('el grupo aguanta un guardado y una carga', () {+ final a = fit.createRoutine('Push');+ fit.setRoutineGroup(a, 'PPL');+ final saved = fit.toJson();+ fit.resetAllData();+ fit.applyBackup(saved);+ expect(fit.routines.single.group, 'PPL');+ });+ });++ group('planes hechos', () {+ test('cada ejercicio de cada plantilla existe en el catálogo', () {+ for (final template in kProgramTemplates) {+ for (final day in template.days) {+ for (final (name, _) in day.exercises) {+ expect(fit.matchExerciseByName(name), isNotNull,+ reason: '${template.name} · $name');+ }+ }+ }+ });++ test('aplicar un plan crea sus rutinas agrupadas y con sus series', () {+ final made = fit.applyTemplate(kProgramTemplates.firstWhere((x) => x.id == 'stronglifts'));+ expect(made, 2);+ expect(fit.routineGroups, ['StrongLifts 5×5']);+ final a = fit.routinesInGroup('StrongLifts 5×5').first;+ expect(a.exerciseIds.length, 3);+ expect(fit.routineSets(a, a.exerciseIds.first), 5);+ });++ test('coloca los días solo si el plan semanal estaba vacío', () {+ fit.applyTemplate(kProgramTemplates.firstWhere((x) => x.id == 'stronglifts'));+ expect(fit.weeklyPlan.length, 2);++ final before = Map.of(fit.weeklyPlan);+ fit.applyTemplate(kProgramTemplates.firstWhere((x) => x.id == 'ppl'));+ expect(fit.weeklyPlan, before);+ });+ });++ group('copiar rutinas', () {+ test('duplicar se lleva ejercicios, series y grupo', () {+ final r = routineWith([bench()]);+ fit.bumpRoutineSets(r.id, bench(), 2);+ fit.setRoutineGroup(r.id, 'PPL');++ final copy = fit.duplicateRoutine(r.id);+ final made = fit.routines.firstWhere((x) => x.id == copy);+ expect(made.exerciseIds, r.exerciseIds);+ expect(fit.routineSets(made, bench()), 5);+ expect(made.group, 'PPL');+ expect(made.name.contains(r.name), isTrue);+ });++ test('guardar la sesión como rutina se queda con las series buenas', () {+ fit.toggleAutoWarmup(bench());+ final r = routineWith([bench()]);+ fit.bumpRoutineSets(r.id, bench(), 1);+ fit.startRoutine(r);++ final id = fit.saveSessionAsRoutine();+ final made = fit.routines.firstWhere((x) => x.id == id);+ expect(made.exerciseIds, [bench()]);+ expect(fit.routineSets(made, bench()), 4);+ });+ });++ group('hábitos (recordatorio inteligente)', () {+ void logAt(DateTime when, int minutes) {+ fit.sessions.add(LoggedSession(when, minutes * 60,+ [LoggedExercise(bench(), 'Bench', 'chest', [LoggedSet(5, 60)])]));+ }++ test('sin historial no hay hábito', () {+ expect(fit.usualWeekdays, isEmpty);+ expect(fit.usualStartMinute, isNull);+ expect(fit.hasTrainingHabit, isFalse);+ });++ test('saca los días que más entrenas y la hora de siempre', () {+ final monday = DateTime(2026, 9, 7, 20, 0);+ for (var week = 0; week < 3; week++) {+ logAt(monday.add(Duration(days: 7 * week)), 60);+ logAt(monday.add(Duration(days: 7 * week + 2)), 60);+ }+ expect(fit.usualWeekdays, [1, 3]);+ expect(fit.usualStartMinute, 19 * 60);+ expect(fit.hasTrainingHabit, isTrue);+ });++ test('el foco de hoy sigue siendo uno de los tres días', () {+ final today = DateTime.now();+ for (var week = 1; week <= 3; week++) {+ fit.sessions.add(LoggedSession(today.subtract(Duration(days: 7 * week)), 3600,+ [LoggedExercise(bench(), 'Bench', 'chest', [LoggedSet(5, 60)])]));+ }+ expect(fit.familyOnWeekday(today.weekday), 'push');+ expect(fit.suggestedFocus.muscles, contains('chest'));+ });+ });++ group('superseries', () {+ ({Routine routine, String a, String b}) chainedPair() {+ final squat = fit.matchExerciseByName('Barbell Squat')!.id;+ final r = routineWith([bench(), squat]);+ fit.bumpRoutineSets(r.id, bench(), -1);+ fit.bumpRoutineSets(r.id, squat, -1);+ fit.toggleChain(r.id, bench());+ return (routine: r, a: bench(), b: squat);+ }++ test('el encadenado se guarda y se lee', () {+ final pair = chainedPair();+ expect(fit.chainsToNext(pair.routine, pair.a), isTrue);+ expect(fit.chainsToNext(pair.routine, pair.b), isFalse);++ final saved = fit.toJson();+ fit.resetAllData();+ fit.applyBackup(saved);+ expect(fit.routines.single.chained, {pair.a});+ });++ test('marcar una serie salta al encadenado sin descanso', () {+ final pair = chainedPair();+ fit.startRoutine(pair.routine);+ expect(fit.inSuperset, isTrue);++ fit.toggleSet(0, 0);+ expect(fit.session!.currentIndex, 1);+ expect(fit.session!.restRemaining, isNull);+ });++ test('al cerrar la vuelta descansa y vuelve al primero', () {+ final pair = chainedPair();+ fit.startRoutine(pair.routine);+ fit.session!.exercises[0].sets.add(SessionSet(10, 60, false));+ fit.session!.exercises[1].sets.add(SessionSet(10, 60, false));++ fit.toggleSet(0, 0);+ fit.toggleSet(1, 0);+ expect(fit.session!.restRemaining, isNotNull);+ expect(fit.session!.currentIndex, 0);+ });++ test('sin encadenar sigue el comportamiento de siempre', () async {+ final squat = fit.matchExerciseByName('Barbell Squat')!.id;+ final r = routineWith([bench(), squat]);+ fit.bumpRoutineSets(r.id, bench(), -2);+ fit.startRoutine(r);+ expect(fit.inSuperset, isFalse);+ fit.toggleSet(0, 0);+ expect(fit.session!.restRemaining, isNotNull);+ expect(fit.session!.currentIndex, 0, reason: 'el tic se ve antes de saltar');++ await Future<void>.delayed(WorkoutState.advanceDelay + const Duration(milliseconds: 200));+ expect(fit.session!.currentIndex, 1);+ });+ });++ group('ajustes nuevos', () {+ test('el objetivo semanal es el que se enseña en el anillo', () {+ fit.updateProfile(weeklyGoalDelta: 10 - fit.profile.weeklyGoal);+ expect(fit.weeklyTarget, 10);+ expect(fit.goalPct, 0);+ });++ test('el foco de hoy se puede apagar y se guarda', () {+ expect(fit.showFocus, isTrue);+ fit.toggleFocusCard();+ final saved = fit.toJson();+ fit.resetAllData();+ fit.applyBackup(saved);+ expect(fit.showFocus, isFalse);+ });++ test('la hora del aviso se guarda y se puede quitar', () {+ fit.setTrainReminder(19 * 60 + 30);+ final saved = fit.toJson();+ fit.resetAllData();+ fit.applyBackup(saved);+ expect(fit.trainReminderMin, 19 * 60 + 30);+ fit.setTrainReminder(null);+ expect(fit.trainReminderMin, isNull);+ });+ });+}diff --git a/test/route_stack_test.dart b/test/route_stack_test.dartindex 302d32d..5a4e201 100644--- a/test/route_stack_test.dart+++ b/test/route_stack_test.dart@@ -68,4 +68,23 @@ void main() {fit.handleBack();expect(fit.route, 'exercises');});++ test('every screen you can open knows how to come back', () {+ for (final open in <(String, void Function())>[+ ('preferences', fit.goPreferences),+ ('moments', fit.goMoments),+ ('awards', fit.goAwards),+ ]) {+ fit.goSettings();+ open.$2();+ expect(fit.route, open.$1);+ expect(fit.handleBack(), isTrue, reason: 'salir de ${open.$1} no puede cerrar la app');+ expect(fit.route, 'settings');+ }+ });++ test('back from home is the only one that leaves the app', () {+ fit.goHome();+ expect(fit.handleBack(), isFalse);+ });}diff --git a/test/routine_session_edit_test.dart b/test/routine_session_edit_test.dartindex 86f799d..f3d5af4 100644--- a/test/routine_session_edit_test.dart+++ b/test/routine_session_edit_test.dart@@ -1,4 +1,5 @@import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/models/profile.dart';import 'package:gymmane/models/note.dart';import 'package:gymmane/services/local_store.dart';import 'package:gymmane/state/fit_state.dart';@@ -155,7 +156,7 @@ void main() {expect(fit.notesFor(a), isEmpty);expect(fit.favorites, isEmpty);expect(fit.session, isNull);- expect(fit.profile.name, 'InlitX');+ expect(fit.profile.name, kDefaultName);expect(fit.onboarded, false, reason: 'vuelve a estar recién instalada');expect(fit.route, 'home');});diff --git a/test/session_test.dart b/test/session_test.dartindex e071b02..ccbb50e 100644--- a/test/session_test.dart+++ b/test/session_test.dart@@ -32,6 +32,29 @@ void main() {expect(fit.session!.exercises.length, fit.sessionPicks.length);});+ test('logging a past day stamps that date and leaves the clock alone', () {+ final day = DateTime.now().subtract(const Duration(days: 3));+ final id = fit.createRoutine('Past');+ fit.toggleRoutineExercise(id, 'EIeI8Vf');+ fit.startRoutine(fit.routines.firstWhere((r) => r.id == id), on: day);++ final s = fit.session!;+ expect(s.manual, isTrue);+ expect(s.loggedAt, DateTime(day.year, day.month, day.day, 12));++ fit.toggleSet(0, 0);+ expect(s.restRemaining, isNull, reason: 'no rest timer while filling in a past day');++ fit.finishSession();+ final logged = fit.sessions.single;+ expect(logged.date, DateTime(day.year, day.month, day.day, 12));+ expect(logged.durationSec, 0, reason: 'a typed-in session has no measured duration');+ expect(fit.daySummary(day)?.sets, 1);++ fit.saveAndExit();+ fit.deleteRoutine(id);+ });+test('dropping every exercise refuses to start a session', () {fit.startWorkout();fit.toggleMuscle('chest');@@ -74,6 +97,46 @@ void main() {fit.saveAndExit();});+ test('the rest counts by the clock, so leaving the app does not stall it', () {+ fit.startWorkout();+ fit.toggleMuscle('chest');+ fit.trainContinue();+ fit.startSession();+ fit.startRest();++ final left = fit.session!.restRemaining!;+ fit.session!.restEndsAt = fit.session!.restEndsAt!.subtract(const Duration(seconds: 30));+ expect(fit.session!.restRemaining, lessThanOrEqualTo(left - 29),+ reason: 'el tiempo que pasa fuera de la app cuenta igual');++ fit.session!.restEndsAt = DateTime.now().subtract(const Duration(seconds: 1));+ expect(fit.session!.restRemaining, isNull, reason: 'un descanso vencido no se queda clavado');+ fit.syncRest();+ expect(fit.session!.restEndsAt, isNull);++ fit.saveAndExit();+ });++ test('pausing freezes the rest and resuming hands it back', () {+ fit.startWorkout();+ fit.toggleMuscle('chest');+ fit.trainContinue();+ fit.startSession();+ fit.startRest();+ final left = fit.session!.restRemaining!;++ fit.toggleSessionPause();+ expect(fit.session!.restFrozen, left);+ expect(fit.session!.restEndsAt, isNull);+ expect(fit.session!.restRemaining, left, reason: 'en pausa el descanso no corre');++ fit.toggleSessionPause();+ expect(fit.session!.restFrozen, isNull);+ expect(fit.session!.restRemaining, left, reason: 'al reanudar sigue donde estaba');++ fit.saveAndExit();+ });+test('back walks up the routes instead of leaving the app', () {fit.goProgress();expect(fit.handleBack(), true);diff --git a/test/shell_repaint_test.dart b/test/shell_repaint_test.dartindex d9cac2c..d1741f1 100644--- a/test/shell_repaint_test.dart+++ b/test/shell_repaint_test.dart@@ -1,4 +1,5 @@import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/widgets/ui_kit.dart';import 'package:gymmane/app/gymmane_app.dart';import 'package:gymmane/l10n/l10n.dart';import 'package:gymmane/services/local_store.dart';@@ -34,13 +35,13 @@ void main() {testWidgets('the timeline repaints when its own buttons change the state', (tester) async {await open(tester, 'timeline');- await tester.tap(find.text(t.timelineBody));+ await tester.tap(find.text(titleCase(t.timelineBody)));await tester.pumpAndSettle();- expect(find.text(t.addTodayPhotos), findsNothing, reason: 'la pantalla no se repintó');+ expect(find.text(titleCase(t.addTodayPhotos)), findsNothing, reason: 'la pantalla no se repintó');- await tester.tap(find.text(t.timelinePhotos));+ await tester.tap(find.text(titleCase(t.timelinePhotos)));await tester.pumpAndSettle();- expect(find.text(t.addTodayPhotos), findsOneWidget);+ expect(find.text(titleCase(t.addTodayPhotos)), findsOneWidget);await tester.tap(find.text('60'));await tester.pumpAndSettle();diff --git a/test/shell_transition_test.dart b/test/shell_transition_test.dartnew file mode 100644index 0000000..d481632--- /dev/null+++ b/test/shell_transition_test.dart@@ -0,0 +1,100 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/app/gymmane_app.dart';+import 'package:gymmane/l10n/l10n.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/screens/home_screen.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/services/progress_reminder.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:gymmane/widgets/award_celebration.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ ProgressReminder.instance.enabled = false;+ setAppLanguage('es');+ fit.onboarded = true;+ fit.session = null;+ fit.sessions.clear();+ fit.awards.clear();+ fit.awardsSeen.clear();+ fit.pendingAwards.clear();+ fit.resetRoute('home');+ });++ double homeOpacity(WidgetTester tester) {+ final fade = tester.widget<FadeTransition>(+ find+ .ancestor(of: find.byType(HomeScreen), matching: find.byType(FadeTransition))+ .first,+ );+ return fade.opacity.value;+ }++ testWidgets('the screen being left is gone before the new one shows up', (tester) async {+ await tester.pumpWidget(const GymManeApp());+ await tester.pump();++ fit.goProgress();+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 120));++ expect(find.byType(HomeScreen), findsOneWidget);+ expect(homeOpacity(tester), 0, reason: 'la pantalla anterior se quedaba de fondo');++ await tester.pump(const Duration(milliseconds: 400));+ expect(find.byType(HomeScreen), findsNothing);+ });++ testWidgets('a medal waits before taking over the screen', (tester) async {+ await tester.pumpWidget(const GymManeApp());+ await tester.pump();++ fit.refreshAwards();+ await tester.pump();+ expect(find.byType(AwardCelebration), findsNothing);++ await tester.pump(const Duration(seconds: 1));+ expect(find.byType(AwardCelebration), findsNothing,+ reason: 'no da tiempo a ver la app antes de la medalla');++ await tester.pump(const Duration(seconds: 2));+ expect(find.byType(AwardCelebration), findsOneWidget);++ await tester.pump(const Duration(seconds: 2));+ fit.persistNow();+ });++ testWidgets('medals queue up one after another with a pause in between', (tester) async {+ await tester.pumpWidget(const GymManeApp());+ await tester.pump();++ fit.sessions.add(LoggedSession(DateTime.now(), 1200, [+ LoggedExercise('EIeI8Vf', 'Barbell Bench Press', 'chest', [LoggedSet(10, 60)]),+ ]));+ fit.refreshAwards();+ expect(fit.pendingAwards.length, greaterThan(1));++ await tester.pump(const Duration(seconds: 3));+ expect(find.byType(AwardCelebration), findsOneWidget);++ await tester.tap(find.text(t.awardNice));+ await tester.pump();+ expect(find.byType(AwardCelebration), findsNothing);++ await tester.pump(const Duration(seconds: 2));+ expect(find.byType(AwardCelebration), findsNothing,+ reason: 'la segunda medalla salía pegada a la primera');++ await tester.pump(const Duration(seconds: 2));+ expect(find.byType(AwardCelebration), findsOneWidget);++ await tester.pump(const Duration(seconds: 2));+ fit.persistNow();+ });+}diff --git a/test/smoke_test.dart b/test/smoke_test.dartindex c6ec187..4859671 100644--- a/test/smoke_test.dart+++ b/test/smoke_test.dart@@ -36,6 +36,7 @@ void main() {'progress','exercises','settings',+ 'preferences','routines','tools','train',diff --git a/test/timeline_body_test.dart b/test/timeline_body_test.dartindex 46e3ed9..e11cc24 100644--- a/test/timeline_body_test.dart+++ b/test/timeline_body_test.dart@@ -1,5 +1,6 @@import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/widgets/ui_kit.dart';import 'package:gymmane/l10n/l10n.dart';import 'package:gymmane/models/workout.dart';import 'package:gymmane/screens/timeline_screen.dart';@@ -99,13 +100,13 @@ void main() {await tester.pumpWidget(_host(TimelineScreen.new));await tester.pumpAndSettle();- expect(find.text(t.addTodayPhotos), findsOneWidget);+ expect(find.text(titleCase(t.addTodayPhotos)), findsOneWidget);- await tester.tap(find.text(t.timelineBody));+ await tester.tap(find.text(titleCase(t.timelineBody)));await tester.pumpAndSettle();expect(fit.bodyTimeline, true);- expect(find.text(t.addTodayPhotos), findsNothing);+ expect(find.text(titleCase(t.addTodayPhotos)), findsNothing);expect(find.text(t.timelineBodyHint), findsOneWidget);fit.persistNow();});diff --git a/test/timeline_test.dart b/test/timeline_test.dartindex 0670f99..fb715cf 100644--- a/test/timeline_test.dart+++ b/test/timeline_test.dart@@ -96,9 +96,13 @@ void main() {expect(fit.daysUntilPhoto, isNull);});- test('a rubbish interval falls back to the default', () {+ test('a hand-typed interval sticks and anything out of range is clamped', () {fit.setPhotoInterval(7);- expect(fit.photoIntervalDays, 30);+ expect(fit.photoIntervalDays, 7);+ fit.setPhotoInterval(900);+ expect(fit.photoIntervalDays, 365);+ fit.setPhotoInterval(-3);+ expect(fit.photoIntervalDays, 0);});test('comparing defaults to the first and the last, and only offers shared poses', () async {