Offline gym log for Android. No account, no ads, no internet.
Dart androidbodybuildingdartexercisesf-droidfitnessfluttergymgym-apphealthprivacyself-hostedworkoutworkout-appworkout-tracker
Group tests by topic
InlitX39131ba3a642
diff --git a/test/activity_map_test.dart b/test/activity_map_test.dartnew file mode 100644index 0000000..1a7329a--- /dev/null+++ b/test/activity_map_test.dart@@ -0,0 +1,160 @@+import 'dart:convert';+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();++ group('tonos del mapa', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ LoggedSession at(int daysAgo, List<LoggedSet> sets) => LoggedSession(+ shiftDays(DateTime.now(), -daysAgo).add(const Duration(hours: 18)),+ 600,+ [LoggedExercise('push', 'push', 'chest', sets)],+ );++ test('#187 el mapa reparte los tonos por volumen y el día sin peso queda abajo', () {+ fit.sessions+ ..add(at(4, [LoggedSet(10, 0), LoggedSet(10, 0)]))+ ..add(at(3, [LoggedSet(10, 30)]))+ ..add(at(2, [for (var i = 0; i < 6; i++) LoggedSet(10, 60)]))+ ..add(at(1, [for (var i = 0; i < 12; i++) LoggedSet(8, 100)]));+ final l = fit.heatmapLevels;+ final n = l.length;+ expect(l[n - 5], 1);+ expect(l[n - 4], 1);+ expect(l[n - 3], greaterThan(1));+ expect(l[n - 2], heatLevels);+ expect(l[n - 3], lessThan(l[n - 2]));+ expect(l.last, 0);+ });+ });++ group('#220 calendario de 12 meses', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ test('por defecto son 12 semanas y se guarda el cambio', () {+ expect(fit.heatmapYear, isFalse);+ expect(fit.heatmapShown.length, 12 * 7);+ fit.setHeatmapRange('year');+ expect(fit.heatmapShown.length, 53 * 7);+ final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;+ fit.resetAllData();+ expect(fit.heatmapYear, isFalse);+ fit.applyBackup(data);+ expect(fit.heatmapYear, isTrue);+ });++ test('con historia de más de un año llega hasta el primer entreno', () {+ fit.setHeatmapRange('year');+ final old = DateTime.now().subtract(const Duration(days: 500));+ fit.sessions.add(LoggedSession(old, 1800, [+ LoggedExercise('x', 'X', 'chest', [LoggedSet(8, 50)]),+ ]));+ final weeks = fit.heatmapShownWeeks;+ expect(weeks, greaterThan(53));+ final first = fit.heatmapShownDate(0);+ expect(first.isAfter(DateTime(old.year, old.month, old.day)), isFalse);+ final i = DateTime(old.year, old.month, old.day).difference(first).inDays;+ expect(fit.heatmapShown[i], greaterThan(0));+ });++ test('tocar un día abre la fecha correcta en los dos modos', () {+ final today = DateTime.now();+ final key = DateTime(today.year, today.month, today.day);+ for (final range in ['weeks', 'year']) {+ fit.setHeatmapRange(range);+ final levels = fit.heatmapShown;+ final i = levels.lastIndexWhere((l) => l >= 0);+ expect(fit.heatmapShownDate(i), key, reason: range);+ }+ });++ test('un valor raro no cambia el ajuste', () {+ fit.setHeatmapRange('decade');+ expect(fit.heatmapRange, 'weeks');+ });+ });++ group('#83 mapa de actividad', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ LoggedSession logged(DateTime at, List<LoggedSet> sets, {String id = 'push', String primary = 'chest'}) =>+ LoggedSession(at, 600, [LoggedExercise(id, id, primary, sets)]);++ test('un día de peso corporal se pinta', () {+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(15, 0), LoggedSet(12, 0)]));+ expect(fit.heatmapLevels.last, greaterThan(0));+ });++ test('un día marcado a mano también cuenta', () {+ fit.toggleCheckin(fit.todayIndex);+ expect(fit.heatmapLevels.last, greaterThan(0));+ });+ });++ group('#138 una semana por columna', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ const bench = 'EIeI8Vf';++ LoggedSession logged(DateTime at, List<LoggedSet> sets, {String id = bench}) =>+ LoggedSession(at, 1800, [LoggedExercise(id, 'Barbell Bench Press', 'chest', sets)]);++ test('cada columna empieza el primer día de la semana y hoy cae en su fila', () {+ for (final start in [DateTime.monday, DateTime.sunday]) {+ fit.setWeekStart(start);+ final cells = fit.heatmapWeeks;+ expect(cells.length % 7, 0);+ expect(fit.heatmapWeekDate(0).weekday, start);+ final today = DateTime.now();+ final i = cells.length - 7 + fit.todayIndex;+ final d = fit.heatmapWeekDate(i);+ expect((d.year, d.month, d.day), (today.year, today.month, today.day));+ expect(cells.skip(i + 1).every((l) => l == -1), isTrue);+ }+ });++ test('un entreno de hoy se pinta en la casilla de hoy', () {+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(8, 60)]));+ final cells = fit.heatmapWeeks;+ expect(cells[cells.length - 7 + fit.todayIndex], greaterThan(0));+ });++ test('los días y meses vienen encendidos y apagarlos se guarda', () {+ expect(fit.heatmapLabels, isTrue);+ fit.toggleHeatmapLabels();+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.heatmapLabels, isFalse);+ });+ });+}diff --git a/test/custom_exercises_test.dart b/test/custom_exercises_test.dartnew file mode 100644index 0000000..e685bf5--- /dev/null+++ b/test/custom_exercises_test.dart@@ -0,0 +1,156 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/models/exercise.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();++ group('fusionar ejercicios', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ LoggedSession day(int ago, List<LoggedExercise> exs) =>+ LoggedSession(DateTime.now().subtract(Duration(days: ago)), 1800, exs);++ test('el historial pasa al otro y el propio se queda en la biblioteca', () {+ final mine = fit.addCustomExercise(name: 'Mi press', primary: 'chest', equipment: 'Barbell');+ final bench = idOf('Barbell Bench Press');+ fit.sessions.addAll([+ day(2, [LoggedExercise(mine, 'Mi press', 'chest', [LoggedSet(10, 50)])]),+ day(1, [+ LoggedExercise(bench, 'Bench', 'chest', [LoggedSet(8, 60)]),+ LoggedExercise(mine, 'Mi press', 'chest', [LoggedSet(6, 70)]),+ ]),+ ]);++ fit.mergeExerciseInto(mine, bench);++ expect(fit.exerciseHistory(mine), isEmpty);+ expect(fit.exerciseHistory(bench), hasLength(2));+ expect(fit.sessions[1].exercises, hasLength(1), reason: 'el mismo día se juntan las series');+ expect(fit.sessions[1].exercises.single.sets.map((s) => s.reps), [8, 6]);+ expect(fit.exerciseById(mine), isNotNull);+ });++ test('solo se fusiona un ejercicio propio con otro del mismo tipo', () {+ final bench = idOf('Barbell Bench Press');+ final squat = idOf('Barbell Squat');+ fit.sessions.add(day(1, [LoggedExercise(bench, 'Bench', 'chest', [LoggedSet(8, 60)])]));+ fit.mergeExerciseInto(bench, squat);+ expect(fit.exerciseHistory(bench), hasLength(1));++ final run = fit.addCustomExercise(name: 'Mi carrera', primary: 'quads', equipment: 'Bodyweight', mode: 'cardio');+ expect(fit.mergeTargets(run).every((e) => fit.modeOf(e.id) == 'cardio'), isTrue);+ fit.sessions.add(day(2, [LoggedExercise(run, 'Run', 'quads', [LoggedSet(0, 0, sec: 600)])]));+ fit.mergeExerciseInto(run, bench);+ expect(fit.exerciseHistory(run), hasLength(1));+ });+ });++ group('your own exercises', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ test('a catalogue id starting with c is not taken for yours', () {+ expect(fit.isCustom('cycling'), isFalse);+ final mine = fit.addCustomExercise(name: 'Cable thing', primary: 'chest', equipment: 'Barbell');+ expect(fit.isCustom(mine), isTrue);+ });++ test('yours always show up, whatever place is active', () {+ final mine = fit.addCustomExercise(name: 'Mi press raro', primary: 'chest', equipment: 'Barbell');+ final home = fit.addPresetPlace('home');+ fit.setActivePlace(home);+ expect(fit.exercisesMatching('raro').map((e) => e.id), contains(mine));+ });++ test('steps and type travel through a save and back', () {+ final mine = fit.addCustomExercise(+ name: 'Row a la valla',+ primary: 'back',+ equipment: 'Other',+ steps: ['1. Grab the rail', '- Pull', '', 'Lower slowly'],+ mode: 'time',+ );+ final ex = fit.exerciseById(mine)!;+ expect(ex.steps, ['Grab the rail', 'Pull', 'Lower slowly']);+ expect(ex.mode, 'time');+ final back = Exercise.fromJson(ex.toJson());+ expect(back.steps, ex.steps);+ expect(back.mode, 'time');+ fit.updateCustomExercise(mine,+ name: 'Row', primary: 'back', equipment: 'Other', difficulty: 'Beginner', steps: ['Only'], mode: '');+ expect(fit.exerciseById(mine)!.steps, ['Only']);+ expect(fit.modeOf(mine), '');+ });+ });++ group('#99 músculos secundarios propios', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ LoggedSession logged(DateTime at, List<LoggedSet> sets, {String id = 'push', String primary = 'chest'}) =>+ LoggedSession(at, 600, [LoggedExercise(id, id, primary, sets)]);++ test('se guardan, viajan en la copia y cuentan en las series', () {+ final id = fit.addCustomExercise(+ name: 'Thruster', primary: 'quads', equipment: 'Dumbbell', secondary: ['shoulders', 'quads', 'triceps']);+ final ex = fit.exerciseById(id)!;+ expect(ex.secondary, ['shoulders', 'triceps'], reason: 'sin repetir el principal');+ final json = ex.toJson();+ expect(json['s'], ['shoulders', 'triceps']);+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(8, 20), LoggedSet(8, 20)], id: id, primary: 'quads'));+ expect(fit.muscleSetsOver(7)['shoulders'], 1);+ });+ });++ group('ejercicios propios en la rutina', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ 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();+ });+ });+}diff --git a/test/editing_test.dart b/test/delete_entries_test.dartsimilarity index 100%rename from test/editing_test.dartrename to test/delete_entries_test.dartdiff --git a/test/exercise_library_test.dart b/test/exercise_library_test.dartnew file mode 100644index 0000000..f8b9ad4--- /dev/null+++ b/test/exercise_library_test.dart@@ -0,0 +1,341 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/catalog/exercise_catalog.dart';+import 'package:gymmane/l10n/l10n.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/services/exercise_match.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();++ group('#179 filtro de trapecio', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ test('trapecio, antebrazo y oblicuos salen en el filtro y encuentran ejercicios', () {+ for (final m in ['trapezius', 'forearm', 'obliques']) {+ expect(kFilterMuscles, contains(m));+ fit.setMuscleFilter(m);+ expect(fit.exercisesFiltered, isNotEmpty, reason: m);+ expect(+ fit.exercisesFiltered.every((e) => e.primary == m || e.secondary.contains(m)), isTrue);+ fit.setMuscleFilter(m);+ }+ });+ });++ group('suggestions', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ test('an exercise switched off never lands in the picks but stays searchable', () {+ fit.selectedMuscles+ ..clear()+ ..add('chest');+ fit.trainContinue();+ final first = fit.sessionPicks.first;+ fit.toggleSuggest(first);+ fit.trainContinue();+ expect(fit.sessionPicks.contains(first), isFalse);+ expect(fit.trainSearchResults(fit.exerciseById(first)!.name).map((e) => e.id), contains(first));+ expect(fit.recommendedExercises(20).map((e) => e.id), isNot(contains(first)));+ });++ test('the suggested picks come first in the review list', () {+ fit.selectedMuscles+ ..clear()+ ..addAll(['chest', 'triceps']);+ fit.trainContinue();+ final list = fit.reviewExercises();+ final seeded = list.take(fit.pickSeed.length).map((e) => e.id).toSet();+ expect(seeded, fit.pickSeed);+ });++ test('hidden exercises survive a restart', () {+ fit.toggleSuggest(idOf('Barbell Bench Press'));+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.suggests(idOf('Barbell Bench Press')), isFalse);+ });+ });++ group('#237 buscador', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ List<String> search(String q) => kExercises.where(exerciseSearch(q)).map((e) => e.name).toList();++ test('gemelos en plural, por músculo y con palabras desordenadas', () {+ expect(search('Calf raises'), contains('Bodyweight Standing Calf Raise'));+ expect(search('calves'), contains('Donkey Calf Raise'));+ expect(search('machine calf raise'), contains('Lever Standing Calf Raise'));+ expect(search('seated calf raises'), contains('Dumbbell Seated One Leg Calf Raise'));+ expect(search('calf ra'), contains('Smith Calf Raise'));+ });++ test('el nombre del músculo en castellano también busca', () {+ setAppLanguage('es');+ expect(search('gemelos'), contains('Donkey Calf Raise'));+ setAppLanguage('en');+ });++ test('no se cuelan resultados de más', () {+ expect(search('calf raise').every((n) => n.toLowerCase().contains('calf')), isTrue);+ expect(search('bench press'), isNot(contains('Donkey Calf Raise')));+ expect(search('ch'), isNot(contains('Donkey Calf Raise')));+ });+ });++ group('ejercicios por zona', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ setAppLanguage('en');+ });++ group('ejercicios por zona', () {+ test('piernas trae los de pierna primero y se limpia con el resto', () {+ fit.setZoneFilter('Legs');+ final list = fit.exercisesFiltered;+ final legs = kBodyZones['Legs']!;+ expect(list, isNotEmpty);+ expect(legs.contains(list.first.primary), isTrue);+ expect(list.every((e) => legs.contains(e.primary) || e.secondary.any(legs.contains)), isTrue);+ expect(fit.zoneCount('Legs'), list.where((e) => legs.contains(e.primary)).length);+ fit.setMuscleFilter('chest');+ expect(fit.exZoneFilter, isNull);+ fit.setZoneFilter('Arms');+ expect(fit.exMuscleFilter, isNull);+ fit.clearExFilters();+ expect(fit.exZoneFilter, isNull);+ });++ test('cada músculo del filtro cae en una zona', () {+ final all = kBodyZones.values.expand((m) => m).toSet();+ expect(all, containsAll(kFilterMuscles));+ });+ });++ test('#238 side bend: oblicuos primero', () {+ for (final name in ['Dumbbell Side Bend', 'Weighted Side Bend (On Stability Ball)']) {+ final ex = kExercises.firstWhere((e) => e.name == name);+ expect(ex.primary, 'obliques');+ expect(ex.secondary, ['abdomen']);+ }+ });+ });++ group('biblioteca de ejercicios', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineOf(List<String> names) {+ final id = fit.createRoutine('Push');+ for (final name in names) {+ fit.toggleRoutineExercise(id, idOf(name));+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ group('#115 sin material', () {+ tearDown(fit.clearExFilters);++ test('no enseña lo que necesita barra', () {+ fit.toggleNoGearFilter();+ final ids = fit.exercisesMatching('').map((e) => e.id).toSet();+ expect(ids, isNot(contains(idOf('Pull-up'))));+ expect(ids, isNot(contains('seal-jack')), reason: 'su dibujo es una estación de fondos');+ expect(ids, isNot(contains('outdoor-run')), reason: 'el dibujo es una cinta');+ expect(ids, contains(idOf('Push-up')));+ });++ test('elegir material lo apaga y al revés', () {+ fit.toggleNoGearFilter();+ fit.setEquipmentFilter('Barbell');+ expect(fit.exNoGearOnly, isFalse);+ fit.toggleNoGearFilter();+ expect(fit.exEquipmentFilter, isNull);+ });+ });++ test('#89 solo los creados por ti', () {+ final id = fit.addCustomExercise(name: 'Mi press', primary: 'chest', equipment: 'Dumbbell');+ fit.toggleMineFilter();+ expect(fit.exercisesMatching('').map((e) => e.id), [id]);+ fit.clearExFilters();+ });++ group('#120 calentamiento y #106 cardio', () {+ test('los ejercicios sin peso también calientan', () {+ fit.startRoutine(routineOf(['Push-up']));+ fit.addWarmupSets(0);+ expect(fit.hasWarmup(0), isTrue);+ });++ test('el calentamiento propone movilidad y el cardio solo cardio', () {+ fit.startWorkout();+ fit.startKindWorkout('warmup');+ expect(fit.sessionPicks, isNotEmpty);+ expect(fit.reviewExercises().where((e) => const ['Machine', 'Cable'].contains(e.equipment)), isEmpty);+ fit.startKindWorkout('cardio');+ final cardio = fit.reviewExercises().map((e) => e.id).toSet();+ expect(cardio, containsAll(['skierg', 'battle-ropes', 'running']));+ expect(cardio.every((id) => fit.isCardio(id) || kCardioExtras.contains(id)), isTrue);+ fit.closeTrain();+ });+ });++ group('#119 archivar', () {+ test('un archivado desaparece de todo y vuelve al restaurarlo', () {+ final id = idOf('Pull-up');+ fit.toggleArchived(id);+ expect(fit.exercisesMatching('').map((e) => e.id), isNot(contains(id)));+ expect(fit.trainSearchResults('pull').map((e) => e.id), isNot(contains(id)));+ expect(fit.getFilteredExercises(['back']).map((e) => e.id), isNot(contains(id)));+ expect(fit.recommendedExercises(40).map((e) => e.id), isNot(contains(id)));++ fit.toggleArchivedFilter();+ expect(fit.exercisesMatching('').map((e) => e.id), [id]);++ fit.toggleArchived(id);+ expect(fit.exArchivedOnly, isFalse, reason: 'sin archivados el filtro se apaga');+ expect(fit.exercisesMatching('').map((e) => e.id), contains(id));+ });++ test('se guarda en la copia', () {+ fit.toggleArchived(idOf('Pull-up'));+ expect(fit.toJson()['archived'], [idOf('Pull-up')]);+ });+ });++ test('#95 los recomendados se pueden quitar y se guarda', () {+ expect(fit.showRecommended, isTrue);+ fit.toggleRecommended();+ expect(fit.toJson()['showRecs'], isFalse);+ });++ test('#111 las marcas del vídeo se guardan y se van con el vídeo', () {+ final id = idOf('Barbell Bench Press');+ fit.setVideoMark(id, 1, 40000);+ expect(fit.videoMark(id, 1), 40000);+ expect(fit.toJson()['marks'], {id: {'1': 40000}});+ fit.setVideoMark(id, 1, null);+ expect(fit.videoMarks, isEmpty);+ fit.setVideoMark(id, 0, 1000);+ fit.clearExerciseMedia(id);+ expect(fit.videoMark(id, 0), isNull);+ });++ test('#105 las notas de un ejercicio se abren en lista y atrás vuelve', () {+ fit.openExercise(idOf('Plank'));+ fit.goNotes(exerciseId: idOf('Plank'), all: true);+ expect(fit.notesAllView, isTrue);+ fit.backFromNotes();+ expect(fit.route, 'exercise-detail');+ });+ });++ group('favourites filter', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ test('marking a star and filtering leaves only that exercise', () {+ final a = kExercises[0], b = kExercises[1];+ fit.toggleFavorite(a.id);+ expect(fit.favouriteCount, 1);++ fit.toggleFavouritesFilter();+ final list = fit.exercisesFiltered;+ expect(list.map((e) => e.id), [a.id]);+ expect(list.contains(b), false);+ });++ test('the filter stacks with the muscle one instead of replacing it', () {+ final chest = kExercises.firstWhere((e) => e.primary == 'chest');+ final back = kExercises.firstWhere((e) => e.primary == 'back');+ fit.toggleFavorite(chest.id);+ fit.toggleFavorite(back.id);++ fit.toggleFavouritesFilter();+ fit.setMuscleFilter('chest');+ expect(fit.exercisesFiltered.map((e) => e.id), contains(chest.id));+ expect(fit.exercisesFiltered.map((e) => e.id), isNot(contains(back.id)));+ });++ test('un-starring drops it out of the filtered list', () {+ final a = kExercises[0];+ fit.toggleFavorite(a.id);+ fit.toggleFavouritesFilter();+ expect(fit.exercisesFiltered, isNotEmpty);++ fit.toggleFavorite(a.id);+ expect(fit.favouriteCount, 0);+ expect(fit.exercisesFiltered, isEmpty);+ });++ test('clearing filters brings the whole library back', () {+ fit.toggleFavouritesFilter();+ fit.setMuscleFilter('chest');+ fit.setExSearch('press');+ fit.clearExFilters();+ 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');+ expect(fit.exercisesFiltered, isNotEmpty);+ fit.clearExFilters();+ });+ });+}diff --git a/test/gestures_test.dart b/test/gestures_test.dartnew file mode 100644index 0000000..2c0151f--- /dev/null+++ b/test/gestures_test.dart@@ -0,0 +1,87 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.dart';+import 'package:gymmane/screens/routine_edit_screen.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:gymmane/theme/app_theme.dart';+import 'package:gymmane/widgets/glass.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ group('cerrar hojas', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ testWidgets('#227 una hoja larga se cierra tirando hacia abajo', (tester) async {+ late BuildContext ctx;+ await tester.pumpWidget(MaterialApp(home: Builder(builder: (c) {+ ctx = c;+ return const SizedBox();+ })));+ showAppSheet<void>(+ context: ctx,+ builder: (_) => SingleChildScrollView(+ child: Column(children: [for (var i = 0; i < 60; i++) SizedBox(height: 40, child: Text('fila $i'))]),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('fila 0'), findsOneWidget);+ await tester.drag(find.text('fila 2'), const Offset(0, 300));+ await tester.pumpAndSettle();+ expect(find.text('fila 0'), findsNothing);+ });+ });++ group('arrastrar en la rutina', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ setAppLanguage('en');+ });++ testWidgets('#251 arrastrar al borde de abajo desplaza la lista de la rutina', (tester) async {+ await tester.binding.setSurfaceSize(const Size(400, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final id = fit.createRoutine('Larga');+ for (final ex in fit.allExercises.take(15)) {+ fit.toggleRoutineExercise(id, ex.id);+ }+ fit.openRoutine(id);+ await tester.pumpWidget(MaterialApp(+ theme: AppTheme.dark,+ home: AnimatedBuilder(+ animation: fit,+ builder: (_, _) => const Scaffold(body: RoutineEditScreen()),+ ),+ ));+ await tester.pump(const Duration(seconds: 1));++ final handle = find.byType(ReorderableDragStartListener).first;+ await tester.ensureVisible(handle);+ await tester.pump(const Duration(milliseconds: 300));+ final scroll = tester.state<ScrollableState>(find.byType(Scrollable).first).position;+ final start = scroll.pixels;++ final drag = await tester.startGesture(tester.getCenter(handle));+ await drag.moveBy(const Offset(0, 20));+ await tester.pump(const Duration(milliseconds: 100));+ await drag.moveTo(const Offset(200, 790));+ for (var i = 0; i < 30; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ expect(scroll.pixels, greaterThan(start + 100));+ await drag.up();+ await tester.pump(const Duration(seconds: 1));+ });+ });+}diff --git a/test/history_test.dart b/test/history_test.dartnew file mode 100644index 0000000..d716ea2--- /dev/null+++ b/test/history_test.dart@@ -0,0 +1,315 @@+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/services/local_store.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ group('#180 duración de la sesión', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ test('se corrige y se guarda', () {+ final s = LoggedSession(DateTime.now(), 108 * 60, [+ LoggedExercise('x', 'x', 'chest', [LoggedSet(8, 60)]),+ ]);+ fit.sessions.add(s);+ fit.setSessionDuration(s, 45 * 60);+ expect(fit.daySummary(DateTime.now())!.durationSec, 45 * 60);+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.sessions.single.durationSec, 45 * 60);+ });+ });++ group('#81 entreno que pasa de medianoche', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ DateTime day(int offset, [int hour = 10]) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day + offset, hour);+ }++ test('cuenta en el día en que empezó', () {+ final end = day(0, 1);+ fit.sessions.add(LoggedSession(end, 2 * 3600, [+ LoggedExercise(bench(), 'Bench Press', 'chest', [LoggedSet(8, 60)]),+ ]));+ expect(fit.trainedToday, isFalse);+ expect(fit.sessionsOn(day(-1)).length, 1);+ expect(fit.sessionsOn(DateTime.now()), isEmpty);+ });+ });++ group('historial y series registradas', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ DateTime ago(int days, [int hour = 18]) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day - days, hour);+ }++ void logged(String id, int days, List<LoggedSet> sets) =>+ fit.sessions.add(LoggedSession(ago(days), 1200, [LoggedExercise(id, id, 'back', sets)]));++ group('#228 editar series registradas', () {+ test('cambiar el peso no borra el tiempo, el tipo ni el RPE', () {+ final e = LoggedExercise('plank', 'Plank', 'abdomen', [LoggedSet(0, 10, sec: 45, rpe: 8, kind: SetKind.drop)]);+ fit.sessions.add(LoggedSession(ago(1), 600, [e]));+ fit.bumpLoggedWeight(e, 0, 1);+ expect(e.sets.single.sec, 45);+ expect(e.sets.single.rpe, 8);+ expect(e.sets.single.kind, SetKind.drop);+ fit.bumpLoggedSec(e, 0, 1);+ expect(e.sets.single.sec, 50);+ fit.bumpLoggedSec(e, 0, -20);+ expect(e.sets.single.sec, 0);+ });++ test('añadir serie copia el tiempo y la distancia', () {+ final e = LoggedExercise('run', 'Run', 'quads', [LoggedSet(0, 0, sec: 1800, km: 5)]);+ fit.sessions.add(LoggedSession(ago(1), 600, [e]));+ fit.addLoggedSet(e);+ expect(e.sets.last.sec, 1800);+ expect(e.sets.last.km, 5);+ fit.bumpLoggedKm(e, 1, 1);+ expect(e.sets.last.km, closeTo(5.1, 0.001));+ expect(fit.loggedDistance(e), isTrue);+ });++ test('un ejercicio con tiempo se reconoce aunque sea propio', () {+ final e = LoggedExercise('mio', 'Mío', 'abdomen', [LoggedSet(0, 0, sec: 30)]);+ expect(fit.loggedTimed(e), isTrue);+ expect(fit.loggedTimed(LoggedExercise('b', 'B', 'chest', [LoggedSet(8, 60)])), isFalse);+ });+ });++ group('#214 #196 historial', () {+ test('el mes lista sus entrenos, del más nuevo al más viejo', () {+ final n = DateTime.now();+ final month = DateTime(n.year, n.month);+ fit.sessions.add(LoggedSession(DateTime(n.year, n.month, 1, 18), 1800, [LoggedExercise('a', 'A', 'chest', [LoggedSet(8, 60)])]));+ fit.sessions.add(LoggedSession(DateTime(n.year, n.month, 2, 18), 2400, [LoggedExercise('a', 'A', 'chest', [LoggedSet(8, 62.5), LoggedSet(8, 62.5)])]));+ fit.sessions.add(LoggedSession(DateTime(n.year, n.month - 1, 20, 18), 600, [LoggedExercise('a', 'A', 'chest', [LoggedSet(8, 50)])]));+ final list = fit.sessionsInMonth(month);+ expect(list.length, 2);+ expect(list.first.day.day, 2);+ final sum = fit.monthSummary(month);+ expect(sum.workouts, 2);+ expect(sum.sets, 3);+ expect(sum.seconds, 4200);+ expect(fit.monthSummary(DateTime(n.year, n.month - 1)).workouts, 1);+ });++ test('no se puede ir más allá del mes actual', () {+ fit.goHistory();+ expect(fit.historyAtLatest, isTrue);+ final before = fit.historyMonth;+ fit.shiftHistoryMonth(1);+ expect(fit.historyMonth, before);+ fit.shiftHistoryMonth(-1);+ expect(fit.historyAtLatest, isFalse);+ fit.popRoute();+ });++ test('cuenta los récords de cada entreno, no el primero', () {+ logged('a', 9, [LoggedSet(8, 60)]);+ logged('a', 6, [LoggedSet(8, 65)]);+ logged('a', 3, [LoggedSet(8, 62.5)]);+ final byDay = {for (final e in fit.recordsBySession().entries) e.key.day.day: e.value};+ expect(byDay.length, 1);+ expect(byDay[ago(6).day], 1);+ });++ test('sin nombre ni rutina, el título son los grupos musculares', () {+ final s = LoggedSession(ago(1), 600, [+ LoggedExercise('a', 'A', 'chest', [LoggedSet(8, 60), LoggedSet(8, 60)]),+ LoggedExercise('b', 'B', 'quads', [LoggedSet(5, 100)]),+ ]);+ fit.sessions.add(s);+ expect(fit.sessionHeading(s), contains(' · '));+ fit.renameSession(s, 'Pecho pesado');+ expect(fit.sessionHeading(s), 'Pecho pesado');+ });++ test('la mejor serie de una plancha es la más larga', () {+ final e = LoggedExercise('plank', 'Plank', 'abdomen', [LoggedSet(0, 0, sec: 45), LoggedSet(0, 0, sec: 60)]);+ expect(fit.topSetOf(e)!.sec, 60);+ });+ });++ testWidgets('el historial cambia de mes en la app de verdad', (tester) async {+ setAppLanguage('es');+ fit.refreshAwards(silent: true);+ fit.pendingAwards.clear();+ fit.resetRoute('settings');+ fit.goHistory();+ await tester.pumpWidget(const GymManeApp());+ for (var i = 0; i < 20; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ final now = DateTime.now();+ expect(find.text(t.monthYear(DateTime(now.year, now.month))), findsOneWidget);+ await tester.tap(find.bySemanticsLabel(t.notePrevMonth));+ for (var i = 0; i < 10; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+ expect(find.text(t.monthYear(DateTime(now.year, now.month - 1))), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 1));+ });+ });++ group('#252 vs la última vez', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ setAppLanguage('en');+ });++ String startOne() {+ fit.startWorkout();+ fit.toggleMuscle('chest');+ fit.trainContinue();+ for (final id in fit.sessionPicks.toList().skip(1)) {+ fit.togglePick(id);+ }+ fit.startSession();+ return fit.session!.exercises.first.id;+ }++ void before(List<LoggedExercise> ex) => fit.sessions+ .add(LoggedSession(DateTime.now().subtract(const Duration(days: 1)), 1800, ex));++ void logSet(int reps, double kg) {+ fit.setSessionReps(0, 0, reps);+ fit.setSessionWeight(0, 0, kg);+ fit.toggleSet(0, 0);+ fit.finishSession();+ }++ test('peso corporal: compara repeticiones, no da −100 %', () {+ final id = startOne();+ before([LoggedExercise(id, id, 'chest', [LoggedSet(10, 0)])]);+ logSet(12, 0);+ expect(fit.summaryVsLast, 20);+ expect(fit.summaryFirstTime, isFalse);+ });++ test('solo cuentan los ejercicios en común, no la rutina larga de ayer', () {+ final id = startOne();+ before([+ LoggedExercise(id, id, 'chest', [LoggedSet(10, 50)]),+ LoggedExercise('otro', 'otro', 'back', [LoggedSet(10, 100)]),+ ]);+ logSet(10, 55);+ expect(fit.summaryVsLast, 10);+ });++ test('ayer con peso y hoy sin peso: pasa a repeticiones', () {+ final id = startOne();+ before([LoggedExercise(id, id, 'chest', [LoggedSet(8, 40)])]);+ logSet(8, 0);+ expect(fit.summaryVsLast, 0);+ });++ test('sin sesión anterior con esos ejercicios es la primera vez', () {+ startOne();+ before([LoggedExercise('otro', 'otro', 'back', [LoggedSet(10, 100)])]);+ logSet(10, 20);+ expect(fit.summaryVsLast, isNull);+ expect(fit.summaryFirstTime, isTrue);+ });++ test('nada que comparar (solo tiempo) no enseña tarjeta', () {+ final id = startOne();+ before([LoggedExercise(id, id, 'chest', [LoggedSet(0, 0, sec: 60)])]);+ logSet(0, 0);+ expect(fit.summaryVsLast, isNull);+ expect(fit.summaryFirstTime, isFalse);+ });+ });++ group('#271 RPE en el historial', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ fit.autoAdvance = false;+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ test('cada serie con esfuerzo lleva su etiqueta', () {+ fit.setEffortMode('rpe');+ final label = fit.setsSummary([LoggedSet(5, 100, rpe: 8), LoggedSet(5, 100)]);+ expect(label, '${fit.loggedSetLabel(LoggedSet(5, 100))} @8 · ${fit.loggedSetLabel(LoggedSet(5, 100))}');+ });+ });++ group('#107 entreno pasado con su hora', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineOf(List<String> names) {+ final id = fit.createRoutine('Push');+ for (final name in names) {+ fit.toggleRoutineExercise(id, idOf(name));+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ test('la hora y la duración elegidas llegan al historial', () {+ final day = DateTime.now().subtract(const Duration(days: 2));+ fit.startRoutine(routineOf(['Barbell Bench Press']), on: day);+ fit.setManualStart(18 * 60 + 30);+ fit.setManualMinutes(45);+ fit.stepOutOfSession();+ fit.stepBackIntoSession();+ expect(fit.manualMinutes, 45, reason: 'salir y volver no toca la duración');+ fit.toggleSet(0, 0);+ fit.finishSession();+ final s = fit.sessions.last;+ expect(s.durationSec, 45 * 60);+ expect(s.date, DateTime(day.year, day.month, day.day, 19, 15));+ });+ });+}diff --git a/test/home_test.dart b/test/home_test.dartnew file mode 100644index 0000000..aba74e6--- /dev/null+++ b/test/home_test.dart@@ -0,0 +1,312 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:gymmane/theme/app_colors.dart';+import 'package:gymmane/widgets/home_widget_views.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ group('rutinas en inicio', () {+ late List<String> ids;++ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ ids = fit.allExercises.take(6).map((e) => e.id).toList();+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String routineWith(String name, List<String> exs) {+ final r = fit.createRoutine(name);+ for (final id in exs) {+ fit.toggleRoutineExercise(r, id);+ }+ return r;+ }++ LoggedSession done(String routineId, int ago) => LoggedSession(+ DateTime.now().subtract(Duration(days: ago)),+ 1800,+ [LoggedExercise(ids[0], 'x', 'chest', [LoggedSet(8, 60)])],+ routineId: routineId,+ );++ group('#174 rutina de hoy hecha', () {+ test('tras hacerla no queda nada pendiente hoy', () {+ final r = routineWith('Básica', ids.take(2).toList());+ fit.weeklyPlan[DateTime.now().weekday] = r;+ expect(fit.pendingRoutinesOn(DateTime.now()).map((e) => e.id), [r]);++ fit.sessions.add(done(r, 0));+ expect(fit.pendingRoutinesOn(DateTime.now()), isEmpty);+ expect(fit.todayRoutine?.id, r);+ });+ });++ group('#176 rutinas en inicio', () {+ test('la última hecha va primero y las nunca hechas al final en su orden', () {+ final a = routineWith('A', [ids[0]]);+ final b = routineWith('B', [ids[1]]);+ final c = routineWith('C', [ids[2]]);+ final d = routineWith('D', [ids[3]]);+ fit.sessions.addAll([done(a, 5), done(c, 1), done(a, 9)]);++ expect(fit.routinesByLastDone.map((r) => r.id), [c, a, b, d]);+ expect(fit.lastDoneOf(b), isNull);+ });+ });++ group('#175 ajustes de inicio', () {+ test('las dos tarjetas se pueden quitar y se recuerdan', () async {+ expect(fit.showWeekStats, isTrue);+ expect(fit.showRoutineRow, isTrue);+ fit.toggleWeekStats();+ fit.toggleRoutineRow();+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.showWeekStats, isFalse);+ expect(fit.showRoutineRow, isFalse);+ });++ test('las series de la tarjeta semanal son las de la semana', () {+ fit.sessions.add(LoggedSession(DateTime.now(), 600, [+ LoggedExercise(ids[0], 'x', 'chest', [LoggedSet(8, 60), LoggedSet(8, 60)]),+ ]));+ expect(fit.weekSetCount, 2);+ });+ });+ });++ group('#234 tira de la semana', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ test('con una rutina pendiente el día sale a medias, no hecho', () {+ fit.toggleMultiPlan();+ final a = fit.createRoutine('A');+ final b = fit.createRoutine('B');+ final today = DateTime.now().weekday;+ fit.togglePlanDay(today, a);+ fit.togglePlanDay(today, b);+ expect(fit.isDayPartial(fit.todayIndex), isFalse);++ fit.sessions.add(LoggedSession(DateTime.now().copyWith(hour: 12), 600, [+ LoggedExercise('x', 'X', 'chest', [LoggedSet(5, 60)]),+ ], routineId: a));+ expect(fit.isDayDone(fit.todayIndex), isTrue);+ expect(fit.isDayPartial(fit.todayIndex), isTrue);++ fit.sessions.add(LoggedSession(DateTime.now().copyWith(hour: 12), 600, [+ LoggedExercise('x', 'X', 'chest', [LoggedSet(5, 60)]),+ ], routineId: b));+ expect(fit.isDayPartial(fit.todayIndex), isFalse);+ });++ test('un día con una sola rutina sigue igual que antes', () {+ final a = fit.createRoutine('A');+ fit.togglePlanDay(DateTime.now().weekday, a);+ fit.sessions.add(LoggedSession(DateTime.now().copyWith(hour: 12), 600, [+ LoggedExercise('x', 'X', 'chest', [LoggedSet(5, 60)]),+ ], routineId: a));+ expect(fit.isDayPartial(fit.todayIndex), isFalse);+ });+ });++ group('widgets de inicio', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ testWidgets('el widget de hoy dice hecho o no sin poner el día', (tester) async {+ Future<void> show(bool done) => tester.pumpWidget(Directionality(+ textDirection: TextDirection.ltr,+ child: Center(child: TodayWidgetView(gc: GymColors.dark, done: done, planned: true, streak: 0)),+ ));+ await show(false);+ expect(find.text('${DateTime.now().day}'), findsNothing);+ expect(find.byIcon(Icons.fitness_center_rounded), findsOneWidget);+ await show(true);+ expect(find.byIcon(Icons.check_rounded), findsOneWidget);+ });++ testWidgets('el widget de la semana cuenta los días hechos', (tester) async {+ await tester.pumpWidget(Directionality(+ textDirection: TextDirection.ltr,+ child: Center(+ child: WeekWidgetView(+ gc: GymColors.dark,+ done: const [true, false, true, false, false, false, false],+ goal: 4,+ ),+ ),+ ));+ expect(find.text('2'), findsOneWidget);+ expect(find.text('/4'), findsOneWidget);+ expect(find.byIcon(Icons.check_rounded), findsNWidgets(2));+ final geo = WeekWidgetView.geometry(const Size(320, 150));+ final origin = tester.getTopLeft(find.byType(WeekWidgetView));+ final dots = find.byWidgetPredicate(+ (w) => w is Container && w.decoration is BoxDecoration && (w.decoration as BoxDecoration).shape == BoxShape.circle);+ expect(dots, findsNWidgets(7));+ for (var i = 0; i < 7; i++) {+ final c = tester.getCenter(dots.at(i)) - origin;+ expect(c.dx / 320, closeTo(geo[0] + geo[1] * i, 0.002));+ expect(c.dy / 150, closeTo(geo[2], 0.002));+ }+ });+ });++ group('objetivo semanal y racha', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineOf(List<String> names) {+ final id = fit.createRoutine('Push');+ for (final name in names) {+ fit.toggleRoutineExercise(id, idOf(name));+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ LoggedSession logged(DateTime at, List<LoggedSet> sets, {String id = 'push', String primary = 'chest'}) =>+ LoggedSession(at, 600, [LoggedExercise(id, id, primary, sets)]);++ group('#117 objetivo semanal por días', () {+ test('dos sesiones el mismo día son un día', () {+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 60)]));+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 60)]));+ expect(fit.daysDoneThisWeek, 1);+ });++ test('marcar y desmarcar un día lo deja como estaba', () {+ final before = fit.daysDoneThisWeek;+ fit.toggleCheckin(fit.todayIndex);+ expect(fit.daysDoneThisWeek, before + 1);+ fit.toggleCheckin(fit.todayIndex);+ expect(fit.daysDoneThisWeek, before);+ expect(fit.currentStreak, 0);+ });+ });++ group('#85 racha con calendario', () {+ test('un día sin rutina no rompe la racha', () {+ final today = DateTime.now();+ final yesterday = DateTime(today.year, today.month, today.day - 1);+ final before = DateTime(today.year, today.month, today.day - 2, 18);+ fit.sessions.add(logged(today, [LoggedSet(5, 60)]));+ fit.sessions.add(logged(before, [LoggedSet(5, 60)]));+ expect(fit.currentStreak, 1);++ final r = routineOf(['Barbell Bench Press']);+ for (var d = 1; d <= 7; d++) {+ if (d != yesterday.weekday) fit.assignRoutineToDay(d, r.id);+ }+ expect(fit.currentStreak, 2);+ });+ });+ });++ group('hábitos y ajustes de inicio', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ String bench() => fit.matchExerciseByName('Barbell Bench Press')!.id;++ 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('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/lyfta_import_test.dart b/test/lyfta_import_test.dartnew file mode 100644index 0000000..300a42d--- /dev/null+++ b/test/lyfta_import_test.dart@@ -0,0 +1,80 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/services/workout_import.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ group('lyfta', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ const csv = 'Title,Date,Duration,Description,Notes,Exercise,Exercise Note,Superset id,Weight,Reps,'+ 'RIR/RPE,Distance,Time,Set Type,RecordLevel: gold/silver/bronze,RecordType: 1RM / max_weight / volume / reps\n'+ 'Pull Day,2026-04-17 16:00:05,01:19:33,"A plan, with commas",,Barbell Bent Over Row,,,60.000,10,,,,NORMAL_SET,,\n'+ 'Pull Day,2026-04-17 16:00:05,01:19:33,"A plan, with commas",,Barbell Bent Over Row,,,70.000,8,,,,NORMAL_SET,1,1\n'+ 'Pull Day,2026-04-17 16:00:05,01:19:33,"A plan, with commas",,Pull Up,,,,12,,,,NORMAL_SET,,\n';++ test('the export is recognised and read', () {+ expect(detectFormat(csv), ImportFormat.lyfta);+ final result = parseImport(csv);+ final session = result.sessions.single;+ expect(session.durationSec, 3600 + 19 * 60 + 33);+ expect(session.exercises.first.sets.map((s) => s.weightKg), [60, 70]);+ expect(session.exercises.last.name, 'Pull Up');+ });+ });++ group('#55 nombres de Lyfta', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String? match(String name) => fit.matchExerciseByName(name)?.name;++ test('no cambia de músculo por una palabra suelta', () {+ expect(match('Dumbbell Seated Curl'), isNot('Seated Leg Curl'));+ expect(match('Lever Seated Leg Extension'), isNot(contains('Calf')));+ expect(match('Dumbbell Seated One Arm Rotate'), isNull);+ });++ test('el nombre exacto gana', () {+ expect(match('Machine Reverse Fly'), 'Machine Reverse Fly');+ expect(match('Smith Hack Squat'), 'Smith Hack Squat');+ });++ test('encuentra el ejercicio aunque el nombre traiga más cosas', () {+ expect(match('Cable Standing Face Pull (with rope)'), 'Face Pull');+ expect(match('Barbell Feet Flat Bench Press (male)'), 'Barbell Bench Press');+ expect(match('Lever Pec Deck Fly'), 'Pec Deck');+ expect(match('Close Grip Preacher Curl'), 'Barbell Preacher Curl');+ });++ test('su columna RIR/RPE se entiende en las dos escalas', () {+ const csv = 'Title,Date,Duration,Description,Notes,Exercise,Exercise Note,Superset id,Weight,Reps,'+ 'RIR/RPE,Distance,Time,Set Type,RecordLevel: gold/silver/bronze,RecordType: 1RM / max_weight / volume / reps\n'+ 'Pull,2026-04-17 16:00:05,01:00:00,,,Barbell Curl,,,30.000,10,2,,,NORMAL_SET,,\n'+ 'Pull,2026-04-17 16:00:05,01:00:00,,,Barbell Curl,,,30.000,8,8.5,,,NORMAL_SET,,\n'+ 'Pull,2026-04-17 16:00:05,01:00:00,,,Barbell Curl,,,30.000,8,,,,NORMAL_SET,,\n';+ final sets = parseImport(csv).sessions.single.exercises.single.sets;+ expect(sets.map((s) => s.rpe), [8, 8.5, null]);+ });+ });+}diff --git a/test/muscles_test.dart b/test/muscles_test.dartnew file mode 100644index 0000000..9eb71ae--- /dev/null+++ b/test/muscles_test.dart@@ -0,0 +1,124 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/catalog/exercise_catalog.dart';+import 'package:gymmane/l10n/l10n.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();++ group('#167 músculos secundarios', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ test('se cambian en un ejercicio de la app, se guardan y se pueden restablecer', () {+ final ex = fit.allExercises.firstWhere((e) => e.secondary.length == 1 && e.primary == 'chest');+ final before = [...ex.secondary];+ fit.setSecondary(ex.id, [...before, 'shoulders']);+ expect(fit.exerciseById(ex.id)!.secondary, containsAll([...before, 'shoulders']));+ fit.setMuscleFilter('shoulders');+ expect(fit.exercisesFiltered.map((e) => e.id), contains(ex.id));+ fit.setMuscleFilter('shoulders');+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.exerciseById(ex.id)!.secondary, contains('shoulders'));+ fit.resetSecondary(ex.id);+ expect(fit.exerciseById(ex.id)!.secondary, before);+ expect(fit.hasSecondaryOverride(ex.id), isFalse);+ });++ test('volver a lo de siempre no deja nada guardado y el primario no cuenta', () {+ final ex = fit.allExercises.firstWhere((e) => e.secondary.isNotEmpty);+ fit.setSecondary(ex.id, [...ex.secondary, ex.primary]);+ expect(fit.hasSecondaryOverride(ex.id), isFalse);+ expect(fit.exerciseById(ex.id)!.secondary, isNot(contains(ex.primary)));+ });++ test('en uno propio cambia el ejercicio', () {+ final id = fit.addCustomExercise(name: 'Mío', primary: 'chest', equipment: 'Dumbbell');+ fit.setSecondary(id, ['triceps']);+ expect(fit.exerciseById(id)!.secondary, ['triceps']);+ expect(fit.hasSecondaryOverride(id), isFalse);+ });+ });++ group('músculos sin entrenar', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ test('cuenta los días desde la última serie del músculo principal', () {+ final now = DateTime.now();+ fit.sessions.add(LoggedSession(now.subtract(const Duration(days: 9)), 600, [+ LoggedExercise(bench(), 'Bench Press', 'chest', [LoggedSet(8, 60)]),+ ]));+ final days = fit.daysSinceTrained();+ expect(days['chest'], 9);+ expect(days['quads'], isNull);+ expect(fit.untrainedLongest(), isNot(contains('chest')));+ expect(fit.untrainedLongest().length, 3);+ });+ });++ group('recovery', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ test('nothing trained means fully recovered', () {+ expect(fit.overallRecovery(), 100);+ expect(fit.stillRecovering(), isEmpty);+ });++ test('a hard chest day tires the chest and it recovers in a few days', () {+ final now = DateTime(2026, 9, 18, 18);+ fit.sessions.add(LoggedSession(now.subtract(const Duration(hours: 1)), 3600, [+ LoggedExercise(idOf('Barbell Bench Press'), 'Bench', 'chest',+ [for (var i = 0; i < 8; i++) LoggedSet(8, 80, rpe: 9)]),+ ]));+ final fresh = fit.muscleRecovery(now: now);+ expect(fresh['chest'], lessThan(0.3));+ expect(fresh['quads'], 1);+ expect(fit.hoursUntilRecovered('chest', now: now), greaterThan(12));+ final later = fit.muscleRecovery(now: now.add(const Duration(days: 4)));+ expect(later['chest'], greaterThan(0.8));+ expect(fit.stillRecovering(now: now), contains('chest'));+ });+ });++ group('músculos de la prensa', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ test('#238 la prensa de piernas trabaja sobre todo cuádriceps', () {+ final press = kExercises.firstWhere((e) => e.name == 'Leg Press');+ expect(press.primary, 'quads');+ expect(press.secondary, containsAll(['glutes', 'hamstrings']));+ });+ });+}diff --git a/test/nutrition_log_test.dart b/test/nutrition_log_test.dartnew file mode 100644index 0000000..011e1d5--- /dev/null+++ b/test/nutrition_log_test.dart@@ -0,0 +1,203 @@+import 'dart:convert';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.dart';+import 'package:gymmane/models/nutrition.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();++ group('widgets de nutrición', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ test('lo tocado en el widget se apunta con su hora, en su día, y lo muy viejo se ignora', () {+ final now = DateTime.now();+ final ms = now.subtract(const Duration(minutes: 5)).millisecondsSinceEpoch;+ final twoDays = now.subtract(const Duration(days: 2));+ final old = twoDays.millisecondsSinceEpoch;+ final stale = now.subtract(const Duration(days: 10)).millisecondsSinceEpoch;+ final food = fit.saveFood(name: 'Batido', macros: const Macros(kcal: 120, protein: 24));+ final before = fit.waterOn(now);+ final n = fit.takeWidgetLog('w,$ms,250;w,$old,250;w,$stale,250;s,$ms,${food.id};x,1,2;w,bad,3');+ expect(n, 3);+ expect(fit.waterOn(twoDays), 250);+ expect(fit.waterOn(now), before + 250);+ expect(fit.totalOn(now).protein.round(), 24);+ expect(fit.waterSipsOn(now).last.at.millisecondsSinceEpoch, ms);+ });+ });++ group('#226 batidos marcados', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ const whey = Macros(kcal: 120, protein: 24, carbs: 3, fat: 1.5);++ test('elegir un batido lo marca y solo los marcados salen en la lista', () {+ final a = fit.saveFood(name: 'Whey', macros: whey);+ fit.saveFood(name: 'Avena', macros: const Macros(kcal: 380));+ fit.setShakeFood(a.id);+ expect(fit.isShakeFood(a.id), isTrue);+ expect(fit.shakeFoodItems.map((f) => f.id), [a.id]);+ });++ test('quitar la marca del elegido pasa al siguiente marcado', () {+ final a = fit.saveFood(name: 'Whey', macros: whey);+ final b = fit.saveFood(name: 'Vegano', macros: whey);+ fit.setShakeFood(a.id);+ fit.setShakeTag(b.id, true);+ fit.setShakeTag(a.id, false);+ expect(fit.shakeFoodId, b.id);+ fit.setShakeTag(b.id, false);+ expect(fit.shakeFoodId, '');+ expect(fit.shakeFood, isNull);+ });++ test('marcar el primero lo deja elegido para el vaso', () {+ final a = fit.saveFood(name: 'Whey', macros: whey);+ fit.setShakeTag(a.id, true);+ expect(fit.shakeFoodId, a.id);+ });++ test('borrar el alimento quita la marca', () {+ final a = fit.saveFood(name: 'Whey', macros: whey);+ fit.setShakeTag(a.id, true);+ fit.deleteFood(a.id);+ expect(fit.shakeFoods, isEmpty);+ });++ test('las marcas sobreviven a guardar y cargar', () {+ final a = fit.saveFood(name: 'Whey', macros: whey);+ final b = fit.saveFood(name: 'Vegano', macros: whey);+ fit.setShakeFood(a.id);+ fit.setShakeTag(b.id, true);+ final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;+ fit.applyBackup(data);+ expect(fit.shakeFoods.toSet(), {a.id, b.id});+ expect(fit.shakeFoodId, a.id);+ });++ test('una copia antigua sin marcas conserva su batido elegido', () {+ final a = fit.saveFood(name: 'Whey', macros: whey);+ fit.setShakeFood(a.id);+ final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;+ (data['nutrition'] as Map).remove('shakes');+ fit.applyBackup(data);+ expect(fit.shakeFoods, [a.id]);+ expect(fit.shakeFoodId, a.id);+ });+ });++ group('#247 completa tu día', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ setAppLanguage('en');+ });++ setUp(() {+ fit.nutritionBeta = true;+ fit.setAddBurned(false);+ fit.setNutritionGoals(const NutritionGoals(kcal: 2000, protein: 150));+ fit.setTracker(Tracker.protein, true);+ });++ FoodItem chicken() =>+ fit.saveFood(name: 'Pollo', grams: 100, macros: const Macros(kcal: 120, protein: 25, carbs: 0, fat: 2));+ FoodItem rice() =>+ fit.saveFood(name: 'Arroz', grams: 100, macros: const Macros(kcal: 350, protein: 7, carbs: 78, fat: 1));++ test('un alimento proteico cierra la proteína sin pasarse de kcal', () {+ fit.logFood(fit.saveFood(name: 'Base', grams: 100, macros: const Macros(kcal: 1500, protein: 100, carbs: 150, fat: 50)));+ expect(fit.fillGrams(chicken()), closeTo(200, 0.01));+ });++ test('si las kcal se acaban antes, manda el tope de kcal', () {+ fit.logFood(fit.saveFood(name: 'Base', grams: 100, macros: const Macros(kcal: 1880, protein: 60, carbs: 200, fat: 60)));+ expect(fit.fillGrams(chicken()), closeTo(100, 0.01));+ });++ test('un alimento con poca proteína solo rellena las kcal', () {+ fit.logFood(fit.saveFood(name: 'Base', grams: 100, macros: const Macros(kcal: 1300, protein: 145, carbs: 100, fat: 40)));+ expect(fit.fillGrams(rice()), closeTo(200, 0.01));+ });++ test('sin kcal libres no propone nada', () {+ fit.logFood(fit.saveFood(name: 'Base', grams: 100, macros: const Macros(kcal: 2100, protein: 100, carbs: 200, fat: 60)));+ expect(fit.fillGrams(chicken()), isNull);+ });++ test('al editar una entrada, su propia ración no cuenta como comida', () {+ final e = fit.logFood(chicken(), servings: 2);+ expect(fit.fillGrams(chicken(), replacing: e.total), closeTo(600, 0.01));+ });++ test('te quedarán: resta lo que vas a apuntar', () {+ fit.logFood(fit.saveFood(name: 'Base', grams: 100, macros: const Macros(kcal: 1000, protein: 50, carbs: 100, fat: 30)));+ final left = fit.leftAfter(const Macros(kcal: 240, protein: 50, carbs: 0, fat: 4));+ expect(left.kcal, 760);+ expect(left.protein, 50);+ });+ });++ group('comidas propias y días futuros', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ fit.autoAdvance = false;+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ group('#269 categoría en comidas propias', () {+ test('se guarda, sobrevive a la copia y filtra la búsqueda', () {+ final mine = fit.saveFood(name: 'Pollo marca X', grams: 100, macros: const Macros(kcal: 110), cat: FoodCat.meat);+ fit.saveFood(name: 'Yogur', grams: 125, macros: const Macros(kcal: 80), cat: FoodCat.dairy);+ fit.saveFood(name: 'Sin nada', macros: const Macros(kcal: 50));+ expect(FoodItem.fromJson(mine.toJson()).cat, FoodCat.meat);+ expect(fit.searchFoods('', cat: FoodCat.meat).map((f) => f.name), ['Pollo marca X']);+ expect(fit.searchFoods(''), hasLength(3));+ });++ test('editar puede cambiar o quitar la categoría', () {+ final f = fit.saveFood(name: 'Pan', cat: FoodCat.bakery);+ expect(fit.saveFood(id: f.id, name: 'Pan', cat: FoodCat.grain).cat, FoodCat.grain);+ expect(fit.saveFood(id: f.id, name: 'Pan').cat, isNull);+ });+ });++ group('#273 comidas al futuro', () {+ test('se puede mover una comida a mañana y ver ese día', () {+ final food = fit.saveFood(name: 'Cena', macros: const Macros(kcal: 600));+ final e = fit.logFood(food);+ final now = DateTime.now();+ final tomorrow = DateTime(now.year, now.month, now.day + 1);+ fit.moveEntryToDay(e.id, tomorrow);+ expect(fit.entriesOn(tomorrow).map((x) => x.id), [e.id]);+ fit.setNutritionDay(tomorrow);+ expect(fit.nutritionDay, tomorrow);+ fit.setNutritionDay(DateTime(now.year, now.month, now.day + 30));+ expect(fit.nutritionDay, DateTime(now.year, now.month, now.day + 7));+ });+ });+ });+}diff --git a/test/plan_import_export_test.dart b/test/plan_import_export_test.dartnew file mode 100644index 0000000..e9a1fa6--- /dev/null+++ b/test/plan_import_export_test.dart@@ -0,0 +1,239 @@+import 'dart:convert';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/services/plan_pdf.dart';+import 'package:gymmane/services/plan_share.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ group('reading plans', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineWith(List<String> ids, {String name = 'Push'}) {+ final id = fit.createRoutine(name);+ for (final ex in ids) {+ fit.toggleRoutineExercise(id, ex);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ test('an AI plan with weeks, days, reps, weight and supersets', () {+ final plans = parsePlan('Here you go!\n```json\n'+ '{"program": "Base", "unit": "lb", "weeks": ['+ '{"name": "Week 1", "routines": [{"name": "A", "days": ["Monday", "jue"], "exercises": ['+ '{"name": "Barbell Bench Press", "sets": 3, "reps": "8-10", "weight": 135, "rest": "2 min", "superset": true},'+ '{"name": "Barbell Bent Over Row", "sets": 3, "reps": 8}]}]},'+ '{"name": "Week 2", "routines": [{"name": "A", "exercises": ["Pull Up"]}]}]}\n```');+ expect(plans.length, 2);+ expect(plans.first.group, 'Base · Week 1');+ expect(plans.first.days, [1, 4]);+ final bench = plans.first.items.first;+ expect(bench.reps, 8);+ expect(bench.weightKg, closeTo(61.2, 0.1));+ expect(bench.restSec, 120);+ expect(bench.superset, isTrue);+ expect(plans.last.group, 'Base · Week 2');+ });++ test('a csv plan', () {+ final plans = parsePlan('routine;exercise;sets;reps;weight\n'+ 'Push;Barbell Bench Press;4;8;60\nPush;Push Up;3;15;\nLegs;Barbell Full Squat;5;5;100');+ expect(plans.map((p) => p.name), ['Push', 'Legs']);+ expect(plans.first.items.first.weightKg, 60);+ expect(plans.last.items.single.sets, 5);+ });++ test('prose with commas is not taken for a plan', () {+ expect(parsePlan('Sure, here is your routine, enjoy it'), isEmpty);+ });++ test('importing builds planned sets, supersets and the week, once', () {+ final text = '{"routines": [{"name": "Upper", "days": [2], "exercises": ['+ '{"name": "Barbell Bench Press", "sets": 2, "reps": 8, "weight": 60, "superset": true,'+ ' "plan": [{"type": "warmup", "reps": 10, "weight": 30}]},'+ '{"name": "Barbell Bent Over Row", "sets": 3}]}]}';+ final plans = parsePlan(text);+ final first = fit.applyPlan(plans, schedule: true);+ expect(first.routines, 1);+ final r = fit.routines.single;+ final bench = idOf('Barbell Bench Press');+ expect(fit.plannedSets(r, bench).map((p) => p.kind), [SetKind.warmup, SetKind.normal, SetKind.normal]);+ expect(fit.routineSets(r, bench), 2);+ expect(fit.routineSets(r, idOf('Barbell Bent Over Row')), 3);+ expect(r.chained, contains(bench));+ expect(fit.weeklyPlan[2], r.id);+ final again = fit.applyPlan(plans);+ expect(again.routines, 0);+ expect(fit.routines.length, 1);+ });++ test('a shared plan round-trips to another phone, custom exercises included', () {+ final mine = fit.addCustomExercise(+ name: 'Landmine Twist', primary: 'obliques', equipment: 'Barbell', steps: ['Twist']);+ final bench = idOf('Barbell Bench Press');+ final r = routineWith([bench, mine], name: 'Mixed');+ fit.setRoutineGroup(r.id, 'Couple');+ fit.setPlannedSets(r.id, bench, const [PlannedSet(reps: 8, weightKg: 50)]);+ fit.assignRoutineToDay(3, r.id);+ final json = fit.exportPlanJson([r]);+ expect(jsonDecode(json)['gymmane'], 'plan');+ expect(fit.planSummaryText([r]), contains('Mixed'));++ fit.resetAllData();+ final result = fit.applyPlan(parsePlan(json), schedule: true);+ expect(result.routines, 1);+ expect(result.missed, isEmpty);+ final got = fit.routines.single;+ expect(got.name, 'Mixed');+ expect(got.group, 'Couple');+ expect(fit.plannedSets(got, bench).single.weightKg, 50);+ final twist = fit.customExercises.single;+ expect(twist.name, 'Landmine Twist');+ expect(twist.steps, ['Twist']);+ expect(got.exerciseIds, [bench, twist.id]);+ expect(fit.weeklyPlan[3], got.id);+ });++ test('the request for an AI carries the format', () {+ final text = fit.planRequestText();+ expect(text, contains('"weeks"'));+ expect(text, contains('Barbell Bench Press'));+ });+ });++ group('plan en PDF', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ testWidgets('sale un PDF válido con una página por cada tanda', (tester) async {+ setAppLanguage('es');+ final id = fit.createRoutine('Empuje');+ for (final name in ['Bench Press', 'Barbell Squat', 'Barbell Bent Over Row']) {+ fit.toggleRoutineExercise(id, fit.matchExerciseByName(name)!.id);+ }+ fit.assignRoutineToDay(DateTime.monday, id);+ final bytes = await tester.runAsync(() => buildPlanPdf(fit.routines, week: true));+ await tester.pump(const Duration(seconds: 1));+ final text = latin1.decode(bytes!);+ expect(text.startsWith('%PDF-1.4'), isTrue);+ expect(text.trimRight().endsWith('%%EOF'), isTrue);+ expect(RegExp(r'/Type /Page ').allMatches(text).length, 1);+ String hex(String v) => '<FEFF${v.codeUnits.map((u) => u.toRadixString(16).padLeft(4, '0').toUpperCase()).join()}>';+ expect(text, contains('/Author ${hex('InlitX')}'));+ expect(text, contains('/Lang (es)'));+ expect(text, contains('<dc:creator><rdf:Seq><rdf:li>InlitX</rdf:li></rdf:Seq></dc:creator>'));+ expect(text, contains('<xmp:CreatorTool>GymMane</xmp:CreatorTool>'));+ final xref = int.parse(RegExp(r'startxref\n(\d+)').firstMatch(text)!.group(1)!);+ expect(text.substring(xref, xref + 4), 'xref');+ for (final m in RegExp(r'(\d{10}) 00000 n ').allMatches(text)) {+ final at = int.parse(m.group(1)!);+ expect(RegExp(r'^\d+ 0 obj').hasMatch(text.substring(at, at + 12)), isTrue);+ }+ });++ testWidgets('una rutina larga pasa a otra página', (tester) async {+ setAppLanguage('es');+ final id = fit.createRoutine('Larga');+ for (final e in fit.allExercises.take(24)) {+ fit.toggleRoutineExercise(id, e.id);+ }+ final bytes = await tester.runAsync(() => buildPlanPdf([fit.routines.single]));+ await tester.pump(const Duration(seconds: 1));+ final pages = RegExp(r'/Type /Page ').allMatches(latin1.decode(bytes!)).length;+ expect(pages, greaterThan(1));+ });+ });++ group('importar una rutina que ya tienes', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ setAppLanguage('en');+ });++ String own() {+ final id = fit.createRoutine('Push');+ fit.toggleRoutineExercise(id, fit.matchExerciseByName('Barbell Bench Press')!.id);+ return fit.exportPlanJson(fit.routines);+ }++ test('la vista previa sabe que ya la tienes', () {+ final plans = parsePlan(own());+ final preview = fit.previewPlan(plans);+ expect(preview.routines, 1);+ expect(preview.owned, 1);+ expect(fit.ownsPlan(plans.single), isTrue);+ });++ test('como copia se añade otra vez', () {+ final plans = parsePlan(own());+ expect(fit.applyPlan(plans).routines, 0);+ expect(fit.applyPlan(plans, copies: true).routines, 1);+ expect(fit.routines.length, 2);+ });++ test('en otro móvil se importa normal', () {+ final json = own();+ fit.resetAllData();+ final plans = parsePlan(json);+ expect(fit.previewPlan(plans).owned, 0);+ expect(fit.applyPlan(plans).routines, 1);+ });+ });++ group('texto para la IA', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ LoggedSession logged(DateTime at, List<LoggedSet> sets, {String id = 'push', String primary = 'chest'}) =>+ LoggedSession(at, 600, [LoggedExercise(id, id, primary, sets)]);++ test('un usuario nuevo pide empezar suave y que le pregunten', () {+ final text = fit.planRequestText();+ expect(text, contains(t.planNoHistory));+ expect(text, contains(t.planAskFirst));+ expect(text, contains(t.planDays(fit.weeklyTarget)));+ });++ test('con historial lleva los entrenos y las mejores series', () {+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 100)], id: idOf('Barbell Bench Press')));+ final text = fit.planRequestText();+ expect(text, isNot(contains(t.planNoHistory)));+ expect(text, contains(t.planHistory(1)));+ expect(text, contains(t.planBestLifts));+ });+ });+}diff --git a/test/polish_test.dart b/test/polish_test.dartdeleted file mode 100644index b8d0b25..0000000--- a/test/polish_test.dart+++ /dev/null@@ -1,198 +0,0 @@-import 'dart:math' as math;--import 'package:flutter/material.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/catalog/exercise_catalog.dart';-import 'package:gymmane/l10n/l10n.dart';-import 'package:gymmane/models/workout.dart';-import 'package:gymmane/services/local_store.dart';-import 'package:gymmane/state/fit_state.dart';-import 'package:gymmane/theme/app_colors.dart';-import 'package:shared_preferences/shared_preferences.dart';--void main() {- TestWidgetsFlutterBinding.ensureInitialized();-- setUp(() async {- SharedPreferences.setMockInitialValues({});- await Store.instance.init();- fit.resetAllData();- fit.onboarded = true;- setAppLanguage('en');- });-- group('favourites filter', () {- test('marking a star and filtering leaves only that exercise', () {- final a = kExercises[0], b = kExercises[1];- fit.toggleFavorite(a.id);- expect(fit.favouriteCount, 1);-- fit.toggleFavouritesFilter();- final list = fit.exercisesFiltered;- expect(list.map((e) => e.id), [a.id]);- expect(list.contains(b), false);- });-- test('the filter stacks with the muscle one instead of replacing it', () {- final chest = kExercises.firstWhere((e) => e.primary == 'chest');- final back = kExercises.firstWhere((e) => e.primary == 'back');- fit.toggleFavorite(chest.id);- fit.toggleFavorite(back.id);-- fit.toggleFavouritesFilter();- fit.setMuscleFilter('chest');- expect(fit.exercisesFiltered.map((e) => e.id), contains(chest.id));- expect(fit.exercisesFiltered.map((e) => e.id), isNot(contains(back.id)));- });-- test('un-starring drops it out of the filtered list', () {- final a = kExercises[0];- fit.toggleFavorite(a.id);- fit.toggleFavouritesFilter();- expect(fit.exercisesFiltered, isNotEmpty);-- fit.toggleFavorite(a.id);- expect(fit.favouriteCount, 0);- expect(fit.exercisesFiltered, isEmpty);- });-- test('clearing filters brings the whole library back', () {- fit.toggleFavouritesFilter();- fit.setMuscleFilter('chest');- fit.setExSearch('press');- fit.clearExFilters();- 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');- expect(fit.exercisesFiltered, isNotEmpty);- fit.clearExFilters();- });- });-- group('naming a routine', () {- test('a new routine starts unnamed so the field shows its hint', () {- final id = fit.createRoutine();- expect(fit.routines.single.name, '');- expect(fit.routineTitle(fit.routines.single), t.newRoutineName);- fit.renameRoutine(id, 'Empuje');- expect(fit.routineTitle(fit.routines.single), 'Empuje');- });-- test('clearing the name to retype it does not stick the old one', () {- final id = fit.createRoutine('Viejo');- fit.renameRoutine(id, '');- expect(fit.routines.single.name, '');- fit.renameRoutine(id, 'Nuevo');- expect(fit.routines.single.name, 'Nuevo');- });- });-- group('finish screen tells the truth', () {- void logSession(String exId, double kg) {- fit.sessions.add(LoggedSession(DateTime.now().subtract(const Duration(days: 3)), 600,- [LoggedExercise(exId, 'X', 'chest', [LoggedSet(5, kg)])]));- }-- void doWorkout(double kg) {- fit.startWorkout();- fit.toggleMuscle('chest');- fit.trainContinue();- fit.startSession();- fit.setSessionWeight(0, 0, kg);- fit.setSessionReps(0, 0, 5);- fit.toggleSet(0, 0);- fit.finishSession();- }-- test('a real PR is counted; a lighter day is not', () {- final id = fit.allExercises.firstWhere((e) => e.primary == 'chest').id;- logSession(id, 60);-- doWorkout(80);- expect(fit.summaryPrs, 1);- fit.saveAndExit();-- doWorkout(50);- expect(fit.summaryPrs, 0, reason: 'se compara con TODO lo anterior, no con la última vez');- fit.saveAndExit();- });-- test('the headline changes with what actually happened', () {- expect(t.finishHeadline(prs: 1, streak: 0, goalHit: false),- isNot(t.finishHeadline(prs: 0, streak: 0, goalHit: false)));- expect(t.finishHeadline(prs: 0, streak: 0, goalHit: true),- isNot(t.finishHeadline(prs: 0, streak: 0, goalHit: false)));- setAppLanguage('es');- expect(t.finishHeadline(prs: 2, streak: 0, goalHit: false), 'Récord personal nuevo');- expect(t.finishBody(prs: 2, streak: 0, goalHit: false), contains('2 ejercicios'));- expect(t.finishBody(prs: 1, streak: 0, goalHit: false), contains('un ejercicio'));- });-- test('nothing logged means no fake celebration', () {- fit.startWorkout();- fit.toggleMuscle('chest');- fit.trainContinue();- fit.startSession();- fit.finishSession();- expect(fit.summaryPrs, 0);- expect(fit.summaryVsLast, isNull);- fit.saveAndExit();- });- });-- group('light theme belongs to the same family as dark', () {-- double lin(double c) => c <= 0.03928 ? c / 12.92 : math.pow((c + 0.055) / 1.055, 2.4).toDouble();- double lum(Color c) => 0.2126 * lin(c.r) + 0.7152 * lin(c.g) + 0.0722 * lin(c.b);- double contrast(Color a, Color b) {- final la = lum(a), lb = lum(b);- return (math.max(la, lb) + 0.05) / (math.min(la, lb) + 0.05);- }-- double warmth(Color c) => (c.r - c.b) * 255;-- test('light neutrals are warm, not cold grey', () {- for (final c in [GymColors.light.bg, GymColors.light.bgRaised2, GymColors.light.border]) {- expect(warmth(c), greaterThan(6), reason: 'neutro frío: $c');- }- });-- test('every text colour on light is actually readable', () {- final bg = GymColors.light.bg;- expect(contrast(bg, GymColors.light.text), greaterThan(7), reason: 'principal, AAA');- expect(contrast(bg, GymColors.light.textSecondary), greaterThan(4.5), reason: 'secundario, AA');-- expect(contrast(bg, GymColors.light.textTertiary), greaterThan(3), reason: 'terciario');- });-- test('the light accent reads on bone', () {-- expect(contrast(GymColors.light.bg, GymColors.light.accent), greaterThanOrEqualTo(4.5));- });-- test('dark text stays readable too', () {- final bg = GymColors.dark.bg;- expect(contrast(bg, GymColors.dark.text), greaterThan(7));- expect(contrast(bg, GymColors.dark.textSecondary), greaterThan(4.5));- });-- test('action colour flips with the theme but keeps its contrast', () {- expect(contrast(GymColors.dark.ember, GymColors.dark.onEmber), greaterThan(7));- expect(contrast(GymColors.light.ember, GymColors.light.onEmber), greaterThan(7));- });- });-}diff --git a/test/progression_test.dart b/test/progression_test.dartnew file mode 100644index 0000000..69fbfeb--- /dev/null+++ b/test/progression_test.dart@@ -0,0 +1,415 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.dart';+import 'package:gymmane/models/progression.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();++ group('descarga automática', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ DateTime ago(int days, [int hour = 18]) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day - days, hour);+ }++ void logged(String id, int days, List<LoggedSet> sets) =>+ fit.sessions.add(LoggedSession(ago(days), 1200, [LoggedExercise(id, id, 'back', sets)]));++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ test('sin «subir el peso solo» no hay descarga', () {+ final id = bench();+ for (final d in [9, 6, 3]) {+ logged(id, d, [LoggedSet(8, 80), LoggedSet(6, 80)]);+ }+ expect(fit.stallStreak(id), 3);+ expect(fit.needsDeload(id), isFalse);+ });++ test('tres entrenos al mismo peso sin cumplir bajan al 90 %', () {+ final id = bench();+ fit.progressStep[id] = 2.5;+ for (final d in [9, 6, 3]) {+ logged(id, d, [LoggedSet(8, 80), LoggedSet(6, 80)]);+ }+ final next = fit.nextTarget(id)!;+ expect(next.deload, isTrue);+ expect(next.up, isFalse);+ expect(next.weightKg, 72.5);+ final r = fit.createRoutine('Pecho');+ fit.toggleRoutineExercise(r, id);+ fit.startRoutine(fit.routines.single);+ expect(fit.session!.exercises.single.sets.where((s) => s.kind != SetKind.warmup).first.weight, 72.5);+ fit.saveAndExit();+ });++ test('dos fallos no bastan y cambiar de peso empieza la cuenta de cero', () {+ final id = bench();+ fit.progressStep[id] = 2.5;+ logged(id, 12, [LoggedSet(8, 80), LoggedSet(6, 80)]);+ logged(id, 9, [LoggedSet(8, 80), LoggedSet(6, 80)]);+ expect(fit.needsDeload(id), isFalse);+ logged(id, 6, [LoggedSet(8, 72.5), LoggedSet(6, 72.5)]);+ expect(fit.stallStreak(id), 1);+ logged(id, 3, [LoggedSet(8, 72.5), LoggedSet(8, 72.5)]);+ expect(fit.stallStreak(id), 0);+ expect(fit.nextTarget(id)!.up, isTrue);+ });++ test('en una asistida la descarga da más ayuda', () {+ const pull = 'kiJ4Z2K';+ fit.progressStep[pull] = 2.5;+ for (final d in [9, 6, 3]) {+ logged(pull, d, [LoggedSet(8, 30), LoggedSet(5, 30)]);+ }+ final next = fit.nextTarget(pull)!;+ expect(next.deload, isTrue);+ expect(next.weightKg, 32.5);+ });++ test('con poco peso baja al menos un escalón', () {+ final id = bench();+ fit.progressStep[id] = 2.5;+ for (final d in [9, 6, 3]) {+ logged(id, d, [LoggedSet(8, 5), LoggedSet(6, 5)]);+ }+ expect(fit.nextTarget(id)!.weightKg, 2.5);+ });+ });++ group('#253 tipos de progresión', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ setAppLanguage('en');+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;+ DateTime ago(int d) => DateTime.now().subtract(Duration(days: d));+ void logged(String id, int days, List<LoggedSet> sets) =>+ fit.sessions.add(LoggedSession(ago(days), 1200, [LoggedExercise(id, id, 'chest', sets)]));+ List<(int, double)> opening(String id) {+ final r = fit.createRoutine('R');+ fit.toggleRoutineExercise(r, id);+ fit.startRoutine(fit.routines.firstWhere((x) => x.id == r));+ final out = [+ for (final s in fit.session!.exercises.single.sets.where((s) => s.kind != SetKind.warmup)) (s.reps, s.weight)+ ];+ fit.saveAndExit();+ return out;+ }++ void use(String id, ProgressRule r) => fit.setProgressRule(id, r);++ test('por defecto sigue siendo lineal y solo sugiere', () {+ final id = bench();+ expect(fit.progressRule(id).kind, ProgressKind.linear);+ expect(fit.hasProgress(id), isFalse);+ logged(id, 2, [LoggedSet(8, 60), LoggedSet(8, 60)]);+ expect(fit.nextTarget(id)!.weightKg, 62.5);+ expect(opening(id).first, (8, 60.0));+ });++ test('elegir una estrategia la deja aplicándose sola', () {+ final id = bench();+ use(id, const ProgressRule(kind: ProgressKind.double));+ expect(fit.hasProgress(id), isTrue);+ expect(fit.progressFor(id), 2.5);+ });++ test('manual: sin sugerencia y el peso tal cual', () {+ final id = bench();+ fit.toggleProgress(id);+ use(id, const ProgressRule(kind: ProgressKind.manual));+ logged(id, 2, [LoggedSet(8, 60), LoggedSet(8, 60)]);+ expect(fit.hasProgress(id), isFalse);+ expect(fit.nextTarget(id), isNull);+ expect(opening(id).first, (8, 60.0));+ });++ group('doble progresión 8–12', () {+ setUp(() => use(bench(), const ProgressRule(kind: ProgressKind.double, low: 8, high: 12)));++ test('sin llegar al tope: mismo peso y una repe más en cada serie', () {+ final id = bench();+ logged(id, 2, [LoggedSet(10, 26), LoggedSet(9, 26), LoggedSet(8, 26)]);+ final next = fit.nextTarget(id)!;+ expect(next.move, NextMove.reps);+ expect(next.weightKg, 26);+ expect(opening(id), [(11, 26.0), (10, 26.0), (9, 26.0)]);+ expect(fit.nextWhy(id), t.nextMoreReps);+ expect(fit.nextTargetLabel(id), '26 kg × 11/10/9');+ });++ test('las tres series a 12: sube el peso y vuelve a 8', () {+ final id = bench();+ logged(id, 2, [LoggedSet(12, 26), LoggedSet(12, 26), LoggedSet(12, 26)]);+ expect(fit.nextTarget(id)!.move, NextMove.up);+ expect(fit.nextTargetLabel(id), '28.5 kg × 8');+ expect(opening(id), [(8, 28.5), (8, 28.5), (8, 28.5)]);+ });++ test('nunca pide más del tope del rango', () {+ final id = bench();+ logged(id, 2, [LoggedSet(12, 26), LoggedSet(11, 26)]);+ expect(opening(id).take(2), [(12, 26.0), (12, 26.0)]);+ });++ test('estancado: sin sumar repes 3 veces seguidas, descarga', () {+ final id = bench();+ logged(id, 12, [LoggedSet(9, 60), LoggedSet(8, 60)]);+ for (final d in [9, 6, 3]) {+ logged(id, d, [LoggedSet(9, 60), LoggedSet(8, 60)]);+ }+ expect(fit.stallStreak(id), 3);+ final next = fit.nextTarget(id)!;+ expect(next.deload, isTrue);+ expect(next.weightKg, 55);+ expect(next.reps, 8);+ });++ test('si sumas repes no cuenta como estancado', () {+ final id = bench();+ logged(id, 9, [LoggedSet(8, 60), LoggedSet(8, 60)]);+ logged(id, 6, [LoggedSet(9, 60), LoggedSet(8, 60)]);+ logged(id, 3, [LoggedSet(9, 60), LoggedSet(9, 60)]);+ expect(fit.stallStreak(id), 0);+ });+ });++ group('repes, series y peso', () {+ setUp(() => use(bench(), const ProgressRule(kind: ProgressKind.volume, low: 8, high: 12, sets: 2, maxSets: 3)));++ test('al tope con menos series del máximo: una serie más, vuelta a 8', () {+ final id = bench();+ logged(id, 2, [LoggedSet(12, 40), LoggedSet(12, 40)]);+ expect(fit.nextTarget(id)!.move, NextMove.addSet);+ expect(fit.nextTargetLabel(id), '3 × 40 kg × 8');+ expect(opening(id), [(8, 40.0), (8, 40.0), (8, 40.0)]);+ });++ test('al tope con todas las series: más peso y vuelta a las series de partida', () {+ final id = bench();+ logged(id, 2, [LoggedSet(12, 40), LoggedSet(12, 40), LoggedSet(12, 40)]);+ expect(fit.nextTarget(id)!.move, NextMove.up);+ expect(opening(id), [(8, 42.5), (8, 42.5)]);+ });+ });++ group('última serie a tope', () {+ setUp(() => use(bench(), const ProgressRule(kind: ProgressKind.amrap)));++ test('elegirla descarga al primer fallo', () {+ expect(fit.progressRule(bench()).fails, 1);+ });++ test('cumplir sube un salto', () {+ final id = bench();+ logged(id, 2, [LoggedSet(5, 60), LoggedSet(5, 60), LoggedSet(7, 60)]);+ expect(fit.nextTarget(id)!.weightKg, 62.5);+ expect(opening(id), [(5, 62.5), (5, 62.5), (5, 62.5)]);+ expect(fit.nextWhy(id), t.nextAmrap);+ });++ test('doblar el objetivo en la última sube dos saltos', () {+ final id = bench();+ logged(id, 2, [LoggedSet(5, 60), LoggedSet(5, 60), LoggedSet(10, 60)]);+ expect(fit.nextTarget(id)!.weightKg, 65);+ });++ test('fallar descarga un 10 %', () {+ final id = bench();+ logged(id, 2, [LoggedSet(5, 60), LoggedSet(5, 60), LoggedSet(3, 60)]);+ final next = fit.nextTarget(id)!;+ expect(next.deload, isTrue);+ expect(next.weightKg, 55);+ });+ });++ test('la descarga usa el porcentaje y los fallos elegidos', () {+ final id = bench();+ fit.toggleProgress(id);+ use(id, fit.progressRule(id).copyWith(fails: 2, deloadPct: 20));+ logged(id, 6, [LoggedSet(8, 100), LoggedSet(6, 100)]);+ logged(id, 3, [LoggedSet(8, 100), LoggedSet(6, 100)]);+ expect(fit.nextTarget(id)!.weightKg, 80);+ });++ test('el rango no se cruza', () {+ const r = ProgressRule(kind: ProgressKind.double, low: 8, high: 12);+ expect(r.copyWith(low: 15).high, 16);+ expect(r.copyWith(high: 3).high, 9);+ expect(const ProgressRule(sets: 3, maxSets: 5).copyWith(sets: 6).maxSets, 7);+ });++ test('se guarda en la copia y se borra con los datos', () async {+ final id = bench();+ use(id, const ProgressRule(kind: ProgressKind.volume, low: 6, high: 10, sets: 2, maxSets: 4));+ fit.persistNow();+ await pumpEventQueue();+ fit.loadFromStore();+ final r = fit.progressRule(id);+ expect((r.kind, r.low, r.high, r.sets, r.maxSets), (ProgressKind.volume, 6, 10, 2, 4));+ fit.resetAllData();+ expect(fit.progressRule(id).kind, ProgressKind.linear);+ });+ });++ group('progresión automática', () {+ 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('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');+ });+ });+ });+}diff --git a/test/records_test.dart b/test/records_test.dartnew file mode 100644index 0000000..7c2d234--- /dev/null+++ b/test/records_test.dart@@ -0,0 +1,303 @@+import 'dart:convert';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.dart';+import 'package:gymmane/models/profile.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();++ group('mejor serie y mejor entreno', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ LoggedSession day(int ago, List<LoggedExercise> exs) =>+ LoggedSession(DateTime.now().subtract(Duration(days: ago)), 1800, exs);++ test('la mejor serie es la de más 1RM y el mejor entreno el de más volumen', () {+ final bench = idOf('Barbell Bench Press');+ fit.sessions.addAll([+ day(3, [LoggedExercise(bench, 'Bench', 'chest', [LoggedSet(13, 16), LoggedSet(5, 18)])]),+ day(1, [LoggedExercise(bench, 'Bench', 'chest', [LoggedSet(10, 17), LoggedSet(10, 17), LoggedSet(10, 17)])]),+ ]);++ final set = fit.bestSet(bench)!;+ expect((set.set.weight, set.set.reps), (16, 13));++ final work = fit.bestWorkout(bench, PrKind.weight)!;+ expect(work.score, 510);+ });++ test('en un ejercicio de repeticiones el mejor entreno suma repeticiones', () {+ final pull = idOf('Pull Up');+ fit.sessions.add(day(1, [LoggedExercise(pull, 'Pull', 'back', [LoggedSet(8, 0), LoggedSet(6, 0)])]));+ expect(fit.bestWorkout(pull, PrKind.reps)!.score, 14);+ expect(fit.bestSet(pull), isNull);+ });+ });++ group('#201 máquinas asistidas', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ DateTime ago(int days, [int hour = 18]) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day - days, hour);+ }++ void logged(String id, int days, List<LoggedSet> sets) =>+ fit.sessions.add(LoggedSession(ago(days), 1200, [LoggedExercise(id, id, 'back', sets)]));++ const pull = 'kiJ4Z2K';++ test('las dominadas asistidas vienen marcadas y se pueden desmarcar', () {+ expect(fit.isAssisted(pull), isTrue);+ expect(fit.isAssisted(fit.matchExerciseByName('Bench Press')!.id), isFalse);+ fit.toggleAssisted(pull);+ expect(fit.isAssisted(pull), isFalse);+ final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;+ fit.applyBackup(data);+ expect(fit.isAssisted(pull), isFalse);+ });++ test('el récord es la menor ayuda, no la mayor', () {+ logged(pull, 10, [LoggedSet(8, 40)]);+ logged(pull, 3, [LoggedSet(8, 35)]);+ final r = fit.exerciseRecord(pull)!;+ expect(r.best, 35);+ expect(fit.bestSet(pull)!.set.weight, 35);+ expect(fit.oneRmSeries(pull), [40, 35]);+ });++ test('con más reps y la misma ayuda también es mejor', () {+ logged(pull, 10, [LoggedSet(6, 35)]);+ logged(pull, 3, [LoggedSet(10, 35)]);+ expect(fit.bestSet(pull)!.set.reps, 10);+ });++ test('la sugerencia y los pesos de partida bajan la ayuda', () {+ fit.progressStep[pull] = 2.5;+ logged(pull, 3, [LoggedSet(8, 35), LoggedSet(8, 35)]);+ final next = fit.nextTarget(pull)!;+ expect(next.weightKg, 32.5);+ expect(next.up, isTrue);+ final r = fit.createRoutine('Espalda');+ fit.toggleRoutineExercise(r, pull);+ fit.startRoutine(fit.routines.single);+ expect(fit.session!.exercises.single.sets.where((s) => s.kind != SetKind.warmup).first.weight, 32.5);+ fit.saveAndExit();+ });++ test('la ayuda nunca baja de cero y no hay objetivo de peso', () {+ fit.progressStep[pull] = 5;+ logged(pull, 3, [LoggedSet(8, 2.5)]);+ expect(fit.nextTarget(pull)!.weightKg, 0);+ expect(fit.goalFits(pull), isFalse);+ expect(fit.bestLift(pull), 0);+ });+ });++ group('fuerza relativa', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ setAppLanguage('en');+ });++ void lift(String name, int reps, double kg) {+ final ex = fit.matchExerciseByName(name)!;+ fit.sessions.add(LoggedSession(DateTime.now().subtract(const Duration(days: 2)), 1800,+ [LoggedExercise(ex.id, ex.name, ex.primary, [LoggedSet(reps, kg)])]));+ }++ test('press banca a 1,0× el peso es intermedio en hombre y muy avanzado en mujer', () {+ fit.profile = Profile(weightKg: 80);+ lift('Barbell Bench Press', 1, 80);+ final id = fit.matchExerciseByName('Barbell Bench Press')!.id;+ final rel = fit.relativeStrength(id)!;+ expect(rel.ratio, closeTo(1.03, 0.01));+ expect(rel.level, 1);+ fit.profile = Profile(weightKg: 80, sex: 'female');+ expect(fit.relativeStrength(id)!.level, 3);+ });++ test('solo para los básicos y con marcas de los últimos 90 días', () {+ lift('Dumbbell Biceps Curl', 10, 15);+ expect(fit.relativeStrength(fit.matchExerciseByName('Dumbbell Biceps Curl')!.id), isNull);+ final ex = fit.matchExerciseByName('Barbell Deadlift')!;+ fit.sessions.add(LoggedSession(DateTime.now().subtract(const Duration(days: 200)), 1800,+ [LoggedExercise(ex.id, ex.name, ex.primary, [LoggedSet(5, 140)])]));+ expect(fit.relativeStrength(ex.id), isNull);+ });+ });++ group('#104 récords sin peso', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ LoggedSession logged(DateTime at, List<LoggedSet> sets, {String id = 'push', String primary = 'chest'}) =>+ LoggedSession(at, 600, [LoggedExercise(id, id, primary, sets)]);++ test('peso corporal: el récord son las repeticiones', () {+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(15, 0), LoggedSet(22, 0)]));+ final pr = fit.personalRecords.single;+ expect(pr.kind, PrKind.reps);+ expect(pr.best, 22);+ });++ test('isométrico: el récord es el tiempo', () {+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(0, 0, sec: 45), LoggedSet(0, 0, sec: 70)]));+ final pr = fit.personalRecords.single;+ expect(pr.kind, PrKind.time);+ expect(fit.recordLabel(pr), isNot(contains('kg')));+ });++ test('con peso manda el peso y va primero en la lista', () {+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(30, 0)], id: 'dips'));+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 100)], id: 'bench'));+ expect(fit.personalRecords.map((r) => r.id), ['bench', 'dips']);+ expect(fit.personalRecords.first.kind, PrKind.weight);+ });+ });++ group('#127 ideas de FitNotes', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ const bench = 'EIeI8Vf';++ LoggedSession logged(DateTime at, List<LoggedSet> sets, {String id = bench}) =>+ LoggedSession(at, 1800, [LoggedExercise(id, 'Barbell Bench Press', 'chest', sets)]);++ test('el objetivo mide el mejor peso y se guarda con su fecha', () {+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 100), LoggedSet(3, 110)]));+ final due = DateTime.now().add(const Duration(days: 30));+ fit.setExerciseGoal(bench, 140, due);+ expect(fit.goalBest(bench), 110);+ fit.persistNow();+ fit.loadFromStore();+ final g = fit.exerciseGoals[bench]!;+ expect(g.target, 140);+ expect((g.due!.year, g.due!.month, g.due!.day), (due.year, due.month, due.day));+ fit.clearExerciseGoal(bench);+ expect(fit.exerciseGoals, isEmpty);+ });++ test('el objetivo de un ejercicio sin peso va en repeticiones', () {+ fit.sessions.add(logged(DateTime.now(), [LoggedSet(12, 0)], id: 'I4hDWkc'));+ expect(fit.goalKind('I4hDWkc'), PrKind.reps);+ expect(fit.goalBest('I4hDWkc'), 12);+ });++ test('el entreno se copia como texto con sus series y totales', () {+ final s = logged(DateTime(2026, 9, 29, 18), [LoggedSet(8, 60), LoggedSet(6, 70)]);+ final text = fit.workoutText(s);+ expect(text, contains('60 kg × 8'));+ expect(text, contains('70 kg × 6'));+ expect(text, contains('30 min'));+ expect(text.split('\n').last, contains('14'));+ });++ test('el porcentaje del máximo da un peso que se puede cargar', () {+ fit.bumpRmWeight(100 - fit.rmWeight);+ fit.bumpRmReps(1 - fit.rmReps);+ fit.bumpRmPct(72 - fit.rmPct);+ final w = fit.rmAtPct;+ expect((w - 72.6).abs(), lessThan(2.6));+ expect(w % 1.25, closeTo(0, 1e-9));+ });+ });++ group('finish screen tells the truth', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ void logSession(String exId, double kg) {+ fit.sessions.add(LoggedSession(DateTime.now().subtract(const Duration(days: 3)), 600,+ [LoggedExercise(exId, 'X', 'chest', [LoggedSet(5, kg)])]));+ }++ void doWorkout(double kg) {+ fit.startWorkout();+ fit.toggleMuscle('chest');+ fit.trainContinue();+ fit.startSession();+ fit.setSessionWeight(0, 0, kg);+ fit.setSessionReps(0, 0, 5);+ fit.toggleSet(0, 0);+ fit.finishSession();+ }++ test('a real PR is counted; a lighter day is not', () {+ final id = fit.allExercises.firstWhere((e) => e.primary == 'chest').id;+ logSession(id, 60);++ doWorkout(80);+ expect(fit.summaryPrs, 1);+ fit.saveAndExit();++ doWorkout(50);+ expect(fit.summaryPrs, 0, reason: 'se compara con TODO lo anterior, no con la última vez');+ fit.saveAndExit();+ });++ test('the headline changes with what actually happened', () {+ expect(t.finishHeadline(prs: 1, streak: 0, goalHit: false),+ isNot(t.finishHeadline(prs: 0, streak: 0, goalHit: false)));+ expect(t.finishHeadline(prs: 0, streak: 0, goalHit: true),+ isNot(t.finishHeadline(prs: 0, streak: 0, goalHit: false)));+ setAppLanguage('es');+ expect(t.finishHeadline(prs: 2, streak: 0, goalHit: false), 'Récord personal nuevo');+ expect(t.finishBody(prs: 2, streak: 0, goalHit: false), contains('2 ejercicios'));+ expect(t.finishBody(prs: 1, streak: 0, goalHit: false), contains('un ejercicio'));+ });++ test('nothing logged means no fake celebration', () {+ fit.startWorkout();+ fit.toggleMuscle('chest');+ fit.trainContinue();+ fit.startSession();+ fit.finishSession();+ expect(fit.summaryPrs, 0);+ expect(fit.summaryVsLast, isNull);+ fit.saveAndExit();+ });+ });+}diff --git a/test/reddit_requests_test.dart b/test/reddit_requests_test.dartdeleted file mode 100644index 166ad1b..0000000--- a/test/reddit_requests_test.dart+++ /dev/null@@ -1,470 +0,0 @@-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('la Recommended Routine es una sola rutina puesta lunes, miércoles y viernes', () {- final made = fit.applyTemplate(kProgramTemplates.firstWhere((x) => x.id == 'rr'));- expect(made, 1);- final id = fit.routinesInGroup('Recommended Routine').single.id;- expect(fit.weeklyPlan, {1: id, 3: id, 5: id});- });-- 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('Copy');- 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/requests_06oct_test.dart b/test/requests_06oct_test.dartdeleted file mode 100644index 47f6a66..0000000--- a/test/requests_06oct_test.dart+++ /dev/null@@ -1,120 +0,0 @@-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.resetAllData();- fit.setUnits('kg');- });-- tearDown(() {- if (fit.session != null) fit.saveAndExit();- });-- String idOf(String name) => fit.matchExerciseByName(name)!.id;-- LoggedSession day(int ago, List<LoggedExercise> exs) =>- LoggedSession(DateTime.now().subtract(Duration(days: ago)), 1800, exs);-- group('salto de peso', () {- test('los botones suman el salto elegido', () {- final bench = idOf('Barbell Bench Press');- fit.sessionPicks- ..clear()- ..add(bench);- fit.startSession();- fit.setSessionWeight(0, 0, 60);-- fit.setWeightStep(2);- fit.bumpSessionWeight(0, 0, 1);- expect(fit.session!.exercises[0].sets[0].weight, 62);- });-- test('kg y lb guardan su propio salto y uno raro no entra', () {- fit.setWeightStep(1);- fit.setWeightStep(3);- expect(fit.weightStep, 1);-- fit.setUnits('lb');- expect(fit.weightStep, 5);- fit.setWeightStep(10);- expect(fit.weightStep, 10);-- fit.setUnits('kg');- expect(fit.weightStep, 1);- expect(fit.toJson()['stepKg'], 1);- expect(fit.toJson()['stepLb'], 10);- });-- test('los calentamientos siguen redondeando a discos', () {- fit.setWeightStep(1);- expect(fit.plateStep, 2.5);- });- });-- group('mejor serie y mejor entreno', () {- test('la mejor serie es la de más 1RM y el mejor entreno el de más volumen', () {- final bench = idOf('Barbell Bench Press');- fit.sessions.addAll([- day(3, [LoggedExercise(bench, 'Bench', 'chest', [LoggedSet(13, 16), LoggedSet(5, 18)])]),- day(1, [LoggedExercise(bench, 'Bench', 'chest', [LoggedSet(10, 17), LoggedSet(10, 17), LoggedSet(10, 17)])]),- ]);-- final set = fit.bestSet(bench)!;- expect((set.set.weight, set.set.reps), (16, 13));-- final work = fit.bestWorkout(bench, PrKind.weight)!;- expect(work.score, 510);- });-- test('en un ejercicio de repeticiones el mejor entreno suma repeticiones', () {- final pull = idOf('Pull Up');- fit.sessions.add(day(1, [LoggedExercise(pull, 'Pull', 'back', [LoggedSet(8, 0), LoggedSet(6, 0)])]));- expect(fit.bestWorkout(pull, PrKind.reps)!.score, 14);- expect(fit.bestSet(pull), isNull);- });- });-- group('fusionar ejercicios', () {- test('el historial pasa al otro y el propio se queda en la biblioteca', () {- final mine = fit.addCustomExercise(name: 'Mi press', primary: 'chest', equipment: 'Barbell');- final bench = idOf('Barbell Bench Press');- fit.sessions.addAll([- day(2, [LoggedExercise(mine, 'Mi press', 'chest', [LoggedSet(10, 50)])]),- day(1, [- LoggedExercise(bench, 'Bench', 'chest', [LoggedSet(8, 60)]),- LoggedExercise(mine, 'Mi press', 'chest', [LoggedSet(6, 70)]),- ]),- ]);-- fit.mergeExerciseInto(mine, bench);-- expect(fit.exerciseHistory(mine), isEmpty);- expect(fit.exerciseHistory(bench), hasLength(2));- expect(fit.sessions[1].exercises, hasLength(1), reason: 'el mismo día se juntan las series');- expect(fit.sessions[1].exercises.single.sets.map((s) => s.reps), [8, 6]);- expect(fit.exerciseById(mine), isNotNull);- });-- test('solo se fusiona un ejercicio propio con otro del mismo tipo', () {- final bench = idOf('Barbell Bench Press');- final squat = idOf('Barbell Squat');- fit.sessions.add(day(1, [LoggedExercise(bench, 'Bench', 'chest', [LoggedSet(8, 60)])]));- fit.mergeExerciseInto(bench, squat);- expect(fit.exerciseHistory(bench), hasLength(1));-- final run = fit.addCustomExercise(name: 'Mi carrera', primary: 'quads', equipment: 'Bodyweight', mode: 'cardio');- expect(fit.mergeTargets(run).every((e) => fit.modeOf(e.id) == 'cardio'), isTrue);- fit.sessions.add(day(2, [LoggedExercise(run, 'Run', 'quads', [LoggedSet(0, 0, sec: 600)])]));- fit.mergeExerciseInto(run, bench);- expect(fit.exerciseHistory(run), hasLength(1));- });- });-}diff --git a/test/requests_08oct_test.dart b/test/requests_08oct_test.dartdeleted file mode 100644index db15e5d..0000000--- a/test/requests_08oct_test.dart+++ /dev/null@@ -1,128 +0,0 @@-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();-- late List<String> ids;-- setUp(() async {- SharedPreferences.setMockInitialValues({});- await Store.instance.init();- fit.resetAllData();- fit.onboarded = true;- ids = fit.allExercises.take(6).map((e) => e.id).toList();- });-- tearDown(() {- if (fit.session != null) fit.saveAndExit();- });-- String routineWith(String name, List<String> exs) {- final r = fit.createRoutine(name);- for (final id in exs) {- fit.toggleRoutineExercise(r, id);- }- return r;- }-- LoggedSession done(String routineId, int ago) => LoggedSession(- DateTime.now().subtract(Duration(days: ago)),- 1800,- [LoggedExercise(ids[0], 'x', 'chest', [LoggedSet(8, 60)])],- routineId: routineId,- );-- group('#177 saltar dentro de una superserie', () {- void finish(int exIdx) {- for (final st in fit.session!.exercises[exIdx].sets) {- st.done = true;- }- }-- test('la flecha sale de la cadena como al completar la serie', () {- routineWith('Cadena', ids);- fit.startRoutine(fit.routines.single);- final s = fit.session!;- for (var i = 0; i < 4; i++) {- s.exercises[i].linkedNext = true;- }- for (final i in [0, 1, 3, 4]) {- finish(i);- }- s.currentIndex = 2;-- fit.nextExercise();- expect(s.currentIndex, 5);- });-- test('dentro de la cadena va al siguiente que aún tiene series', () {- routineWith('Cadena', ids);- fit.startRoutine(fit.routines.single);- final s = fit.session!;- for (var i = 0; i < 4; i++) {- s.exercises[i].linkedNext = true;- }- finish(1);- s.currentIndex = 0;-- fit.nextExercise();- expect(s.currentIndex, 2);- });-- test('fuera de una cadena sigue yendo al siguiente de la lista', () {- routineWith('Suelta', ids.take(3).toList());- fit.startRoutine(fit.routines.single);- fit.nextExercise();- expect(fit.session!.currentIndex, 1);- });- });-- group('#174 rutina de hoy hecha', () {- test('tras hacerla no queda nada pendiente hoy', () {- final r = routineWith('Básica', ids.take(2).toList());- fit.weeklyPlan[DateTime.now().weekday] = r;- expect(fit.pendingRoutinesOn(DateTime.now()).map((e) => e.id), [r]);-- fit.sessions.add(done(r, 0));- expect(fit.pendingRoutinesOn(DateTime.now()), isEmpty);- expect(fit.todayRoutine?.id, r);- });- });-- group('#176 rutinas en inicio', () {- test('la última hecha va primero y las nunca hechas al final en su orden', () {- final a = routineWith('A', [ids[0]]);- final b = routineWith('B', [ids[1]]);- final c = routineWith('C', [ids[2]]);- final d = routineWith('D', [ids[3]]);- fit.sessions.addAll([done(a, 5), done(c, 1), done(a, 9)]);-- expect(fit.routinesByLastDone.map((r) => r.id), [c, a, b, d]);- expect(fit.lastDoneOf(b), isNull);- });- });-- group('#175 ajustes de inicio', () {- test('las dos tarjetas se pueden quitar y se recuerdan', () async {- expect(fit.showWeekStats, isTrue);- expect(fit.showRoutineRow, isTrue);- fit.toggleWeekStats();- fit.toggleRoutineRow();- fit.persistNow();- fit.loadFromStore();- expect(fit.showWeekStats, isFalse);- expect(fit.showRoutineRow, isFalse);- });-- test('las series de la tarjeta semanal son las de la semana', () {- fit.sessions.add(LoggedSession(DateTime.now(), 600, [- LoggedExercise(ids[0], 'x', 'chest', [LoggedSet(8, 60), LoggedSet(8, 60)]),- ]));- expect(fit.weekSetCount, 2);- });- });-}diff --git a/test/requests_10oct_test.dart b/test/requests_10oct_test.dartdeleted file mode 100644index d8e6a4b..0000000--- a/test/requests_10oct_test.dart+++ /dev/null@@ -1,122 +0,0 @@-import 'package:flutter/material.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/catalog/exercise_catalog.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.onboarded = true;- });-- group('#179 filtro de trapecio', () {- test('trapecio, antebrazo y oblicuos salen en el filtro y encuentran ejercicios', () {- for (final m in ['trapezius', 'forearm', 'obliques']) {- expect(kFilterMuscles, contains(m));- fit.setMuscleFilter(m);- expect(fit.exercisesFiltered, isNotEmpty, reason: m);- expect(- fit.exercisesFiltered.every((e) => e.primary == m || e.secondary.contains(m)), isTrue);- fit.setMuscleFilter(m);- }- });- });-- group('#183 ejercicio por tiempo sin peso', () {- test('uno propio por tiempo con barra empieza sin peso', () {- final id = fit.addCustomExercise(- name: 'Sweep', primary: 'abdomen', equipment: 'Barbell', mode: 'time');- expect(fit.isRepsOnly(id), isTrue);- });-- test('si ya lo hizo con peso, el peso sigue', () {- final id = fit.addCustomExercise(- name: 'Sweep', primary: 'abdomen', equipment: 'Barbell', mode: 'time');- fit.sessions.add(LoggedSession(DateTime.now(), 600, [- LoggedExercise(id, 'Sweep', 'abdomen', [LoggedSet(0, 10, sec: 30)]),- ]));- expect(fit.isRepsOnly(id), isFalse);- });-- test('se puede volver a poner el peso', () {- final id = fit.addCustomExercise(- name: 'Sweep', primary: 'abdomen', equipment: 'Barbell', mode: 'time');- fit.toggleRepsOnly(id);- expect(fit.isRepsOnly(id), isFalse);- });-- test('los de carga siguen con peso y los de reps no cambian', () {- expect(fit.isRepsOnly('kettlebell-farmer-carry'), isFalse);- expect(fit.isRepsOnly('cable-pallof-hold'), isFalse);- expect(fit.isRepsOnly('jump-rope'), isTrue);- final barbell = fit.allExercises.firstWhere((e) => e.equipment == 'Barbell' && fit.modeOf(e.id).isEmpty);- expect(fit.isRepsOnly(barbell.id), isFalse);- });- });-- group('#180 duración de la sesión', () {- test('se corrige y se guarda', () {- final s = LoggedSession(DateTime.now(), 108 * 60, [- LoggedExercise('x', 'x', 'chest', [LoggedSet(8, 60)]),- ]);- fit.sessions.add(s);- fit.setSessionDuration(s, 45 * 60);- expect(fit.daySummary(DateTime.now())!.durationSec, 45 * 60);- fit.persistNow();- fit.loadFromStore();- expect(fit.sessions.single.durationSec, 45 * 60);- });- });-- group('#181 negro AMOLED', () {- test('es un tema oscuro aparte y se recuerda', () {- fit.setThemePref('amoled');- expect(fit.dark, isTrue);- expect(fit.themeMode, ThemeMode.dark);- fit.persistNow();- fit.loadFromStore();- expect(fit.themePref, 'amoled');- fit.setThemePref('dark');- expect(fit.themePref, 'dark');- });- });-- group('#167 músculos secundarios', () {- test('se cambian en un ejercicio de la app, se guardan y se pueden restablecer', () {- final ex = fit.allExercises.firstWhere((e) => e.secondary.length == 1 && e.primary == 'chest');- final before = [...ex.secondary];- fit.setSecondary(ex.id, [...before, 'shoulders']);- expect(fit.exerciseById(ex.id)!.secondary, containsAll([...before, 'shoulders']));- fit.setMuscleFilter('shoulders');- expect(fit.exercisesFiltered.map((e) => e.id), contains(ex.id));- fit.setMuscleFilter('shoulders');- fit.persistNow();- fit.loadFromStore();- expect(fit.exerciseById(ex.id)!.secondary, contains('shoulders'));- fit.resetSecondary(ex.id);- expect(fit.exerciseById(ex.id)!.secondary, before);- expect(fit.hasSecondaryOverride(ex.id), isFalse);- });-- test('volver a lo de siempre no deja nada guardado y el primario no cuenta', () {- final ex = fit.allExercises.firstWhere((e) => e.secondary.isNotEmpty);- fit.setSecondary(ex.id, [...ex.secondary, ex.primary]);- expect(fit.hasSecondaryOverride(ex.id), isFalse);- expect(fit.exerciseById(ex.id)!.secondary, isNot(contains(ex.primary)));- });-- test('en uno propio cambia el ejercicio', () {- final id = fit.addCustomExercise(name: 'Mío', primary: 'chest', equipment: 'Dumbbell');- fit.setSecondary(id, ['triceps']);- expect(fit.exerciseById(id)!.secondary, ['triceps']);- expect(fit.hasSecondaryOverride(id), isFalse);- });- });-}diff --git a/test/requests_11oct_test.dart b/test/requests_11oct_test.dartdeleted file mode 100644index 9f347e6..0000000--- a/test/requests_11oct_test.dart+++ /dev/null@@ -1,130 +0,0 @@-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.resetAllData();- fit.onboarded = true;- });-- Routine routineOf(List<String> ids) {- final id = fit.createRoutine('Cardio');- for (final ex in ids) {- fit.toggleRoutineExercise(id, ex);- }- return fit.routines.firstWhere((r) => r.id == id);- }-- group('#173 cardio', () {- test('el filtro rápido de cardio solo deja cardio y no cuenta como filtro de la hoja', () {- fit.setKindFilter('cardio');- final list = fit.exercisesFiltered;- expect(list, isNotEmpty);- expect(list.every((e) => fit.kindOf(e) == 'cardio'), isTrue);- expect(list.map((e) => e.id), containsAll(['running', 'jump-rope']));- fit.setKindFilter('cardio');- expect(fit.exKindFilter, isNull);- });-- test('las series de cardio llevan reloj y las de peso no', () {- expect(fit.runsClock('running'), isTrue);- expect(fit.runsClock('cable-pallof-hold'), fit.isTimed('cable-pallof-hold'));- final barbell = fit.allExercises.firstWhere((e) => fit.modeOf(e.id).isEmpty);- expect(fit.runsClock(barbell.id), isFalse);- });-- test('una carrera larga no se corta a la hora', () {- fit.startRoutine(routineOf(['running']));- fit.endCountdown();- fit.session!.exercises.first.sets.first.sec = 90 * 60;- fit.startHold(0, 0);- expect(fit.holdTotal, 90 * 60);- fit.stopHold();- });-- test('terminar antes guarda el tiempo que se ha corrido', () {- fit.startRoutine(routineOf(['running']));- fit.endCountdown();- fit.session!.exercises.first.sets.first.sec = 1200;- fit.startHold(0, 0);- final start = DateTime.now().subtract(const Duration(seconds: 300));- fit.holdStartsAt = start;- fit.holdEndsAt = start.add(const Duration(seconds: 1200));- fit.toggleHoldPause();- fit.completeHold();- final set = fit.session!.exercises.first.sets.first;- expect(set.done, isTrue);- expect(set.sec, inInclusiveRange(299, 301));- });-- test('un aguante terminado antes sigue guardando lo planeado', () {- final plank = fit.matchExerciseByName('Plank')!.id;- fit.startRoutine(routineOf([plank]));- fit.endCountdown();- fit.setExerciseMode(plank, 'time');- final planned = fit.session!.exercises.first.sets.first.sec;- fit.startHold(0, 0);- final start = DateTime.now().subtract(const Duration(seconds: 10));- fit.holdStartsAt = start;- fit.holdEndsAt = start.add(Duration(seconds: fit.holdTotal));- fit.toggleHoldPause();- fit.completeHold();- expect(fit.session!.exercises.first.sets.first.sec, planned);- });- });-- group('#160 nombre del entreno libre', () {- LoggedSession finishFree() {- fit.startRoutine(routineOf(['running']));- fit.endCountdown();- fit.session!.routineId = null;- fit.toggleSet(0, 0);- fit.finishSession();- return fit.filedSession!;- }-- test('se le pone nombre al acabar y se guarda', () {- final s = finishFree();- expect(fit.sessionTitle(s), isNull);- fit.renameSession(s, ' Pierna ');- expect(s.name, 'Pierna');- expect(fit.sessionTitle(s), 'Pierna');- expect(LoggedSession.fromJson(s.toJson()).name, 'Pierna');- expect(fit.workoutText(s).split('\n').first, 'Pierna');- });-- test('seguir entrenando y volver a acabar no pierde el nombre', () {- final s = finishFree();- fit.renameSession(s, 'Torso');- fit.continueSession();- expect(fit.session!.name, 'Torso');- fit.finishSession();- expect(fit.filedSession!.name, 'Torso');- });-- test('reabrir un entreno guardado conserva el nombre', () {- final s = finishFree();- fit.renameSession(s, 'Brazos');- fit.saveAndExit();- fit.resumeLoggedSession(fit.sessions.last);- expect(fit.session!.name, 'Brazos');- });-- test('las de rutina se titulan con la rutina si no se renombran', () {- final r = routineOf(['running']);- fit.renameRoutine(r.id, 'Cardio suave');- fit.startRoutine(fit.routines.firstWhere((x) => x.id == r.id));- fit.endCountdown();- fit.toggleSet(0, 0);- fit.finishSession();- expect(fit.sessionTitle(fit.filedSession!), 'Cardio suave');- });- });-}diff --git a/test/requests_12oct_test.dart b/test/requests_12oct_test.dartdeleted file mode 100644index e0cf20c..0000000--- a/test/requests_12oct_test.dart+++ /dev/null@@ -1,38 +0,0 @@-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.resetAllData();- fit.setUnits('kg');- });-- LoggedSession at(int daysAgo, List<LoggedSet> sets) => LoggedSession(- shiftDays(DateTime.now(), -daysAgo).add(const Duration(hours: 18)),- 600,- [LoggedExercise('push', 'push', 'chest', sets)],- );-- test('#187 el mapa reparte los tonos por volumen y el día sin peso queda abajo', () {- fit.sessions- ..add(at(4, [LoggedSet(10, 0), LoggedSet(10, 0)]))- ..add(at(3, [LoggedSet(10, 30)]))- ..add(at(2, [for (var i = 0; i < 6; i++) LoggedSet(10, 60)]))- ..add(at(1, [for (var i = 0; i < 12; i++) LoggedSet(8, 100)]));- final l = fit.heatmapLevels;- final n = l.length;- expect(l[n - 5], 1);- expect(l[n - 4], 1);- expect(l[n - 3], greaterThan(1));- expect(l[n - 2], heatLevels);- expect(l[n - 3], lessThan(l[n - 2]));- expect(l.last, 0);- });-}diff --git a/test/requests_17oct_test.dart b/test/requests_17oct_test.dartdeleted file mode 100644index cbcb6ac..0000000--- a/test/requests_17oct_test.dart+++ /dev/null@@ -1,153 +0,0 @@-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.resetAllData();- fit.onboarded = true;- });-- Routine routineOf(List<String> ids) {- final id = fit.createRoutine('Core');- for (final ex in ids) {- fit.toggleRoutineExercise(id, ex);- }- return fit.routines.firstWhere((r) => r.id == id);- }-- Future<void> endSide() async {- final past = DateTime.now().subtract(const Duration(milliseconds: 50));- fit.holdStartsAt = past.subtract(Duration(seconds: fit.holdTotal));- fit.holdEndsAt = past;- await Future<void>.delayed(const Duration(milliseconds: 300));- }-- group('#213 cada lado', () {- test('la plancha lateral viene por lados y se puede quitar y volver a poner', () async {- expect(fit.isEachSide('side-plank-hold'), isTrue);- expect(fit.isEachSide('plank-hold'), isFalse);- fit.toggleEachSide('side-plank-hold');- fit.toggleEachSide('plank-hold');- expect(fit.isEachSide('side-plank-hold'), isFalse);- expect(fit.isEachSide('plank-hold'), isTrue);-- fit.persistNow();- fit.eachSide.clear();- fit.eachSideOff.clear();- fit.loadFromStore();- expect(fit.isEachSide('side-plank-hold'), isFalse);- expect(fit.isEachSide('plank-hold'), isTrue);-- fit.toggleEachSide('side-plank-hold');- expect(fit.eachSideOff, isNot(contains('side-plank-hold')));- expect(fit.eachSide, isNot(contains('side-plank-hold')));- });-- test('solo cuenta en ejercicios por tiempo', () {- fit.setExerciseMode('side-plank-hold', 'weight');- expect(fit.isEachSide('side-plank-hold'), isFalse);- fit.setExerciseMode('side-plank-hold', 'time');- expect(fit.isEachSide('side-plank-hold'), isTrue);- });-- test('corre un lado, avisa de cambiar y descansa solo tras el segundo', () async {- fit.startRoutine(routineOf(['side-plank-hold']));- fit.endCountdown();- final set = fit.session!.exercises.first.sets.first;- fit.startHold(0, 0);- expect(fit.holdSides, 2);- expect(fit.holdLength('side-plank-hold', 30), '0:30 × 2');-- await endSide();- expect(fit.holding, isTrue);- expect(fit.holdSide, 1);- expect(fit.switchingSides, isTrue);- expect(set.done, isFalse);- expect(fit.session!.restRemaining, isNull);-- await endSide();- expect(fit.holding, isFalse);- expect(set.done, isTrue);- expect(fit.session!.restRemaining, isNotNull);- fit.skipRest();- });-- test('un aguante normal sigue siendo de una vez', () async {- fit.startRoutine(routineOf(['plank-hold']));- fit.endCountdown();- fit.startHold(0, 0);- expect(fit.holdSides, 1);- await endSide();- expect(fit.holding, isFalse);- expect(fit.session!.exercises.first.sets.first.done, isTrue);- fit.skipRest();- });-- test('pararlo deja todo como al principio', () {- fit.startRoutine(routineOf(['side-plank-hold']));- fit.endCountdown();- fit.startHold(0, 0);- fit.stopHold();- expect(fit.holdSide, 0);- expect(fit.holdSides, 1);- expect(fit.session!.exercises.first.sets.first.done, isFalse);- });- });-- group('#204 descanso a mano', () {- void rest() {- final bench = fit.matchExerciseByName('Bench Press')!.id;- fit.startRoutine(routineOf([bench]));- fit.endCountdown();- fit.toggleSet(0, 0);- expect(fit.session!.restRemaining, isNotNull);- }-- test('fija el descanso al tiempo elegido', () {- rest();- fit.setRest(200);- expect(fit.restTotal, 200);- expect(fit.session!.restRemaining, inInclusiveRange(199, 200));- fit.skipRest();- });-- test('cero lo salta y el tope es de diez minutos', () {- rest();- fit.setRest(5000);- expect(fit.session!.restRemaining, inInclusiveRange(599, 600));- fit.setRest(0);- expect(fit.session!.restRemaining, isNull);- });-- test('con la sesión en pausa se queda congelado en el tiempo nuevo', () {- rest();- fit.toggleSessionPause();- fit.setRest(90);- expect(fit.session!.restFrozen, 90);- expect(fit.session!.restRemaining, 90);- fit.toggleSessionPause();- expect(fit.session!.restRemaining, inInclusiveRange(89, 90));- fit.skipRest();- });- });-- group('#206 fotos tapadas en Progreso', () {- test('se recuerda al reiniciar', () {- expect(fit.hideShots, isFalse);- fit.toggleHideShots();- fit.persistNow();- fit.hideShots = false;- fit.loadFromStore();- expect(fit.hideShots, isTrue);- fit.resetAllData();- expect(fit.hideShots, isFalse);- });- });-}diff --git a/test/requests_18oct_test.dart b/test/requests_18oct_test.dartdeleted file mode 100644index 044a373..0000000--- a/test/requests_18oct_test.dart+++ /dev/null@@ -1,215 +0,0 @@-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/models/nutrition.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.onboarded = true;- });-- String bench() => fit.matchExerciseByName('Bench Press')!.id;-- Routine routine(String name) {- final id = fit.createRoutine(name);- fit.toggleRoutineExercise(id, bench());- return fit.routines.firstWhere((r) => r.id == id);- }-- void train(Routine r, {DateTime? on}) {- fit.startRoutine(r, on: on);- fit.endCountdown();- fit.toggleSet(0, 0);- fit.finishSession();- }-- DateTime day(int offset) {- final n = DateTime.now();- return DateTime(n.year, n.month, n.day + offset, 10);- }-- group('rotación', () {- test('la siguiente es la que sigue a la última, sin mirar el día', () {- final a = routine('A'), b = routine('B'), c = routine('C');- fit.setRotation(true);- for (final r in [a, b, c]) {- fit.toggleRotationRoutine(r.id);- }- expect(fit.rotating, isTrue);- expect(fit.todayRoutine?.id, a.id);- expect(fit.routinesOn(day(3)).single.id, a.id);-- train(a);- expect(fit.rotationNext?.id, b.id);- expect(fit.rotationStep, 1);- expect(fit.todayPlanDone, isTrue);- expect(fit.routinesOn(day(1)).single.id, b.id);-- fit.skipRotation();- expect(fit.rotationNext?.id, c.id);- fit.restartRotation();- expect(fit.rotationNext?.id, a.id);- });-- test('al terminar la última vuelve a la primera', () {- final a = routine('A'), b = routine('B');- fit.setRotation(true);- fit.toggleRotationRoutine(a.id);- fit.toggleRotationRoutine(b.id);- fit.setRotationNext(b.id);- train(b);- expect(fit.rotationNext?.id, a.id);- expect(fit.rotationStep, 0);- });-- test('se guarda, y borrar una rutina pasa a la siguiente', () {- final a = routine('A'), b = routine('B'), c = routine('C');- fit.setRotation(true);- for (final r in [a, b, c]) {- fit.toggleRotationRoutine(r.id);- }- fit.setRotationNext(b.id);- fit.reorderRotation(2, 0);- expect(fit.rotationIds, [c.id, a.id, b.id]);-- fit.persistNow();- fit.rotationIds.clear();- fit.rotation = false;- fit.loadFromStore();- expect(fit.rotating, isTrue);- expect(fit.rotationIds, [c.id, a.id, b.id]);- expect(fit.rotationNext?.id, b.id);-- fit.deleteRoutine(b.id);- expect(fit.rotationIds, [c.id, a.id]);- expect(fit.rotationNext?.id, c.id);- });-- test('al encenderla se llena con el plan semanal y al apagarla vuelve la semana', () {- final a = routine('A'), b = routine('B');- fit.assignRoutineToDay(DateTime.monday, a.id);- fit.assignRoutineToDay(DateTime.thursday, b.id);- fit.setRotation(true);- expect(fit.rotationIds, [a.id, b.id]);- fit.setRotation(false);- expect(fit.weeklyPlan[DateTime.monday], a.id);- expect(fit.weeklyPlan[DateTime.thursday], b.id);- });- });-- group('mover la sesión de hoy', () {- test('pasa a otro día sin tocar el plan semanal y se deshace', () {- final a = routine('A');- final today = DateTime.now();- fit.assignRoutineToDay(today.weekday, a.id);- final undo = fit.moveRoutineDay(a.id, today, day(2));- expect(undo, isNotNull);- expect(fit.routinesOn(today), isEmpty);- expect(fit.routinesOn(day(2)).single.id, a.id);- expect(fit.weeklyPlan[today.weekday], a.id);- expect(fit.movedOn(today), isTrue);- expect(fit.isTrainingDay(today), isFalse);-- fit.persistNow();- fit.planMoves.clear();- fit.loadFromStore();- expect(fit.routinesOn(day(2)).single.id, a.id);-- undo!();- expect(fit.routinesOn(today).single.id, a.id);- expect(fit.movedOn(day(2)), isFalse);- });-- test('volver al plan quita el cambio de ese día', () {- final a = routine('A');- final today = DateTime.now();- fit.assignRoutineToDay(today.weekday, a.id);- fit.moveRoutineDay(a.id, today, day(1));- fit.undoMoves(today);- expect(fit.routinesOn(today).single.id, a.id);- });- });-- group('músculos sin entrenar', () {- test('cuenta los días desde la última serie del músculo principal', () {- final now = DateTime.now();- fit.sessions.add(LoggedSession(now.subtract(const Duration(days: 9)), 600, [- LoggedExercise(bench(), 'Bench Press', 'chest', [LoggedSet(8, 60)]),- ]));- final days = fit.daysSinceTrained();- expect(days['chest'], 9);- expect(days['quads'], isNull);- expect(fit.untrainedLongest(), isNot(contains('chest')));- expect(fit.untrainedLongest().length, 3);- });- });-- group('vista en lista', () {- test('el ajuste se guarda y por defecto son tarjetas', () {- expect(fit.sessionLayout, 'cards');- fit.setSessionLayout('list');- fit.persistNow();- fit.sessionLayout = 'cards';- fit.loadFromStore();- expect(fit.listLayout, isTrue);- });-- test('marcar una serie de otro ejercicio lo pone delante y descansa con su tiempo', () {- final id = fit.createRoutine('L');- final squat = fit.matchExerciseByName('Barbell Squat')!.id;- fit.toggleRoutineExercise(id, bench());- fit.toggleRoutineExercise(id, squat);- fit.setRoutineRest(id, squat, 200);- fit.startRoutine(fit.routines.firstWhere((r) => r.id == id));- fit.endCountdown();- fit.toggleSetAt(1, 0);- expect(fit.session!.currentIndex, 1);- expect(fit.restTotal, 200);- fit.skipRest();- });-- test('copiar la serie anterior y mover ejercicios', () {- fit.sessions.add(LoggedSession(day(-2), 600, [- LoggedExercise(bench(), 'Bench Press', 'chest', [LoggedSet(6, 82.5)]),- ]));- final r = routine('P');- fit.startRoutine(r);- fit.endCountdown();- fit.copyPreviousSet(0, 0);- final st = fit.session!.exercises.first.sets.first;- expect(st.reps, 6);- expect(st.weight, 82.5);-- fit.addExerciseToSession(fit.matchExerciseByName('Barbell Squat')!.id);- final first = fit.session!.exercises.first.id;- fit.moveSessionExercise(0, 1);- expect(fit.session!.exercises[1].id, first);- fit.moveSessionExercise(1, -1);- expect(fit.session!.exercises[0].id, first);- });- });- group('widgets de nutrición', () {- test('lo tocado en el widget se apunta con su hora, en su día, y lo muy viejo se ignora', () {- final now = DateTime.now();- final ms = now.subtract(const Duration(minutes: 5)).millisecondsSinceEpoch;- final twoDays = now.subtract(const Duration(days: 2));- final old = twoDays.millisecondsSinceEpoch;- final stale = now.subtract(const Duration(days: 10)).millisecondsSinceEpoch;- final food = fit.saveFood(name: 'Batido', macros: const Macros(kcal: 120, protein: 24));- final before = fit.waterOn(now);- final n = fit.takeWidgetLog('w,$ms,250;w,$old,250;w,$stale,250;s,$ms,${food.id};x,1,2;w,bad,3');- expect(n, 3);- expect(fit.waterOn(twoDays), 250);- expect(fit.waterOn(now), before + 250);- expect(fit.totalOn(now).protein.round(), 24);- expect(fit.waterSipsOn(now).last.at.millisecondsSinceEpoch, ms);- });- });-}diff --git a/test/requests_18sep_test.dart b/test/requests_18sep_test.dartdeleted file mode 100644index b20088f..0000000--- a/test/requests_18sep_test.dart+++ /dev/null@@ -1,424 +0,0 @@-import 'dart:convert';--import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/models/exercise.dart';-import 'package:gymmane/models/live_session.dart';-import 'package:gymmane/models/workout.dart';-import 'package:gymmane/services/local_store.dart';-import 'package:gymmane/services/plan_share.dart';-import 'package:gymmane/services/rest_alarm.dart';-import 'package:gymmane/services/workout_import.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');- });-- tearDown(() {- if (fit.session != null) fit.saveAndExit();- });-- String idOf(String name) => fit.matchExerciseByName(name)!.id;-- Routine routineWith(List<String> ids, {String name = 'Push'}) {- final id = fit.createRoutine(name);- for (final ex in ids) {- fit.toggleRoutineExercise(id, ex);- }- return fit.routines.firstWhere((r) => r.id == id);- }-- group('sets inside a live workout', () {- test('changing a set carries over to the sets that still match it', () {- final r = routineWith([idOf('Barbell Bench Press')]);- fit.startRoutine(r);- final sets = fit.session!.exercises.first.sets;- for (var j = 0; j < sets.length; j++) {- fit.setSessionWeight(0, j, 60);- fit.setSessionReps(0, j, 10);- }- fit.setSessionWeight(0, sets.length - 1, 70);-- fit.setSessionWeight(0, 0, 62.5);- fit.setSessionReps(0, 0, 8);- expect(sets.first.weight, 62.5);- for (var j = 1; j < sets.length - 1; j++) {- expect(sets[j].weight, 62.5);- expect(sets[j].reps, 8);- }- expect(sets.last.weight, 70);- expect(sets.last.reps, 8);- });-- test('a set can be removed and brought back', () {- final r = routineWith([idOf('Barbell Bench Press')]);- fit.startRoutine(r);- final sets = fit.session!.exercises.single.sets;- final before = sets.length;- final gone = fit.removeSet(0, 1)!;- expect(sets.length, before - 1);- fit.insertSet(0, 1, gone);- expect(sets.length, before);- expect(identical(sets[1], gone), isTrue);- });-- test('a warm-up added by mistake goes away in one tap', () {- final r = routineWith([idOf('Barbell Bench Press')]);- fit.startRoutine(r);- final working = fit.session!.exercises.single.sets.length;- fit.addWarmupSets(0);- expect(fit.hasWarmup(0), isTrue);- fit.removeWarmupSets(0);- expect(fit.hasWarmup(0), isFalse);- expect(fit.session!.exercises.single.sets.length, working);- });-- test('jumping and reordering keep the exercise you are on', () {- final ids = [idOf('Barbell Bench Press'), idOf('Barbell Full Squat'), idOf('Pull Up')];- final r = routineWith(ids);- fit.toggleChain(r.id, ids[0]);- fit.startRoutine(r);- fit.goToExercise(1);- expect(fit.currentExercise!.id, ids[1]);- fit.reorderSessionExercise(2, 0);- expect(fit.session!.exercises.first.id, ids[2]);- expect(fit.currentExercise!.id, ids[1]);- expect(fit.session!.exercises.every((e) => !e.linkedNext || e.id != ids[2]), isTrue);- });- });-- group('suggestions', () {- test('an exercise switched off never lands in the picks but stays searchable', () {- fit.selectedMuscles- ..clear()- ..add('chest');- fit.trainContinue();- final first = fit.sessionPicks.first;- fit.toggleSuggest(first);- fit.trainContinue();- expect(fit.sessionPicks.contains(first), isFalse);- expect(fit.trainSearchResults(fit.exerciseById(first)!.name).map((e) => e.id), contains(first));- expect(fit.recommendedExercises(20).map((e) => e.id), isNot(contains(first)));- });-- test('the suggested picks come first in the review list', () {- fit.selectedMuscles- ..clear()- ..addAll(['chest', 'triceps']);- fit.trainContinue();- final list = fit.reviewExercises();- final seeded = list.take(fit.pickSeed.length).map((e) => e.id).toSet();- expect(seeded, fit.pickSeed);- });-- test('hidden exercises survive a restart', () {- fit.toggleSuggest(idOf('Barbell Bench Press'));- fit.persistNow();- fit.loadFromStore();- expect(fit.suggests(idOf('Barbell Bench Press')), isFalse);- });- });-- group('your own exercises', () {- test('a catalogue id starting with c is not taken for yours', () {- expect(fit.isCustom('cycling'), isFalse);- final mine = fit.addCustomExercise(name: 'Cable thing', primary: 'chest', equipment: 'Barbell');- expect(fit.isCustom(mine), isTrue);- });-- test('yours always show up, whatever place is active', () {- final mine = fit.addCustomExercise(name: 'Mi press raro', primary: 'chest', equipment: 'Barbell');- final home = fit.addPresetPlace('home');- fit.setActivePlace(home);- expect(fit.exercisesMatching('raro').map((e) => e.id), contains(mine));- });-- test('steps and type travel through a save and back', () {- final mine = fit.addCustomExercise(- name: 'Row a la valla',- primary: 'back',- equipment: 'Other',- steps: ['1. Grab the rail', '- Pull', '', 'Lower slowly'],- mode: 'time',- );- final ex = fit.exerciseById(mine)!;- expect(ex.steps, ['Grab the rail', 'Pull', 'Lower slowly']);- expect(ex.mode, 'time');- final back = Exercise.fromJson(ex.toJson());- expect(back.steps, ex.steps);- expect(back.mode, 'time');- fit.updateCustomExercise(mine,- name: 'Row', primary: 'back', equipment: 'Other', difficulty: 'Beginner', steps: ['Only'], mode: '');- expect(fit.exerciseById(mine)!.steps, ['Only']);- expect(fit.modeOf(mine), '');- });- });-- group('cardio and timed work', () {- test('a run opens with time and distance, and remembers them', () {- final run = idOf('Outdoor Run');- expect(fit.modeOf(run), 'cardio');- expect(fit.restFor(run), 0);- final r = routineWith([run]);- expect(fit.routineSets(r, run), 1);- fit.startRoutine(r);- final st = fit.session!.exercises.single.sets.single;- expect(st.sec, 1200);- fit.setSessionKm(0, 0, 5.2);- fit.setSessionSeconds(0, 0, 1800);- fit.toggleSet(0, 0);- fit.finishSession();- fit.saveAndExit();- final logged = fit.lastSetsFor(run).single;- expect(logged.km, 5.2);- expect(fit.loggedSetLabel(logged), '5.2 km · 30:00');- fit.startRoutine(r);- expect(fit.session!.exercises.single.sets.single.km, 5.2);- expect(fit.nextTarget(run), isNull);- });-- test('miles show for imperial users', () {- fit.setUnits('lb');- expect(fit.distanceLabel(1.609344), '1 mi');- fit.setUnits('kg');- });-- test('a plank opens with seconds and the hold can start and stop', () {- final plank = idOf('Plank');- expect(fit.modeOf(plank), 'time');- fit.startRoutine(routineWith([plank]));- final sets = fit.session!.exercises.single.sets;- expect(sets.first.sec, 30);- fit.startHold(0, 0);- expect(fit.holding, isTrue);- expect(fit.holdRemaining, 30);- expect(fit.holdLead, inInclusiveRange(4, 5));- fit.stopHold();- expect(fit.holding, isFalse);- expect(sets.first.done, isFalse);- });-- test('how an exercise is logged can be changed and changed back', () {- final rope = idOf('Jump Rope');- expect(fit.modeOf(rope), 'time');- fit.setExerciseMode(rope, '');- expect(fit.modeOf(rope), '');- fit.setExerciseMode(rope, 'time');- expect(fit.modeOverride.containsKey(rope), isFalse);- });-- test('timed and cardio sets keep their fields through json', () {- final s = SessionSet(0, 20, true, sec: 45, km: null, kind: SetKind.restPause);- final back = SessionSet.fromJson(s.toJson());- expect(back.sec, 45);- expect(back.kind, SetKind.restPause);- final l = LoggedSet.fromJson(LoggedSet(0, 0, sec: 600, km: 2.5).toJson());- expect(l.km, 2.5);- expect(l.oneRm, 0);- });- });-- group('planned routines', () {- test('planned sets open the workout with their type, reps and weight', () {- final bench = idOf('Barbell Bench Press');- final r = routineWith([bench]);- fit.setPlannedSets(r.id, bench, const [- PlannedSet(reps: 12, weightKg: 30, kind: SetKind.warmup),- PlannedSet(reps: 8, weightKg: 70),- PlannedSet(reps: 6, weightKg: 75, kind: SetKind.drop),- ]);- expect(fit.routineSets(r, bench), 2);- fit.startRoutine(r);- final sets = fit.session!.exercises.single.sets;- expect(sets.map((s) => s.kind), [SetKind.warmup, SetKind.normal, SetKind.drop]);- expect(sets.map((s) => s.reps), [12, 8, 6]);- expect(sets.map((s) => s.weight), [30, 70, 75]);- });-- test('the set stepper grows and shrinks the plan, never below one working set', () {- final bench = idOf('Barbell Bench Press');- final r = routineWith([bench]);- fit.setPlannedSets(r.id, bench, const [- PlannedSet(kind: SetKind.warmup),- PlannedSet(reps: 5, weightKg: 100),- ]);- fit.bumpRoutineSets(r.id, bench, 2);- expect(fit.routineSets(r, bench), 3);- expect(fit.plannedSets(r, bench).last.weightKg, 100);- fit.bumpRoutineSets(r.id, bench, -5);- expect(fit.routineSets(r, bench), 1);- expect(fit.plannedSets(r, bench).first.kind, SetKind.warmup);- });-- test('a finished workout saved as routine keeps its sets and supersets', () {- final ids = [idOf('Barbell Bench Press'), idOf('Barbell Bent Over Row')];- final r = routineWith(ids);- fit.toggleChain(r.id, ids.first);- fit.startRoutine(r);- fit.setSessionWeight(0, 0, 62.5);- final saved = fit.saveSessionAsRoutine('Copy');- final made = fit.routines.firstWhere((x) => x.id == saved);- expect(made.chained, contains(ids.first));- expect(fit.plannedSets(made, ids.first).first.weightKg, 62.5);- });- });-- group('reading plans', () {- test('an AI plan with weeks, days, reps, weight and supersets', () {- final plans = parsePlan('Here you go!\n```json\n'- '{"program": "Base", "unit": "lb", "weeks": ['- '{"name": "Week 1", "routines": [{"name": "A", "days": ["Monday", "jue"], "exercises": ['- '{"name": "Barbell Bench Press", "sets": 3, "reps": "8-10", "weight": 135, "rest": "2 min", "superset": true},'- '{"name": "Barbell Bent Over Row", "sets": 3, "reps": 8}]}]},'- '{"name": "Week 2", "routines": [{"name": "A", "exercises": ["Pull Up"]}]}]}\n```');- expect(plans.length, 2);- expect(plans.first.group, 'Base · Week 1');- expect(plans.first.days, [1, 4]);- final bench = plans.first.items.first;- expect(bench.reps, 8);- expect(bench.weightKg, closeTo(61.2, 0.1));- expect(bench.restSec, 120);- expect(bench.superset, isTrue);- expect(plans.last.group, 'Base · Week 2');- });-- test('a csv plan', () {- final plans = parsePlan('routine;exercise;sets;reps;weight\n'- 'Push;Barbell Bench Press;4;8;60\nPush;Push Up;3;15;\nLegs;Barbell Full Squat;5;5;100');- expect(plans.map((p) => p.name), ['Push', 'Legs']);- expect(plans.first.items.first.weightKg, 60);- expect(plans.last.items.single.sets, 5);- });-- test('prose with commas is not taken for a plan', () {- expect(parsePlan('Sure, here is your routine, enjoy it'), isEmpty);- });-- test('importing builds planned sets, supersets and the week, once', () {- final text = '{"routines": [{"name": "Upper", "days": [2], "exercises": ['- '{"name": "Barbell Bench Press", "sets": 2, "reps": 8, "weight": 60, "superset": true,'- ' "plan": [{"type": "warmup", "reps": 10, "weight": 30}]},'- '{"name": "Barbell Bent Over Row", "sets": 3}]}]}';- final plans = parsePlan(text);- final first = fit.applyPlan(plans, schedule: true);- expect(first.routines, 1);- final r = fit.routines.single;- final bench = idOf('Barbell Bench Press');- expect(fit.plannedSets(r, bench).map((p) => p.kind), [SetKind.warmup, SetKind.normal, SetKind.normal]);- expect(fit.routineSets(r, bench), 2);- expect(fit.routineSets(r, idOf('Barbell Bent Over Row')), 3);- expect(r.chained, contains(bench));- expect(fit.weeklyPlan[2], r.id);- final again = fit.applyPlan(plans);- expect(again.routines, 0);- expect(fit.routines.length, 1);- });-- test('a shared plan round-trips to another phone, custom exercises included', () {- final mine = fit.addCustomExercise(- name: 'Landmine Twist', primary: 'obliques', equipment: 'Barbell', steps: ['Twist']);- final bench = idOf('Barbell Bench Press');- final r = routineWith([bench, mine], name: 'Mixed');- fit.setRoutineGroup(r.id, 'Couple');- fit.setPlannedSets(r.id, bench, const [PlannedSet(reps: 8, weightKg: 50)]);- fit.assignRoutineToDay(3, r.id);- final json = fit.exportPlanJson([r]);- expect(jsonDecode(json)['gymmane'], 'plan');- expect(fit.planSummaryText([r]), contains('Mixed'));-- fit.resetAllData();- final result = fit.applyPlan(parsePlan(json), schedule: true);- expect(result.routines, 1);- expect(result.missed, isEmpty);- final got = fit.routines.single;- expect(got.name, 'Mixed');- expect(got.group, 'Couple');- expect(fit.plannedSets(got, bench).single.weightKg, 50);- final twist = fit.customExercises.single;- expect(twist.name, 'Landmine Twist');- expect(twist.steps, ['Twist']);- expect(got.exerciseIds, [bench, twist.id]);- expect(fit.weeklyPlan[3], got.id);- });-- test('the request for an AI carries the format', () {- final text = fit.planRequestText();- expect(text, contains('"weeks"'));- expect(text, contains('Barbell Bench Press'));- });- });-- group('recovery', () {- test('nothing trained means fully recovered', () {- expect(fit.overallRecovery(), 100);- expect(fit.stillRecovering(), isEmpty);- });-- test('a hard chest day tires the chest and it recovers in a few days', () {- final now = DateTime(2026, 9, 18, 18);- fit.sessions.add(LoggedSession(now.subtract(const Duration(hours: 1)), 3600, [- LoggedExercise(idOf('Barbell Bench Press'), 'Bench', 'chest',- [for (var i = 0; i < 8; i++) LoggedSet(8, 80, rpe: 9)]),- ]));- final fresh = fit.muscleRecovery(now: now);- expect(fresh['chest'], lessThan(0.3));- expect(fresh['quads'], 1);- expect(fit.hoursUntilRecovered('chest', now: now), greaterThan(12));- final later = fit.muscleRecovery(now: now.add(const Duration(days: 4)));- expect(later['chest'], greaterThan(0.8));- expect(fit.stillRecovering(now: now), contains('chest'));- });- });-- group('settings', () {- test('the theme can follow the phone and older backups still load', () {- fit.setThemePref('system');- fit.persistNow();- fit.loadFromStore();- expect(fit.themePref, 'system');- fit.applyBackup({'dark': false});- expect(fit.themePref, 'light');- fit.setThemePref('dark');- });-- test('the rest alarm style is kept and handed to the alarm', () {- fit.setAlarmStyle('vibrate');- expect(RestAlarm.instance.style, 'vibrate');- fit.persistNow();- fit.loadFromStore();- expect(fit.alarmStyle, 'vibrate');- fit.setAlarmStyle('loud');- });-- test('height reads in feet and inches for imperial users', () {- fit.setUnits('lb');- expect(fit.heightLabel(175), '5′ 9″');- fit.setUnits('kg');- expect(fit.heightLabel(175), '175 cm');- });- });-- group('lyfta', () {- const csv = 'Title,Date,Duration,Description,Notes,Exercise,Exercise Note,Superset id,Weight,Reps,'- 'RIR/RPE,Distance,Time,Set Type,RecordLevel: gold/silver/bronze,RecordType: 1RM / max_weight / volume / reps\n'- 'Pull Day,2026-04-17 16:00:05,01:19:33,"A plan, with commas",,Barbell Bent Over Row,,,60.000,10,,,,NORMAL_SET,,\n'- 'Pull Day,2026-04-17 16:00:05,01:19:33,"A plan, with commas",,Barbell Bent Over Row,,,70.000,8,,,,NORMAL_SET,1,1\n'- 'Pull Day,2026-04-17 16:00:05,01:19:33,"A plan, with commas",,Pull Up,,,,12,,,,NORMAL_SET,,\n';-- test('the export is recognised and read', () {- expect(detectFormat(csv), ImportFormat.lyfta);- final result = parseImport(csv);- final session = result.sessions.single;- expect(session.durationSec, 3600 + 19 * 60 + 33);- expect(session.exercises.first.sets.map((s) => s.weightKg), [60, 70]);- expect(session.exercises.last.name, 'Pull Up');- });- });-}diff --git a/test/requests_19oct_b_test.dart b/test/requests_19oct_b_test.dartdeleted file mode 100644index 4e51437..0000000--- a/test/requests_19oct_b_test.dart+++ /dev/null@@ -1,81 +0,0 @@-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/catalog/exercise_catalog.dart';-import 'package:gymmane/l10n/l10n.dart';-import 'package:gymmane/models/workout.dart';-import 'package:gymmane/services/exercise_match.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.onboarded = true;- setAppLanguage('en');- });-- List<String> search(String q) => kExercises.where(exerciseSearch(q)).map((e) => e.name).toList();-- group('#237 buscador', () {- test('gemelos en plural, por músculo y con palabras desordenadas', () {- expect(search('Calf raises'), contains('Bodyweight Standing Calf Raise'));- expect(search('calves'), contains('Donkey Calf Raise'));- expect(search('machine calf raise'), contains('Lever Standing Calf Raise'));- expect(search('seated calf raises'), contains('Dumbbell Seated One Leg Calf Raise'));- expect(search('calf ra'), contains('Smith Calf Raise'));- });-- test('el nombre del músculo en castellano también busca', () {- setAppLanguage('es');- expect(search('gemelos'), contains('Donkey Calf Raise'));- setAppLanguage('en');- });-- test('no se cuelan resultados de más', () {- expect(search('calf raise').every((n) => n.toLowerCase().contains('calf')), isTrue);- expect(search('bench press'), isNot(contains('Donkey Calf Raise')));- expect(search('ch'), isNot(contains('Donkey Calf Raise')));- });- });-- group('#234 tira de la semana', () {- test('con una rutina pendiente el día sale a medias, no hecho', () {- fit.toggleMultiPlan();- final a = fit.createRoutine('A');- final b = fit.createRoutine('B');- final today = DateTime.now().weekday;- fit.togglePlanDay(today, a);- fit.togglePlanDay(today, b);- expect(fit.isDayPartial(fit.todayIndex), isFalse);-- fit.sessions.add(LoggedSession(DateTime.now().copyWith(hour: 12), 600, [- LoggedExercise('x', 'X', 'chest', [LoggedSet(5, 60)]),- ], routineId: a));- expect(fit.isDayDone(fit.todayIndex), isTrue);- expect(fit.isDayPartial(fit.todayIndex), isTrue);-- fit.sessions.add(LoggedSession(DateTime.now().copyWith(hour: 12), 600, [- LoggedExercise('x', 'X', 'chest', [LoggedSet(5, 60)]),- ], routineId: b));- expect(fit.isDayPartial(fit.todayIndex), isFalse);- });-- test('un día con una sola rutina sigue igual que antes', () {- final a = fit.createRoutine('A');- fit.togglePlanDay(DateTime.now().weekday, a);- fit.sessions.add(LoggedSession(DateTime.now().copyWith(hour: 12), 600, [- LoggedExercise('x', 'X', 'chest', [LoggedSet(5, 60)]),- ], routineId: a));- expect(fit.isDayPartial(fit.todayIndex), isFalse);- });- });-- test('#236 el cronómetro solo en ejercicios con reloj', () {- expect(fit.runsClock('plank-hold'), isTrue);- expect(fit.runsClock(fit.matchExerciseByName('Bench Press')!.id), isFalse);- });-}diff --git a/test/requests_19oct_test.dart b/test/requests_19oct_test.dartdeleted file mode 100644index 80a8560..0000000--- a/test/requests_19oct_test.dart+++ /dev/null@@ -1,284 +0,0 @@-import 'dart:io';--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.resetAllData();- fit.onboarded = true;- });-- String bench() => fit.matchExerciseByName('Bench Press')!.id;- String squat() => fit.matchExerciseByName('Barbell Squat')!.id;-- Routine routine(String name, [List<String>? ids]) {- final id = fit.createRoutine(name);- for (final e in ids ?? [bench()]) {- fit.toggleRoutineExercise(id, e);- }- return fit.routines.firstWhere((r) => r.id == id);- }-- void train(Routine r) {- fit.startRoutine(r);- fit.endCountdown();- fit.toggleSet(0, 0);- fit.finishSession();- }-- void close() => fit.saveAndExit();-- DateTime day(int offset, [int hour = 10]) {- final n = DateTime.now();- return DateTime(n.year, n.month, n.day + offset, hour);- }-- group('rotación a fondo', () {- Routine rotate(List<Routine> list) {- fit.setRotation(true);- for (final r in list) {- if (!fit.rotationIds.contains(r.id)) fit.toggleRotationRoutine(r.id);- }- return list.first;- }-- test('A, B, C seguidas en días distintos dan la vuelta entera', () {- final a = routine('A'), b = routine('B'), c = routine('C');- rotate([a, b, c]);- final seen = <String>[];- for (var i = 0; i < 4; i++) {- final next = fit.rotationNext!;- seen.add(next.name);- train(next);- close();- }- expect(seen, ['A', 'B', 'C', 'A']);- expect(fit.rotationNext?.id, b.id);- });-- test('hoy enseña la hecha y mañana la siguiente', () {- final a = routine('A'), b = routine('B');- rotate([a, b]);- train(a);- close();- expect(fit.routinesOn(DateTime.now()).single.id, a.id);- expect(fit.pendingRoutinesOn(DateTime.now()), isEmpty);- expect(fit.routinesOn(day(1)).single.id, b.id);- expect(fit.routinesOn(day(-1)), isEmpty);- });-- test('una rutina fuera de la rotación no la mueve', () {- final a = routine('A'), b = routine('B'), x = routine('X');- rotate([a, b]);- train(x);- close();- expect(fit.rotationNext?.id, a.id);- });-- test('hacer la B cuando tocaba la A salta a la C', () {- final a = routine('A'), b = routine('B'), c = routine('C');- rotate([a, b, c]);- train(b);- close();- expect(fit.rotationNext?.id, c.id);- });-- test('volver al entreno desde el resumen no avanza dos veces', () {- final a = routine('A'), b = routine('B'), c = routine('C');- rotate([a, b, c]);- train(a);- expect(fit.rotationNext?.id, b.id);- fit.continueSession();- expect(fit.rotationNext?.id, a.id);- fit.finishSession();- expect(fit.rotationNext?.id, b.id);- close();- expect(fit.sessions.length, 1);- });-- test('quitar la que tocaba pasa a la primera y vaciarla vuelve a la semana', () {- final a = routine('A'), b = routine('B');- fit.assignRoutineToDay(DateTime.now().weekday, a.id);- rotate([a, b]);- fit.setRotationNext(b.id);- fit.toggleRotationRoutine(b.id);- expect(fit.rotationNext?.id, a.id);- fit.toggleRotationRoutine(a.id);- expect(fit.rotating, isFalse);- expect(fit.routinesOn(DateTime.now()).single.id, a.id);- });-- test('nada de rutinas vacías ni ids sueltos al cargar', () {- final a = routine('A'), b = routine('B');- rotate([a, b]);- fit.rotationIds.add('no-existe');- fit.persistNow();- fit.loadFromStore();- expect(fit.rotationRoutines.map((r) => r.id), [a.id, b.id]);- });- });-- group('mover el día a fondo', () {- test('a un día que ya tiene rutina se suman las dos', () {- final a = routine('A'), b = routine('B');- final today = DateTime.now();- fit.toggleMultiPlan();- fit.assignRoutineToDay(today.weekday, a.id);- fit.assignRoutineToDay(day(1).weekday, b.id);- fit.moveRoutineDay(a.id, today, day(1));- expect(fit.routinesOn(day(1)).map((r) => r.id), [b.id, a.id]);- expect(fit.routinesOn(today), isEmpty);- expect(fit.routinesOn(day(8)).map((r) => r.id), [b.id]);- });-- test('mover dos veces y deshacer la segunda deja la primera', () {- final a = routine('A');- final today = DateTime.now();- fit.assignRoutineToDay(today.weekday, a.id);- fit.moveRoutineDay(a.id, today, day(1));- final undo = fit.moveRoutineDay(a.id, day(1), day(2))!;- expect(fit.routinesOn(day(2)).single.id, a.id);- expect(fit.routinesOn(day(1)), isEmpty);- undo();- expect(fit.routinesOn(day(1)).single.id, a.id);- expect(fit.routinesOn(day(2)), isEmpty);- });-- test('no mueve lo que no está ese día ni al mismo día', () {- final a = routine('A');- final today = DateTime.now();- expect(fit.moveRoutineDay(a.id, today, day(1)), isNull);- fit.assignRoutineToDay(today.weekday, a.id);- expect(fit.moveRoutineDay(a.id, today, DateTime.now()), isNull);- expect(fit.planMoves, isEmpty);- });-- test('los cambios viejos se borran solos', () {- final a = routine('A');- fit.planMoves['2001-01-01'] = [a.id];- final today = DateTime.now();- fit.assignRoutineToDay(today.weekday, a.id);- fit.moveRoutineDay(a.id, today, day(1));- expect(fit.planMoves.containsKey('2001-01-01'), isFalse);- });-- test('borrar la rutina la quita también de los días movidos', () {- final a = routine('A');- final today = DateTime.now();- fit.assignRoutineToDay(today.weekday, a.id);- fit.moveRoutineDay(a.id, today, day(1));- fit.deleteRoutine(a.id);- expect(fit.routinesOn(day(1)), isEmpty);- });- });-- group('#81 entreno que pasa de medianoche', () {- test('cuenta en el día en que empezó', () {- final end = day(0, 1);- fit.sessions.add(LoggedSession(end, 2 * 3600, [- LoggedExercise(bench(), 'Bench Press', 'chest', [LoggedSet(8, 60)]),- ]));- expect(fit.trainedToday, isFalse);- expect(fit.sessionsOn(day(-1)).length, 1);- expect(fit.sessionsOn(DateTime.now()), isEmpty);- });- });-- group('#212 series añadidas en la rutina', () {- test('añadir una serie se ofrece guardar y queda en la rutina', () {- final r = routine('A', [bench(), squat()]);- expect(fit.routineSets(r, bench()), 3);- fit.startRoutine(r);- fit.endCountdown();- fit.addSet(0);- fit.removeSet(1, 2);- fit.toggleSet(0, 0);- fit.finishSession();- expect(fit.sessionEditedRoutine, isTrue);- final changes = fit.sessionRoutineChanges;- expect(changes.added, isEmpty);- expect([for (final c in changes.sets) (c.ex.id, c.from, c.to)], [(bench(), 3, 4), (squat(), 3, 2)]);- fit.saveSessionIntoRoutine();- expect(fit.routineSets(r, bench()), 4);- expect(fit.routineSets(r, squat()), 2);- expect(fit.sessionEditedRoutine, isFalse);- });-- test('con series planificadas copia la última', () {- final r = routine('A');- fit.setPlannedSets(r.id, bench(), const [- PlannedSet(kind: SetKind.warmup, reps: 10),- PlannedSet(reps: 8, weightKg: 60),- PlannedSet(reps: 6, weightKg: 70),- ]);- fit.startRoutine(r);- fit.endCountdown();- fit.addSet(0);- fit.toggleSet(0, 0);- fit.finishSession();- fit.saveSessionIntoRoutine();- final plan = fit.plannedSets(r, bench());- expect(plan.length, 4);- expect(plan.first.kind, SetKind.warmup);- expect(plan.last.reps, 6);- expect(plan.last.weightKg, 70);- });-- test('sin cambios no molesta', () {- final r = routine('A');- train(r);- expect(fit.sessionEditedRoutine, isFalse);- });- });-- group('#211 press inclinado en máquina', () {- test('está en el catálogo con su dibujo', () {- final ex = fit.exerciseById('incline-chest-press-machine');- expect(ex, isNotNull);- expect(ex!.equipment, 'Machine');- expect(File('assets/art/${ex.art}.txt').readAsLinesSync().where((l) => l.isNotEmpty).length, 2);- expect(fit.matchExerciseByName('Incline Chest Press (Machine)')?.id, ex.id);- });- });-- group('descanso', () {- test('quitar segundos baja la barra y sumar la alarga', () {- final r = routine('A');- fit.setRoutineRest(r.id, bench(), 120);- fit.startRoutine(r);- fit.endCountdown();- fit.toggleSet(0, 0);- expect(fit.restTotal, 120);- fit.nudgeRest(-15);- fit.nudgeRest(-15);- expect(fit.restTotal, 120);- expect(fit.session!.restRemaining, lessThanOrEqualTo(90));- fit.nudgeRest(60);- expect(fit.restTotal, greaterThanOrEqualTo(fit.session!.restRemaining!));- fit.skipRest();- });-- test('cuando el aviso nativo dice que acabó, se cierra el descanso', () {- final r = routine('A');- fit.startRoutine(r);- fit.endCountdown();- fit.toggleSet(0, 0);- final s = fit.session!;- s.restEndsAt = DateTime.now().subtract(const Duration(seconds: 1));- final tick = fit.restDoneTick;- fit.restElapsed();- expect(s.restEndsAt, isNull);- expect(fit.restDoneTick, tick + 1);- fit.restElapsed();- expect(fit.restDoneTick, tick + 1);- });- });-}diff --git a/test/requests_19sep_test.dart b/test/requests_19sep_test.dartdeleted file mode 100644index d9fea83..0000000--- a/test/requests_19sep_test.dart+++ /dev/null@@ -1,174 +0,0 @@-import 'package:flutter/material.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/models/workout.dart';-import 'package:gymmane/services/local_store.dart';-import 'package:gymmane/services/workout_import.dart';-import 'package:gymmane/state/fit_state.dart';-import 'package:gymmane/theme/app_colors.dart';-import 'package:gymmane/widgets/home_widget_views.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');- });-- tearDown(() {- if (fit.session != null) fit.saveAndExit();- });-- Routine oneSetEach(List<String> names) {- final id = fit.createRoutine('Push');- for (final name in names) {- final ex = fit.matchExerciseByName(name)!.id;- fit.toggleRoutineExercise(id, ex);- fit.bumpRoutineSets(id, ex, -2);- }- return fit.routines.firstWhere((r) => r.id == id);- }-- Future<void> wait(Duration d) => Future<void>.delayed(d + const Duration(milliseconds: 200));-- group('#67 terminar solo', () {- test('al marcar la última serie del último ejercicio se abre el resumen', () async {- fit.startRoutine(oneSetEach(['Barbell Bench Press', 'Barbell Squat']));- fit.endCountdown();- expect(fit.route, 'session');-- fit.toggleSet(0, 0);- await wait(WorkoutState.advanceDelay);- expect(fit.session!.currentIndex, 1);-- fit.toggleSet(1, 0);- expect(fit.isSessionComplete, isFalse, reason: 'primero se ve el tic marcado');- await wait(WorkoutState.finishDelay);- expect(fit.isSessionComplete, isTrue);- expect(fit.sessions, hasLength(1));- });-- test('desmarcar a tiempo lo cancela', () async {- fit.startRoutine(oneSetEach(['Barbell Bench Press']));- fit.endCountdown();- fit.toggleSet(0, 0);- fit.toggleSet(0, 0);- await wait(WorkoutState.finishDelay);- expect(fit.isSessionComplete, isFalse);- });-- test('con el paso automático apagado espera al botón', () async {- fit.toggleAutoAdvance();- fit.startRoutine(oneSetEach(['Barbell Bench Press']));- fit.endCountdown();- fit.toggleSet(0, 0);- await wait(WorkoutState.finishDelay);- expect(fit.isSessionComplete, isFalse);- fit.toggleAutoAdvance();- });-- test('si quedan series atrás, vuelve a ellas en vez de terminar', () async {- fit.startRoutine(oneSetEach(['Barbell Bench Press', 'Barbell Squat']));- fit.endCountdown();- fit.goToExercise(1);- fit.toggleSet(1, 0);- await wait(WorkoutState.finishDelay);- expect(fit.isSessionComplete, isFalse);- expect(fit.session!.currentIndex, 0);- });- });-- test('#58 el paso automático queda contado para avisar del cambio', () async {- fit.startRoutine(oneSetEach(['Barbell Bench Press', 'Barbell Squat']));- fit.endCountdown();- final before = fit.autoMoves;- fit.goToExercise(1);- expect(fit.autoMoves, before, reason: 'moverse a mano no avisa');- fit.goToExercise(0);- fit.toggleSet(0, 0);- await wait(WorkoutState.advanceDelay);- expect(fit.autoMoves, before + 1);- });-- test('el check puesto a mano se quita con otro toque', () {- final today = fit.todayIndex;- fit.toggleCheckin(today);- expect(fit.isDayDone(today), isTrue);- fit.toggleCheckin(today);- expect(fit.isDayDone(today), isFalse);- expect(fit.dateForWeekday(today).day, DateTime.now().day);- });-- testWidgets('el widget de hoy dice hecho o no sin poner el día', (tester) async {- Future<void> show(bool done) => tester.pumpWidget(Directionality(- textDirection: TextDirection.ltr,- child: Center(child: TodayWidgetView(gc: GymColors.dark, done: done, planned: true, streak: 0)),- ));- await show(false);- expect(find.text('${DateTime.now().day}'), findsNothing);- expect(find.byIcon(Icons.fitness_center_rounded), findsOneWidget);- await show(true);- expect(find.byIcon(Icons.check_rounded), findsOneWidget);- });-- testWidgets('el widget de la semana cuenta los días hechos', (tester) async {- await tester.pumpWidget(Directionality(- textDirection: TextDirection.ltr,- child: Center(- child: WeekWidgetView(- gc: GymColors.dark,- done: const [true, false, true, false, false, false, false],- goal: 4,- ),- ),- ));- expect(find.text('2'), findsOneWidget);- expect(find.text('/4'), findsOneWidget);- expect(find.byIcon(Icons.check_rounded), findsNWidgets(2));- final geo = WeekWidgetView.geometry(const Size(320, 150));- final origin = tester.getTopLeft(find.byType(WeekWidgetView));- final dots = find.byWidgetPredicate(- (w) => w is Container && w.decoration is BoxDecoration && (w.decoration as BoxDecoration).shape == BoxShape.circle);- expect(dots, findsNWidgets(7));- for (var i = 0; i < 7; i++) {- final c = tester.getCenter(dots.at(i)) - origin;- expect(c.dx / 320, closeTo(geo[0] + geo[1] * i, 0.002));- expect(c.dy / 150, closeTo(geo[2], 0.002));- }- });-- group('#55 nombres de Lyfta', () {- String? match(String name) => fit.matchExerciseByName(name)?.name;-- test('no cambia de músculo por una palabra suelta', () {- expect(match('Dumbbell Seated Curl'), isNot('Seated Leg Curl'));- expect(match('Lever Seated Leg Extension'), isNot(contains('Calf')));- expect(match('Dumbbell Seated One Arm Rotate'), isNull);- });-- test('el nombre exacto gana', () {- expect(match('Machine Reverse Fly'), 'Machine Reverse Fly');- expect(match('Smith Hack Squat'), 'Smith Hack Squat');- });-- test('encuentra el ejercicio aunque el nombre traiga más cosas', () {- expect(match('Cable Standing Face Pull (with rope)'), 'Face Pull');- expect(match('Barbell Feet Flat Bench Press (male)'), 'Barbell Bench Press');- expect(match('Lever Pec Deck Fly'), 'Pec Deck');- expect(match('Close Grip Preacher Curl'), 'Barbell Preacher Curl');- });-- test('su columna RIR/RPE se entiende en las dos escalas', () {- const csv = 'Title,Date,Duration,Description,Notes,Exercise,Exercise Note,Superset id,Weight,Reps,'- 'RIR/RPE,Distance,Time,Set Type,RecordLevel: gold/silver/bronze,RecordType: 1RM / max_weight / volume / reps\n'- 'Pull,2026-04-17 16:00:05,01:00:00,,,Barbell Curl,,,30.000,10,2,,,NORMAL_SET,,\n'- 'Pull,2026-04-17 16:00:05,01:00:00,,,Barbell Curl,,,30.000,8,8.5,,,NORMAL_SET,,\n'- 'Pull,2026-04-17 16:00:05,01:00:00,,,Barbell Curl,,,30.000,8,,,,NORMAL_SET,,\n';- final sets = parseImport(csv).sessions.single.exercises.single.sets;- expect(sets.map((s) => s.rpe), [8, 8.5, null]);- });- });-}diff --git a/test/requests_20oct_b_test.dart b/test/requests_20oct_b_test.dartdeleted file mode 100644index 56f6516..0000000--- a/test/requests_20oct_b_test.dart+++ /dev/null@@ -1,220 +0,0 @@-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/catalog/exercise_catalog.dart';-import 'package:gymmane/l10n/l10n.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.onboarded = true;- setAppLanguage('en');- });-- test('#238 la prensa de piernas trabaja sobre todo cuádriceps', () {- final press = kExercises.firstWhere((e) => e.name == 'Leg Press');- expect(press.primary, 'quads');- expect(press.secondary, containsAll(['glutes', 'hamstrings']));- });-- group('#240 barra propia', () {- test('sin elegir nada, la barra es la olímpica', () {- expect(fit.plateBarDisplay, 20);- expect(fit.defaultBar, 20);- });-- test('una barra de otro peso calcula los discos sobre ella', () {- fit.setPlateBar(12.5);- fit.plateTarget = 52.5;- expect(fit.plateBreakdown.map((p) => '${fmt(p.weight)}x${p.count}'), ['20x1']);- });-- test('la barra elegida se recuerda al reabrir y vale para toda la app', () async {- fit.setPlateBar(7);- fit.persistNow();- await pumpEventQueue();- fit.loadFromStore();- expect(fit.plateBarDisplay, 7);- expect(fit.defaultBar, 7);- expect(fit.barFor('x'), 7);- });-- test('borrar los datos vuelve a la barra de 20', () {- fit.setPlateBar(15);- fit.resetAllData();- expect(fit.plateBarDisplay, 20);- });- });-- group('#219 calorías de caminar y correr', () {- LoggedSession walk(String id, double km, int sec, {int dur = 0, double? incline}) {- final s = LoggedSession(DateTime.now().copyWith(hour: 12), dur == 0 ? sec : dur, [- LoggedExercise(id, id, 'quads', [LoggedSet(0, 0, sec: sec, km: km)], incline: incline),- ]);- fit.sessions.add(s);- return s;- }-- setUp(() => fit.addBodyweight(70));-- test('caminar 5 km en una hora con 70 kg: 175 activas y ~249 en total (ACSM)', () {- final s = walk('walking', 5, 3600);- final c = fit.cardioKcal(s, s.exercises.first)!;- expect(c.active, 175);- expect(c.total, closeTo(249, 1));- expect(c.own, isFalse);- });-- test('a partir de 7,2 km/h usa la fórmula de correr', () {- final s = walk('running', 10, 3000);- expect(fit.cardioKcal(s, s.exercises.first)!.active, 700);- });-- test('la inclinación suma: 3 km en 30 min al 10 % son 294 activas', () {- final s = walk('treadmill-incline-walk', 3, 1800, incline: 10);- expect(fit.cardioKcal(s, s.exercises.first)!.active, 294);- });-- test('cada serie es un tramo y se calcula por separado', () {- final s = LoggedSession(DateTime.now().copyWith(hour: 12), 4800, [- LoggedExercise('running', 'Running', 'quads', [- LoggedSet(0, 0, sec: 1800, km: 2.5),- LoggedSet(0, 0, sec: 3000, km: 10),- ]),- ]);- fit.sessions.add(s);- final walkPart = (0.1 * (2500 / 30)) * 70 * 30 / 200;- expect(fit.cardioKcal(s, s.exercises.first)!.active, (walkPart + 700).round());- });-- test('el valor del reloj manda sobre el estimado y se puede volver atrás', () {- final s = walk('walking', 5, 3600);- final e = s.exercises.first;- fit.setLoggedKcal(e, 210);- expect(fit.cardioKcal(s, e)!.active, 210);- expect(fit.cardioKcal(s, e)!.own, isTrue);- fit.setLoggedKcal(e, null);- expect(fit.cardioKcal(s, e)!.active, 175);- });-- test('bici, elíptica o remo no se estiman con la fórmula de caminar', () {- final s = walk('cycling', 20, 3600);- expect(fit.cardioKcal(s, s.exercises.first), isNull);- });-- test('un ejercicio propio que se llama carrera sí se estima', () {- final id = fit.addCustomExercise(name: 'Carrera por el parque', primary: 'quads', equipment: 'Bodyweight', mode: 'cardio');- final s = LoggedSession(DateTime.now().copyWith(hour: 12), 3600, [- LoggedExercise(id, 'Carrera por el parque', 'quads', [LoggedSet(0, 0, sec: 3600, km: 5)]),- ]);- fit.sessions.add(s);- expect(fit.cardioKcal(s, s.exercises.first)!.active, 175);- });-- test('las kcal quemadas del día usan el cardio y el resto como pesas', () {- walk('walking', 5, 3600, dur: 5400);- expect(fit.burnedOn(DateTime.now()), 175 + 140);- });-- test('la inclinación y el valor propio se guardan', () async {- final s = walk('walking', 5, 3600);- fit.setLoggedIncline(s.exercises.first, 4);- fit.setLoggedKcal(s.exercises.first, 300);- await pumpEventQueue();- fit.loadFromStore();- final e = fit.sessions.last.exercises.first;- expect(e.incline, 4);- expect(e.kcal, 300);- });-- test('la siguiente sesión hereda la última inclinación de ese ejercicio', () {- final s = walk('treadmill-incline-walk', 3, 1800);- fit.setLoggedIncline(s.exercises.first, 12);- expect(fit.lastIncline('treadmill-incline-walk'), 12);- });- });-- group('#158 planes guardados', () {- late String a, b, c;- setUp(() {- a = fit.createRoutine('A');- b = fit.createRoutine('B');- c = fit.createRoutine('C');- fit.assignRoutineToDay(1, a);- fit.assignRoutineToDay(3, b);- });-- test('guardar la semana y cambiar a otra sin perder la primera', () {- fit.savePlanAs('Invierno');- fit.savePlanAs('Verano', empty: true);- expect(fit.weeklyPlan, isEmpty);- fit.assignRoutineToDay(2, c);- fit.switchPlan(fit.savedPlans.first.id);- expect(fit.weeklyPlan, {1: a, 3: b});- fit.switchPlan(fit.savedPlans.last.id);- expect(fit.weeklyPlan, {2: c});- });-- test('los cambios en la semana van al plan elegido', () {- fit.savePlanAs('Invierno');- fit.assignRoutineToDay(5, c);- fit.savePlanAs('Viaje', empty: true);- fit.switchPlan(fit.savedPlans.first.id);- expect(fit.weeklyPlan, {1: a, 3: b, 5: c});- });-- test('empezar vacío sin haber guardado conserva la semana como «Mi plan»', () {- fit.savePlanAs('Reddit', empty: true);- expect(fit.savedPlans.map((p) => p.name), [t.planMine, 'Reddit']);- fit.switchPlan(fit.savedPlans.first.id);- expect(fit.weeklyPlan, {1: a, 3: b});- });-- test('borrar una rutina la quita de todos los planes', () {- fit.savePlanAs('Invierno');- fit.savePlanAs('Verano');- fit.deleteRoutine(a);- for (final p in fit.savedPlansLive) {- expect(p.uses(a), isFalse);- }- fit.switchPlan(fit.savedPlans.first.id);- expect(fit.weeklyPlan, {3: b});- });-- test('borrar un plan deja la semana como está', () {- fit.savePlanAs('Invierno');- fit.deletePlan(fit.savedPlans.first.id);- expect(fit.savedPlans, isEmpty);- expect(fit.currentPlanId, '');- expect(fit.weeklyPlan, {1: a, 3: b});- });-- test('los planes, el elegido y sus cambios se guardan al reabrir', () async {- fit.savePlanAs('Invierno');- fit.savePlanAs('Verano', empty: true);- fit.assignRoutineToDay(6, c);- fit.renamePlan(fit.currentPlanId, 'Verano 2027');- fit.persistNow();- await pumpEventQueue();- fit.loadFromStore();- expect(fit.savedPlans.map((p) => p.name), ['Invierno', 'Verano 2027']);- expect(fit.currentPlanId, fit.savedPlans.last.id);- expect(fit.weeklyPlan, {6: c});- fit.switchPlan(fit.savedPlans.first.id);- expect(fit.weeklyPlan, {1: a, 3: b});- fit.switchPlan(fit.savedPlans.last.id);- expect(fit.weeklyPlan, {6: c});- });-- test('un nombre vacío no crea nada', () {- fit.savePlanAs(' ');- expect(fit.savedPlans, isEmpty);- });- });-}diff --git a/test/requests_20oct_test.dart b/test/requests_20oct_test.dartdeleted file mode 100644index c49dff1..0000000--- a/test/requests_20oct_test.dart+++ /dev/null@@ -1,496 +0,0 @@-import 'dart:convert';--import 'package:flutter/services.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/app/gymmane_app.dart';-import 'package:gymmane/l10n/l10n.dart';-import 'package:flutter/material.dart';-import 'package:gymmane/models/note.dart';-import 'package:gymmane/models/nutrition.dart';-import 'package:gymmane/models/workout.dart';-import 'package:gymmane/services/local_store.dart';-import 'package:gymmane/services/plan_pdf.dart';-import 'package:gymmane/state/fit_state.dart';-import 'package:gymmane/widgets/glass.dart';-import 'package:shared_preferences/shared_preferences.dart';--void main() {- TestWidgetsFlutterBinding.ensureInitialized();-- setUp(() async {- SharedPreferences.setMockInitialValues({});- await Store.instance.init();- fit.resetAllData();- fit.onboarded = true;- });-- const whey = Macros(kcal: 120, protein: 24, carbs: 3, fat: 1.5);-- group('#226 batidos marcados', () {- test('elegir un batido lo marca y solo los marcados salen en la lista', () {- final a = fit.saveFood(name: 'Whey', macros: whey);- fit.saveFood(name: 'Avena', macros: const Macros(kcal: 380));- fit.setShakeFood(a.id);- expect(fit.isShakeFood(a.id), isTrue);- expect(fit.shakeFoodItems.map((f) => f.id), [a.id]);- });-- test('quitar la marca del elegido pasa al siguiente marcado', () {- final a = fit.saveFood(name: 'Whey', macros: whey);- final b = fit.saveFood(name: 'Vegano', macros: whey);- fit.setShakeFood(a.id);- fit.setShakeTag(b.id, true);- fit.setShakeTag(a.id, false);- expect(fit.shakeFoodId, b.id);- fit.setShakeTag(b.id, false);- expect(fit.shakeFoodId, '');- expect(fit.shakeFood, isNull);- });-- test('marcar el primero lo deja elegido para el vaso', () {- final a = fit.saveFood(name: 'Whey', macros: whey);- fit.setShakeTag(a.id, true);- expect(fit.shakeFoodId, a.id);- });-- test('borrar el alimento quita la marca', () {- final a = fit.saveFood(name: 'Whey', macros: whey);- fit.setShakeTag(a.id, true);- fit.deleteFood(a.id);- expect(fit.shakeFoods, isEmpty);- });-- test('las marcas sobreviven a guardar y cargar', () {- final a = fit.saveFood(name: 'Whey', macros: whey);- final b = fit.saveFood(name: 'Vegano', macros: whey);- fit.setShakeFood(a.id);- fit.setShakeTag(b.id, true);- final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;- fit.applyBackup(data);- expect(fit.shakeFoods.toSet(), {a.id, b.id});- expect(fit.shakeFoodId, a.id);- });-- test('una copia antigua sin marcas conserva su batido elegido', () {- final a = fit.saveFood(name: 'Whey', macros: whey);- fit.setShakeFood(a.id);- final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;- (data['nutrition'] as Map).remove('shakes');- fit.applyBackup(data);- expect(fit.shakeFoods, [a.id]);- expect(fit.shakeFoodId, a.id);- });- });-- group('#220 calendario de 12 meses', () {- test('por defecto son 12 semanas y se guarda el cambio', () {- expect(fit.heatmapYear, isFalse);- expect(fit.heatmapShown.length, 12 * 7);- fit.setHeatmapRange('year');- expect(fit.heatmapShown.length, 53 * 7);- final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;- fit.resetAllData();- expect(fit.heatmapYear, isFalse);- fit.applyBackup(data);- expect(fit.heatmapYear, isTrue);- });-- test('con historia de más de un año llega hasta el primer entreno', () {- fit.setHeatmapRange('year');- final old = DateTime.now().subtract(const Duration(days: 500));- fit.sessions.add(LoggedSession(old, 1800, [- LoggedExercise('x', 'X', 'chest', [LoggedSet(8, 50)]),- ]));- final weeks = fit.heatmapShownWeeks;- expect(weeks, greaterThan(53));- final first = fit.heatmapShownDate(0);- expect(first.isAfter(DateTime(old.year, old.month, old.day)), isFalse);- final i = DateTime(old.year, old.month, old.day).difference(first).inDays;- expect(fit.heatmapShown[i], greaterThan(0));- });-- test('tocar un día abre la fecha correcta en los dos modos', () {- final today = DateTime.now();- final key = DateTime(today.year, today.month, today.day);- for (final range in ['weeks', 'year']) {- fit.setHeatmapRange(range);- final levels = fit.heatmapShown;- final i = levels.lastIndexWhere((l) => l >= 0);- expect(fit.heatmapShownDate(i), key, reason: range);- }- });-- test('un valor raro no cambia el ajuste', () {- fit.setHeatmapRange('decade');- expect(fit.heatmapRange, 'weeks');- });- });-- group('plan en PDF', () {- testWidgets('sale un PDF válido con una página por cada tanda', (tester) async {- setAppLanguage('es');- final id = fit.createRoutine('Empuje');- for (final name in ['Bench Press', 'Barbell Squat', 'Barbell Bent Over Row']) {- fit.toggleRoutineExercise(id, fit.matchExerciseByName(name)!.id);- }- fit.assignRoutineToDay(DateTime.monday, id);- final bytes = await tester.runAsync(() => buildPlanPdf(fit.routines, week: true));- await tester.pump(const Duration(seconds: 1));- final text = latin1.decode(bytes!);- expect(text.startsWith('%PDF-1.4'), isTrue);- expect(text.trimRight().endsWith('%%EOF'), isTrue);- expect(RegExp(r'/Type /Page ').allMatches(text).length, 1);- String hex(String v) => '<FEFF${v.codeUnits.map((u) => u.toRadixString(16).padLeft(4, '0').toUpperCase()).join()}>';- expect(text, contains('/Author ${hex('InlitX')}'));- expect(text, contains('/Lang (es)'));- expect(text, contains('<dc:creator><rdf:Seq><rdf:li>InlitX</rdf:li></rdf:Seq></dc:creator>'));- expect(text, contains('<xmp:CreatorTool>GymMane</xmp:CreatorTool>'));- final xref = int.parse(RegExp(r'startxref\n(\d+)').firstMatch(text)!.group(1)!);- expect(text.substring(xref, xref + 4), 'xref');- for (final m in RegExp(r'(\d{10}) 00000 n ').allMatches(text)) {- final at = int.parse(m.group(1)!);- expect(RegExp(r'^\d+ 0 obj').hasMatch(text.substring(at, at + 12)), isTrue);- }- });-- testWidgets('una rutina larga pasa a otra página', (tester) async {- setAppLanguage('es');- final id = fit.createRoutine('Larga');- for (final e in fit.allExercises.take(24)) {- fit.toggleRoutineExercise(id, e.id);- }- final bytes = await tester.runAsync(() => buildPlanPdf([fit.routines.single]));- await tester.pump(const Duration(seconds: 1));- final pages = RegExp(r'/Type /Page ').allMatches(latin1.decode(bytes!)).length;- expect(pages, greaterThan(1));- });- });-- DateTime ago(int days, [int hour = 18]) {- final n = DateTime.now();- return DateTime(n.year, n.month, n.day - days, hour);- }-- DateTime dayAgo(int days) {- final n = DateTime.now();- return DateTime(n.year, n.month, n.day - days);- }-- void logged(String id, int days, List<LoggedSet> sets) =>- fit.sessions.add(LoggedSession(ago(days), 1200, [LoggedExercise(id, id, 'back', sets)]));-- group('#224 notas en el entreno', () {- test('una nota fijada sale siempre en el entreno', () {- fit.saveNote(exerciseId: 'row', date: ago(10), kind: NoteKind.note, text: 'Asiento en el 2', pinned: true);- logged('row', 5, [LoggedSet(8, 40)]);- expect(fit.workoutNotesFor('row').map((n) => n.text), ['Asiento en el 2']);- });-- test('una nota sin fijar y que no es plan no molesta', () {- fit.saveNote(exerciseId: 'row', date: ago(1), kind: NoteKind.done, text: 'Buen día');- expect(fit.workoutNotesFor('row'), isEmpty);- });-- test('la próxima vez sale hoy, la próxima vez y luego desaparece', () {- fit.saveNote(exerciseId: 'row', date: ago(0), kind: NoteKind.plan, text: 'Sube a 45');- expect(fit.workoutNotesFor('row').single.text, 'Sube a 45');- final old = fit.notes.single;- fit.notes[0] = GymNote(- id: old.id,- exerciseId: 'row',- date: dayAgo(3),- kind: NoteKind.plan,- text: old.text,- createdAt: old.createdAt,- );- logged('row', 3, [LoggedSet(8, 40)]);- expect(fit.workoutNotesFor('row').single.text, 'Sube a 45');- logged('row', 1, [LoggedSet(8, 45)]);- expect(fit.workoutNotesFor('row'), isEmpty);- });-- test('solo sale el plan más reciente', () {- fit.saveNote(exerciseId: 'row', date: ago(2), kind: NoteKind.plan, text: 'Viejo');- fit.saveNote(exerciseId: 'row', date: ago(1), kind: NoteKind.plan, text: 'Nuevo');- expect(fit.workoutNotesFor('row').map((n) => n.text), ['Nuevo']);- });-- test('fijar y soltar se guarda, y una nota general no se puede fijar', () {- fit.saveNote(exerciseId: 'row', date: ago(0), kind: NoteKind.note, text: 'Polea 19');- final id = fit.notes.single.id;- fit.setNotePinned(id, true);- final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;- fit.applyBackup(data);- expect(fit.noteById(id)!.pinned, isTrue);- fit.setNotePinned(id, false);- expect(fit.workoutNotesFor('row'), isEmpty);- fit.saveNote(exerciseId: '', date: ago(0), kind: NoteKind.note, text: 'General', pinned: true);- expect(fit.notes.last.pinned, isFalse);- });-- test('editar sin decir nada conserva la chincheta', () {- fit.saveNote(exerciseId: 'row', date: ago(0), kind: NoteKind.note, text: 'A', pinned: true);- final id = fit.notes.single.id;- fit.saveNote(id: id, exerciseId: 'row', date: ago(0), kind: NoteKind.note, text: 'B');- expect(fit.noteById(id)!.pinned, isTrue);- });- });-- group('#228 editar series registradas', () {- test('cambiar el peso no borra el tiempo, el tipo ni el RPE', () {- final e = LoggedExercise('plank', 'Plank', 'abdomen', [LoggedSet(0, 10, sec: 45, rpe: 8, kind: SetKind.drop)]);- fit.sessions.add(LoggedSession(ago(1), 600, [e]));- fit.bumpLoggedWeight(e, 0, 1);- expect(e.sets.single.sec, 45);- expect(e.sets.single.rpe, 8);- expect(e.sets.single.kind, SetKind.drop);- fit.bumpLoggedSec(e, 0, 1);- expect(e.sets.single.sec, 50);- fit.bumpLoggedSec(e, 0, -20);- expect(e.sets.single.sec, 0);- });-- test('añadir serie copia el tiempo y la distancia', () {- final e = LoggedExercise('run', 'Run', 'quads', [LoggedSet(0, 0, sec: 1800, km: 5)]);- fit.sessions.add(LoggedSession(ago(1), 600, [e]));- fit.addLoggedSet(e);- expect(e.sets.last.sec, 1800);- expect(e.sets.last.km, 5);- fit.bumpLoggedKm(e, 1, 1);- expect(e.sets.last.km, closeTo(5.1, 0.001));- expect(fit.loggedDistance(e), isTrue);- });-- test('un ejercicio con tiempo se reconoce aunque sea propio', () {- final e = LoggedExercise('mio', 'Mío', 'abdomen', [LoggedSet(0, 0, sec: 30)]);- expect(fit.loggedTimed(e), isTrue);- expect(fit.loggedTimed(LoggedExercise('b', 'B', 'chest', [LoggedSet(8, 60)])), isFalse);- });- });-- group('#201 máquinas asistidas', () {- const pull = 'kiJ4Z2K';-- test('las dominadas asistidas vienen marcadas y se pueden desmarcar', () {- expect(fit.isAssisted(pull), isTrue);- expect(fit.isAssisted(fit.matchExerciseByName('Bench Press')!.id), isFalse);- fit.toggleAssisted(pull);- expect(fit.isAssisted(pull), isFalse);- final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;- fit.applyBackup(data);- expect(fit.isAssisted(pull), isFalse);- });-- test('el récord es la menor ayuda, no la mayor', () {- logged(pull, 10, [LoggedSet(8, 40)]);- logged(pull, 3, [LoggedSet(8, 35)]);- final r = fit.exerciseRecord(pull)!;- expect(r.best, 35);- expect(fit.bestSet(pull)!.set.weight, 35);- expect(fit.oneRmSeries(pull), [40, 35]);- });-- test('con más reps y la misma ayuda también es mejor', () {- logged(pull, 10, [LoggedSet(6, 35)]);- logged(pull, 3, [LoggedSet(10, 35)]);- expect(fit.bestSet(pull)!.set.reps, 10);- });-- test('la sugerencia y los pesos de partida bajan la ayuda', () {- fit.progressStep[pull] = 2.5;- logged(pull, 3, [LoggedSet(8, 35), LoggedSet(8, 35)]);- final next = fit.nextTarget(pull)!;- expect(next.weightKg, 32.5);- expect(next.up, isTrue);- final r = fit.createRoutine('Espalda');- fit.toggleRoutineExercise(r, pull);- fit.startRoutine(fit.routines.single);- expect(fit.session!.exercises.single.sets.where((s) => s.kind != SetKind.warmup).first.weight, 32.5);- fit.saveAndExit();- });-- test('la ayuda nunca baja de cero y no hay objetivo de peso', () {- fit.progressStep[pull] = 5;- logged(pull, 3, [LoggedSet(8, 2.5)]);- expect(fit.nextTarget(pull)!.weightKg, 0);- expect(fit.goalFits(pull), isFalse);- expect(fit.bestLift(pull), 0);- });- });-- group('#218 segundo aviso', () {- test('solo acepta las opciones de la hoja y se guarda', () {- expect(fit.trainAgainMin, 0);- fit.setTrainAgain(45);- expect(fit.trainAgainMin, 0);- fit.setTrainAgain(120);- final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;- fit.resetAllData();- expect(fit.trainAgainMin, 0);- fit.applyBackup(data);- expect(fit.trainAgainMin, 120);- });- });-- group('descarga automática', () {- String bench() => fit.matchExerciseByName('Bench Press')!.id;-- test('sin «subir el peso solo» no hay descarga', () {- final id = bench();- for (final d in [9, 6, 3]) {- logged(id, d, [LoggedSet(8, 80), LoggedSet(6, 80)]);- }- expect(fit.stallStreak(id), 3);- expect(fit.needsDeload(id), isFalse);- });-- test('tres entrenos al mismo peso sin cumplir bajan al 90 %', () {- final id = bench();- fit.progressStep[id] = 2.5;- for (final d in [9, 6, 3]) {- logged(id, d, [LoggedSet(8, 80), LoggedSet(6, 80)]);- }- final next = fit.nextTarget(id)!;- expect(next.deload, isTrue);- expect(next.up, isFalse);- expect(next.weightKg, 72.5);- final r = fit.createRoutine('Pecho');- fit.toggleRoutineExercise(r, id);- fit.startRoutine(fit.routines.single);- expect(fit.session!.exercises.single.sets.where((s) => s.kind != SetKind.warmup).first.weight, 72.5);- fit.saveAndExit();- });-- test('dos fallos no bastan y cambiar de peso empieza la cuenta de cero', () {- final id = bench();- fit.progressStep[id] = 2.5;- logged(id, 12, [LoggedSet(8, 80), LoggedSet(6, 80)]);- logged(id, 9, [LoggedSet(8, 80), LoggedSet(6, 80)]);- expect(fit.needsDeload(id), isFalse);- logged(id, 6, [LoggedSet(8, 72.5), LoggedSet(6, 72.5)]);- expect(fit.stallStreak(id), 1);- logged(id, 3, [LoggedSet(8, 72.5), LoggedSet(8, 72.5)]);- expect(fit.stallStreak(id), 0);- expect(fit.nextTarget(id)!.up, isTrue);- });-- test('en una asistida la descarga da más ayuda', () {- const pull = 'kiJ4Z2K';- fit.progressStep[pull] = 2.5;- for (final d in [9, 6, 3]) {- logged(pull, d, [LoggedSet(8, 30), LoggedSet(5, 30)]);- }- final next = fit.nextTarget(pull)!;- expect(next.deload, isTrue);- expect(next.weightKg, 32.5);- });-- test('con poco peso baja al menos un escalón', () {- final id = bench();- fit.progressStep[id] = 2.5;- for (final d in [9, 6, 3]) {- logged(id, d, [LoggedSet(8, 5), LoggedSet(6, 5)]);- }- expect(fit.nextTarget(id)!.weightKg, 2.5);- });- });-- group('#214 #196 historial', () {- test('el mes lista sus entrenos, del más nuevo al más viejo', () {- final n = DateTime.now();- final month = DateTime(n.year, n.month);- fit.sessions.add(LoggedSession(DateTime(n.year, n.month, 1, 18), 1800, [LoggedExercise('a', 'A', 'chest', [LoggedSet(8, 60)])]));- fit.sessions.add(LoggedSession(DateTime(n.year, n.month, 2, 18), 2400, [LoggedExercise('a', 'A', 'chest', [LoggedSet(8, 62.5), LoggedSet(8, 62.5)])]));- fit.sessions.add(LoggedSession(DateTime(n.year, n.month - 1, 20, 18), 600, [LoggedExercise('a', 'A', 'chest', [LoggedSet(8, 50)])]));- final list = fit.sessionsInMonth(month);- expect(list.length, 2);- expect(list.first.day.day, 2);- final sum = fit.monthSummary(month);- expect(sum.workouts, 2);- expect(sum.sets, 3);- expect(sum.seconds, 4200);- expect(fit.monthSummary(DateTime(n.year, n.month - 1)).workouts, 1);- });-- test('no se puede ir más allá del mes actual', () {- fit.goHistory();- expect(fit.historyAtLatest, isTrue);- final before = fit.historyMonth;- fit.shiftHistoryMonth(1);- expect(fit.historyMonth, before);- fit.shiftHistoryMonth(-1);- expect(fit.historyAtLatest, isFalse);- fit.popRoute();- });-- test('cuenta los récords de cada entreno, no el primero', () {- logged('a', 9, [LoggedSet(8, 60)]);- logged('a', 6, [LoggedSet(8, 65)]);- logged('a', 3, [LoggedSet(8, 62.5)]);- final byDay = {for (final e in fit.recordsBySession().entries) e.key.day.day: e.value};- expect(byDay.length, 1);- expect(byDay[ago(6).day], 1);- });-- test('sin nombre ni rutina, el título son los grupos musculares', () {- final s = LoggedSession(ago(1), 600, [- LoggedExercise('a', 'A', 'chest', [LoggedSet(8, 60), LoggedSet(8, 60)]),- LoggedExercise('b', 'B', 'quads', [LoggedSet(5, 100)]),- ]);- fit.sessions.add(s);- expect(fit.sessionHeading(s), contains(' · '));- fit.renameSession(s, 'Pecho pesado');- expect(fit.sessionHeading(s), 'Pecho pesado');- });-- test('la mejor serie de una plancha es la más larga', () {- final e = LoggedExercise('plank', 'Plank', 'abdomen', [LoggedSet(0, 0, sec: 45), LoggedSet(0, 0, sec: 60)]);- expect(fit.topSetOf(e)!.sec, 60);- });- });-- testWidgets('el historial cambia de mes en la app de verdad', (tester) async {- setAppLanguage('es');- fit.refreshAwards(silent: true);- fit.pendingAwards.clear();- fit.resetRoute('settings');- fit.goHistory();- await tester.pumpWidget(const GymManeApp());- for (var i = 0; i < 20; i++) {- await tester.pump(const Duration(milliseconds: 100));- }- final now = DateTime.now();- expect(find.text(t.monthYear(DateTime(now.year, now.month))), findsOneWidget);- await tester.tap(find.bySemanticsLabel(t.notePrevMonth));- for (var i = 0; i < 10; i++) {- await tester.pump(const Duration(milliseconds: 100));- }- expect(find.text(t.monthYear(DateTime(now.year, now.month - 1))), findsOneWidget);- await tester.pumpWidget(const SizedBox());- await tester.pump(const Duration(seconds: 1));- });-- testWidgets('#227 una hoja larga se cierra tirando hacia abajo', (tester) async {- late BuildContext ctx;- await tester.pumpWidget(MaterialApp(home: Builder(builder: (c) {- ctx = c;- return const SizedBox();- })));- showAppSheet<void>(- context: ctx,- builder: (_) => SingleChildScrollView(- child: Column(children: [for (var i = 0; i < 60; i++) SizedBox(height: 40, child: Text('fila $i'))]),- ),- );- await tester.pumpAndSettle();- expect(find.text('fila 0'), findsOneWidget);- await tester.drag(find.text('fila 2'), const Offset(0, 300));- await tester.pumpAndSettle();- expect(find.text('fila 0'), findsNothing);- });-- test('el corredor del logo está en los assets', () async {- final data = await rootBundle.load('assets/img/runner.png');- expect(data.lengthInBytes, greaterThan(0));- });-}diff --git a/test/requests_22oct_test.dart b/test/requests_22oct_test.dartdeleted file mode 100644index 3c6ca20..0000000--- a/test/requests_22oct_test.dart+++ /dev/null@@ -1,341 +0,0 @@-import 'package:flutter/material.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/l10n/l10n.dart';-import 'package:gymmane/models/nutrition.dart';-import 'package:gymmane/models/progression.dart';-import 'package:gymmane/models/workout.dart';-import 'package:gymmane/screens/routine_edit_screen.dart';-import 'package:gymmane/services/local_store.dart';-import 'package:gymmane/state/fit_state.dart';-import 'package:gymmane/theme/app_theme.dart';-import 'package:shared_preferences/shared_preferences.dart';--void main() {- TestWidgetsFlutterBinding.ensureInitialized();-- setUp(() async {- SharedPreferences.setMockInitialValues({});- await Store.instance.init();- fit.resetAllData();- fit.onboarded = true;- fit.setUnits('kg');- setAppLanguage('en');- });-- group('#252 vs la última vez', () {- String startOne() {- fit.startWorkout();- fit.toggleMuscle('chest');- fit.trainContinue();- for (final id in fit.sessionPicks.toList().skip(1)) {- fit.togglePick(id);- }- fit.startSession();- return fit.session!.exercises.first.id;- }-- void before(List<LoggedExercise> ex) => fit.sessions- .add(LoggedSession(DateTime.now().subtract(const Duration(days: 1)), 1800, ex));-- void logSet(int reps, double kg) {- fit.setSessionReps(0, 0, reps);- fit.setSessionWeight(0, 0, kg);- fit.toggleSet(0, 0);- fit.finishSession();- }-- test('peso corporal: compara repeticiones, no da −100 %', () {- final id = startOne();- before([LoggedExercise(id, id, 'chest', [LoggedSet(10, 0)])]);- logSet(12, 0);- expect(fit.summaryVsLast, 20);- expect(fit.summaryFirstTime, isFalse);- });-- test('solo cuentan los ejercicios en común, no la rutina larga de ayer', () {- final id = startOne();- before([- LoggedExercise(id, id, 'chest', [LoggedSet(10, 50)]),- LoggedExercise('otro', 'otro', 'back', [LoggedSet(10, 100)]),- ]);- logSet(10, 55);- expect(fit.summaryVsLast, 10);- });-- test('ayer con peso y hoy sin peso: pasa a repeticiones', () {- final id = startOne();- before([LoggedExercise(id, id, 'chest', [LoggedSet(8, 40)])]);- logSet(8, 0);- expect(fit.summaryVsLast, 0);- });-- test('sin sesión anterior con esos ejercicios es la primera vez', () {- startOne();- before([LoggedExercise('otro', 'otro', 'back', [LoggedSet(10, 100)])]);- logSet(10, 20);- expect(fit.summaryVsLast, isNull);- expect(fit.summaryFirstTime, isTrue);- });-- test('nada que comparar (solo tiempo) no enseña tarjeta', () {- final id = startOne();- before([LoggedExercise(id, id, 'chest', [LoggedSet(0, 0, sec: 60)])]);- logSet(0, 0);- expect(fit.summaryVsLast, isNull);- expect(fit.summaryFirstTime, isFalse);- });- });-- group('#253 tipos de progresión', () {- String bench() => fit.matchExerciseByName('Bench Press')!.id;- DateTime ago(int d) => DateTime.now().subtract(Duration(days: d));- void logged(String id, int days, List<LoggedSet> sets) =>- fit.sessions.add(LoggedSession(ago(days), 1200, [LoggedExercise(id, id, 'chest', sets)]));- List<(int, double)> opening(String id) {- final r = fit.createRoutine('R');- fit.toggleRoutineExercise(r, id);- fit.startRoutine(fit.routines.firstWhere((x) => x.id == r));- final out = [- for (final s in fit.session!.exercises.single.sets.where((s) => s.kind != SetKind.warmup)) (s.reps, s.weight)- ];- fit.saveAndExit();- return out;- }-- void use(String id, ProgressRule r) => fit.setProgressRule(id, r);-- test('por defecto sigue siendo lineal y solo sugiere', () {- final id = bench();- expect(fit.progressRule(id).kind, ProgressKind.linear);- expect(fit.hasProgress(id), isFalse);- logged(id, 2, [LoggedSet(8, 60), LoggedSet(8, 60)]);- expect(fit.nextTarget(id)!.weightKg, 62.5);- expect(opening(id).first, (8, 60.0));- });-- test('elegir una estrategia la deja aplicándose sola', () {- final id = bench();- use(id, const ProgressRule(kind: ProgressKind.double));- expect(fit.hasProgress(id), isTrue);- expect(fit.progressFor(id), 2.5);- });-- test('manual: sin sugerencia y el peso tal cual', () {- final id = bench();- fit.toggleProgress(id);- use(id, const ProgressRule(kind: ProgressKind.manual));- logged(id, 2, [LoggedSet(8, 60), LoggedSet(8, 60)]);- expect(fit.hasProgress(id), isFalse);- expect(fit.nextTarget(id), isNull);- expect(opening(id).first, (8, 60.0));- });-- group('doble progresión 8–12', () {- setUp(() => use(bench(), const ProgressRule(kind: ProgressKind.double, low: 8, high: 12)));-- test('sin llegar al tope: mismo peso y una repe más en cada serie', () {- final id = bench();- logged(id, 2, [LoggedSet(10, 26), LoggedSet(9, 26), LoggedSet(8, 26)]);- final next = fit.nextTarget(id)!;- expect(next.move, NextMove.reps);- expect(next.weightKg, 26);- expect(opening(id), [(11, 26.0), (10, 26.0), (9, 26.0)]);- expect(fit.nextWhy(id), t.nextMoreReps);- expect(fit.nextTargetLabel(id), '26 kg × 11/10/9');- });-- test('las tres series a 12: sube el peso y vuelve a 8', () {- final id = bench();- logged(id, 2, [LoggedSet(12, 26), LoggedSet(12, 26), LoggedSet(12, 26)]);- expect(fit.nextTarget(id)!.move, NextMove.up);- expect(fit.nextTargetLabel(id), '28.5 kg × 8');- expect(opening(id), [(8, 28.5), (8, 28.5), (8, 28.5)]);- });-- test('nunca pide más del tope del rango', () {- final id = bench();- logged(id, 2, [LoggedSet(12, 26), LoggedSet(11, 26)]);- expect(opening(id).take(2), [(12, 26.0), (12, 26.0)]);- });-- test('estancado: sin sumar repes 3 veces seguidas, descarga', () {- final id = bench();- logged(id, 12, [LoggedSet(9, 60), LoggedSet(8, 60)]);- for (final d in [9, 6, 3]) {- logged(id, d, [LoggedSet(9, 60), LoggedSet(8, 60)]);- }- expect(fit.stallStreak(id), 3);- final next = fit.nextTarget(id)!;- expect(next.deload, isTrue);- expect(next.weightKg, 55);- expect(next.reps, 8);- });-- test('si sumas repes no cuenta como estancado', () {- final id = bench();- logged(id, 9, [LoggedSet(8, 60), LoggedSet(8, 60)]);- logged(id, 6, [LoggedSet(9, 60), LoggedSet(8, 60)]);- logged(id, 3, [LoggedSet(9, 60), LoggedSet(9, 60)]);- expect(fit.stallStreak(id), 0);- });- });-- group('repes, series y peso', () {- setUp(() => use(bench(), const ProgressRule(kind: ProgressKind.volume, low: 8, high: 12, sets: 2, maxSets: 3)));-- test('al tope con menos series del máximo: una serie más, vuelta a 8', () {- final id = bench();- logged(id, 2, [LoggedSet(12, 40), LoggedSet(12, 40)]);- expect(fit.nextTarget(id)!.move, NextMove.addSet);- expect(fit.nextTargetLabel(id), '3 × 40 kg × 8');- expect(opening(id), [(8, 40.0), (8, 40.0), (8, 40.0)]);- });-- test('al tope con todas las series: más peso y vuelta a las series de partida', () {- final id = bench();- logged(id, 2, [LoggedSet(12, 40), LoggedSet(12, 40), LoggedSet(12, 40)]);- expect(fit.nextTarget(id)!.move, NextMove.up);- expect(opening(id), [(8, 42.5), (8, 42.5)]);- });- });-- group('última serie a tope', () {- setUp(() => use(bench(), const ProgressRule(kind: ProgressKind.amrap)));-- test('elegirla descarga al primer fallo', () {- expect(fit.progressRule(bench()).fails, 1);- });-- test('cumplir sube un salto', () {- final id = bench();- logged(id, 2, [LoggedSet(5, 60), LoggedSet(5, 60), LoggedSet(7, 60)]);- expect(fit.nextTarget(id)!.weightKg, 62.5);- expect(opening(id), [(5, 62.5), (5, 62.5), (5, 62.5)]);- expect(fit.nextWhy(id), t.nextAmrap);- });-- test('doblar el objetivo en la última sube dos saltos', () {- final id = bench();- logged(id, 2, [LoggedSet(5, 60), LoggedSet(5, 60), LoggedSet(10, 60)]);- expect(fit.nextTarget(id)!.weightKg, 65);- });-- test('fallar descarga un 10 %', () {- final id = bench();- logged(id, 2, [LoggedSet(5, 60), LoggedSet(5, 60), LoggedSet(3, 60)]);- final next = fit.nextTarget(id)!;- expect(next.deload, isTrue);- expect(next.weightKg, 55);- });- });-- test('la descarga usa el porcentaje y los fallos elegidos', () {- final id = bench();- fit.toggleProgress(id);- use(id, fit.progressRule(id).copyWith(fails: 2, deloadPct: 20));- logged(id, 6, [LoggedSet(8, 100), LoggedSet(6, 100)]);- logged(id, 3, [LoggedSet(8, 100), LoggedSet(6, 100)]);- expect(fit.nextTarget(id)!.weightKg, 80);- });-- test('el rango no se cruza', () {- const r = ProgressRule(kind: ProgressKind.double, low: 8, high: 12);- expect(r.copyWith(low: 15).high, 16);- expect(r.copyWith(high: 3).high, 9);- expect(const ProgressRule(sets: 3, maxSets: 5).copyWith(sets: 6).maxSets, 7);- });-- test('se guarda en la copia y se borra con los datos', () async {- final id = bench();- use(id, const ProgressRule(kind: ProgressKind.volume, low: 6, high: 10, sets: 2, maxSets: 4));- fit.persistNow();- await pumpEventQueue();- fit.loadFromStore();- final r = fit.progressRule(id);- expect((r.kind, r.low, r.high, r.sets, r.maxSets), (ProgressKind.volume, 6, 10, 2, 4));- fit.resetAllData();- expect(fit.progressRule(id).kind, ProgressKind.linear);- });- });-- group('#247 completa tu día', () {- setUp(() {- fit.nutritionBeta = true;- fit.setAddBurned(false);- fit.setNutritionGoals(const NutritionGoals(kcal: 2000, protein: 150));- fit.setTracker(Tracker.protein, true);- });-- FoodItem chicken() =>- fit.saveFood(name: 'Pollo', grams: 100, macros: const Macros(kcal: 120, protein: 25, carbs: 0, fat: 2));- FoodItem rice() =>- fit.saveFood(name: 'Arroz', grams: 100, macros: const Macros(kcal: 350, protein: 7, carbs: 78, fat: 1));-- test('un alimento proteico cierra la proteína sin pasarse de kcal', () {- fit.logFood(fit.saveFood(name: 'Base', grams: 100, macros: const Macros(kcal: 1500, protein: 100, carbs: 150, fat: 50)));- expect(fit.fillGrams(chicken()), closeTo(200, 0.01));- });-- test('si las kcal se acaban antes, manda el tope de kcal', () {- fit.logFood(fit.saveFood(name: 'Base', grams: 100, macros: const Macros(kcal: 1880, protein: 60, carbs: 200, fat: 60)));- expect(fit.fillGrams(chicken()), closeTo(100, 0.01));- });-- test('un alimento con poca proteína solo rellena las kcal', () {- fit.logFood(fit.saveFood(name: 'Base', grams: 100, macros: const Macros(kcal: 1300, protein: 145, carbs: 100, fat: 40)));- expect(fit.fillGrams(rice()), closeTo(200, 0.01));- });-- test('sin kcal libres no propone nada', () {- fit.logFood(fit.saveFood(name: 'Base', grams: 100, macros: const Macros(kcal: 2100, protein: 100, carbs: 200, fat: 60)));- expect(fit.fillGrams(chicken()), isNull);- });-- test('al editar una entrada, su propia ración no cuenta como comida', () {- final e = fit.logFood(chicken(), servings: 2);- expect(fit.fillGrams(chicken(), replacing: e.total), closeTo(600, 0.01));- });-- test('te quedarán: resta lo que vas a apuntar', () {- fit.logFood(fit.saveFood(name: 'Base', grams: 100, macros: const Macros(kcal: 1000, protein: 50, carbs: 100, fat: 30)));- final left = fit.leftAfter(const Macros(kcal: 240, protein: 50, carbs: 0, fat: 4));- expect(left.kcal, 760);- expect(left.protein, 50);- });- });-- testWidgets('#251 arrastrar al borde de abajo desplaza la lista de la rutina', (tester) async {- await tester.binding.setSurfaceSize(const Size(400, 800));- addTearDown(() => tester.binding.setSurfaceSize(null));- final id = fit.createRoutine('Larga');- for (final ex in fit.allExercises.take(15)) {- fit.toggleRoutineExercise(id, ex.id);- }- fit.openRoutine(id);- await tester.pumpWidget(MaterialApp(- theme: AppTheme.dark,- home: AnimatedBuilder(- animation: fit,- builder: (_, _) => const Scaffold(body: RoutineEditScreen()),- ),- ));- await tester.pump(const Duration(seconds: 1));-- final handle = find.byType(ReorderableDragStartListener).first;- await tester.ensureVisible(handle);- await tester.pump(const Duration(milliseconds: 300));- final scroll = tester.state<ScrollableState>(find.byType(Scrollable).first).position;- final start = scroll.pixels;-- final drag = await tester.startGesture(tester.getCenter(handle));- await drag.moveBy(const Offset(0, 20));- await tester.pump(const Duration(milliseconds: 100));- await drag.moveTo(const Offset(200, 790));- for (var i = 0; i < 30; i++) {- await tester.pump(const Duration(milliseconds: 50));- }- expect(scroll.pixels, greaterThan(start + 100));- await drag.up();- await tester.pump(const Duration(seconds: 1));- });-}diff --git a/test/requests_23oct_test.dart b/test/requests_23oct_test.dartdeleted file mode 100644index 2d0caf4..0000000--- a/test/requests_23oct_test.dart+++ /dev/null@@ -1,153 +0,0 @@-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/catalog/exercise_catalog.dart';-import 'package:gymmane/l10n/l10n.dart';-import 'package:gymmane/models/profile.dart';-import 'package:gymmane/models/workout.dart';-import 'package:gymmane/services/local_store.dart';-import 'package:gymmane/services/plan_share.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.onboarded = true;- fit.setUnits('kg');- setAppLanguage('en');- });-- group('importar una rutina que ya tienes', () {- String own() {- final id = fit.createRoutine('Push');- fit.toggleRoutineExercise(id, fit.matchExerciseByName('Barbell Bench Press')!.id);- return fit.exportPlanJson(fit.routines);- }-- test('la vista previa sabe que ya la tienes', () {- final plans = parsePlan(own());- final preview = fit.previewPlan(plans);- expect(preview.routines, 1);- expect(preview.owned, 1);- expect(fit.ownsPlan(plans.single), isTrue);- });-- test('como copia se añade otra vez', () {- final plans = parsePlan(own());- expect(fit.applyPlan(plans).routines, 0);- expect(fit.applyPlan(plans, copies: true).routines, 1);- expect(fit.routines.length, 2);- });-- test('en otro móvil se importa normal', () {- final json = own();- fit.resetAllData();- final plans = parsePlan(json);- expect(fit.previewPlan(plans).owned, 0);- expect(fit.applyPlan(plans).routines, 1);- });- });-- group('#250 series cluster', () {- test('es un tipo de serie más y no rompe los guardados viejos', () {- expect(SetKind.values.last, SetKind.cluster);- expect(setKindFrom(SetKind.restPause.index), SetKind.restPause);- final back = LoggedSet.fromJson(LoggedSet(9, 80, kind: SetKind.cluster).toJson());- expect(back.kind, SetKind.cluster);- expect(back.counts, isTrue);- });-- test('viaja en el plan compartido', () {- final plans = parsePlan('{"name":"A","exercises":[{"name":"Barbell Full Squat",'- '"plan":[{"type":"cluster","reps":12,"weight":100}]}]}');- expect(plans.single.items.single.plan.single.kind, SetKind.cluster.index);- fit.applyPlan(plans);- final r = fit.routines.single;- expect(fit.exportPlanJson([r]), contains('"type": "cluster"'));- });- });-- group('deslizar para duplicar una serie', () {- test('la copia va justo debajo, sin marcar, y se puede deshacer', () {- fit.startWorkout();- fit.toggleMuscle('chest');- fit.trainContinue();- fit.startSession();- final sets = fit.session!.exercises.first.sets;- final before = sets.length;- fit.setSessionReps(0, 0, 7);- fit.setSessionWeight(0, 0, 42.5);- fit.toggleSet(0, 0);- final copy = fit.duplicateSet(0, 0)!;- expect(sets.length, before + 1);- expect(identical(sets[1], copy), isTrue);- expect(copy.done, isFalse);- expect((copy.reps, copy.weight), (7, 42.5));- fit.removeSetObject(0, copy);- expect(sets.length, before);- expect(sets.contains(copy), isFalse);- });- });-- group('fuerza relativa', () {- void lift(String name, int reps, double kg) {- final ex = fit.matchExerciseByName(name)!;- fit.sessions.add(LoggedSession(DateTime.now().subtract(const Duration(days: 2)), 1800,- [LoggedExercise(ex.id, ex.name, ex.primary, [LoggedSet(reps, kg)])]));- }-- test('press banca a 1,0× el peso es intermedio en hombre y muy avanzado en mujer', () {- fit.profile = Profile(weightKg: 80);- lift('Barbell Bench Press', 1, 80);- final id = fit.matchExerciseByName('Barbell Bench Press')!.id;- final rel = fit.relativeStrength(id)!;- expect(rel.ratio, closeTo(1.03, 0.01));- expect(rel.level, 1);- fit.profile = Profile(weightKg: 80, sex: 'female');- expect(fit.relativeStrength(id)!.level, 3);- });-- test('solo para los básicos y con marcas de los últimos 90 días', () {- lift('Dumbbell Biceps Curl', 10, 15);- expect(fit.relativeStrength(fit.matchExerciseByName('Dumbbell Biceps Curl')!.id), isNull);- final ex = fit.matchExerciseByName('Barbell Deadlift')!;- fit.sessions.add(LoggedSession(DateTime.now().subtract(const Duration(days: 200)), 1800,- [LoggedExercise(ex.id, ex.name, ex.primary, [LoggedSet(5, 140)])]));- expect(fit.relativeStrength(ex.id), isNull);- });- });-- group('ejercicios por zona', () {- test('piernas trae los de pierna primero y se limpia con el resto', () {- fit.setZoneFilter('Legs');- final list = fit.exercisesFiltered;- final legs = kBodyZones['Legs']!;- expect(list, isNotEmpty);- expect(legs.contains(list.first.primary), isTrue);- expect(list.every((e) => legs.contains(e.primary) || e.secondary.any(legs.contains)), isTrue);- expect(fit.zoneCount('Legs'), list.where((e) => legs.contains(e.primary)).length);- fit.setMuscleFilter('chest');- expect(fit.exZoneFilter, isNull);- fit.setZoneFilter('Arms');- expect(fit.exMuscleFilter, isNull);- fit.clearExFilters();- expect(fit.exZoneFilter, isNull);- });-- test('cada músculo del filtro cae en una zona', () {- final all = kBodyZones.values.expand((m) => m).toSet();- expect(all, containsAll(kFilterMuscles));- });- });-- test('#238 side bend: oblicuos primero', () {- for (final name in ['Dumbbell Side Bend', 'Weighted Side Bend (On Stability Ball)']) {- final ex = kExercises.firstWhere((e) => e.name == name);- expect(ex.primary, 'obliques');- expect(ex.secondary, ['abdomen']);- }- });-}diff --git a/test/requests_26oct_test.dart b/test/requests_26oct_test.dartdeleted file mode 100644index 4a928f0..0000000--- a/test/requests_26oct_test.dart+++ /dev/null@@ -1,97 +0,0 @@-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/models/nutrition.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.onboarded = true;- fit.setUnits('kg');- fit.autoAdvance = false;- });-- tearDown(() {- if (fit.session != null) fit.saveAndExit();- });-- group('#269 categoría en comidas propias', () {- test('se guarda, sobrevive a la copia y filtra la búsqueda', () {- final mine = fit.saveFood(name: 'Pollo marca X', grams: 100, macros: const Macros(kcal: 110), cat: FoodCat.meat);- fit.saveFood(name: 'Yogur', grams: 125, macros: const Macros(kcal: 80), cat: FoodCat.dairy);- fit.saveFood(name: 'Sin nada', macros: const Macros(kcal: 50));- expect(FoodItem.fromJson(mine.toJson()).cat, FoodCat.meat);- expect(fit.searchFoods('', cat: FoodCat.meat).map((f) => f.name), ['Pollo marca X']);- expect(fit.searchFoods(''), hasLength(3));- });-- test('editar puede cambiar o quitar la categoría', () {- final f = fit.saveFood(name: 'Pan', cat: FoodCat.bakery);- expect(fit.saveFood(id: f.id, name: 'Pan', cat: FoodCat.grain).cat, FoodCat.grain);- expect(fit.saveFood(id: f.id, name: 'Pan').cat, isNull);- });- });-- group('#271 RPE en el historial', () {- test('cada serie con esfuerzo lleva su etiqueta', () {- fit.setEffortMode('rpe');- final label = fit.setsSummary([LoggedSet(5, 100, rpe: 8), LoggedSet(5, 100)]);- expect(label, '${fit.loggedSetLabel(LoggedSet(5, 100))} @8 · ${fit.loggedSetLabel(LoggedSet(5, 100))}');- });- });-- group('#266 superserie sin rutina', () {- test('se encadena y se separa dentro de la sesión libre', () {- fit.startWorkout();- fit.toggleMuscle('chest');- fit.trainContinue();- fit.startSession();- fit.addExerciseToSession(fit.matchExerciseByName('Barbell Squat')!.id);- final s = fit.session!;- expect(s.routineId, isNull);- final last = s.exercises.length - 1;- fit.toggleSessionLink(last - 1);- expect(s.exercises[last - 1].linkedNext, isTrue);- fit.toggleSessionLink(last);- expect(s.exercises[last].linkedNext, isFalse);- fit.toggleSessionLink(last - 1);- expect(s.exercises[last - 1].linkedNext, isFalse);- });- });-- group('#272 pesos de cuarto de kilo', () {- test('61,25 no se redondea y lo raro sigue a un decimal', () {- expect(fit.weightValue(61.25), anyOf('61.25', '61,25'));- expect(fit.weightValue(61.33), anyOf('61.3', '61,3'));- expect(fit.weightValue(60), '60');- });-- test('la regla baja a 0,25 con saltos de 1,25', () {- fit.setWeightStep(1.25);- expect(fit.rulerStep, 0.25);- fit.setWeightStep(2.5);- expect(fit.rulerStep, 0.5);- });- });-- group('#273 comidas al futuro', () {- test('se puede mover una comida a mañana y ver ese día', () {- final food = fit.saveFood(name: 'Cena', macros: const Macros(kcal: 600));- final e = fit.logFood(food);- final now = DateTime.now();- final tomorrow = DateTime(now.year, now.month, now.day + 1);- fit.moveEntryToDay(e.id, tomorrow);- expect(fit.entriesOn(tomorrow).map((x) => x.id), [e.id]);- fit.setNutritionDay(tomorrow);- expect(fit.nutritionDay, tomorrow);- fit.setNutritionDay(DateTime(now.year, now.month, now.day + 30));- expect(fit.nutritionDay, DateTime(now.year, now.month, now.day + 7));- });- });-}diff --git a/test/requests_27sep_test.dart b/test/requests_27sep_test.dartdeleted file mode 100644index b69c13d..0000000--- a/test/requests_27sep_test.dart+++ /dev/null@@ -1,456 +0,0 @@-import 'package:flutter_test/flutter_test.dart';-import 'package:gymmane/catalog/exercise_catalog.dart';-import 'package:gymmane/l10n/l10n.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');- });-- tearDown(() {- if (fit.session != null) fit.saveAndExit();- });-- String idOf(String name) => fit.matchExerciseByName(name)!.id;-- Routine routineOf(List<String> names) {- final id = fit.createRoutine('Push');- for (final name in names) {- fit.toggleRoutineExercise(id, idOf(name));- }- return fit.routines.firstWhere((r) => r.id == id);- }-- LoggedSession logged(DateTime at, List<LoggedSet> sets, {String id = 'push', String primary = 'chest'}) =>- LoggedSession(at, 600, [LoggedExercise(id, id, primary, sets)]);-- group('#83 mapa de actividad', () {- test('un día de peso corporal se pinta', () {- fit.sessions.add(logged(DateTime.now(), [LoggedSet(15, 0), LoggedSet(12, 0)]));- expect(fit.heatmapLevels.last, greaterThan(0));- });-- test('un día marcado a mano también cuenta', () {- fit.toggleCheckin(fit.todayIndex);- expect(fit.heatmapLevels.last, greaterThan(0));- });- });-- group('#104 récords sin peso', () {- test('peso corporal: el récord son las repeticiones', () {- fit.sessions.add(logged(DateTime.now(), [LoggedSet(15, 0), LoggedSet(22, 0)]));- final pr = fit.personalRecords.single;- expect(pr.kind, PrKind.reps);- expect(pr.best, 22);- });-- test('isométrico: el récord es el tiempo', () {- fit.sessions.add(logged(DateTime.now(), [LoggedSet(0, 0, sec: 45), LoggedSet(0, 0, sec: 70)]));- final pr = fit.personalRecords.single;- expect(pr.kind, PrKind.time);- expect(fit.recordLabel(pr), isNot(contains('kg')));- });-- test('con peso manda el peso y va primero en la lista', () {- fit.sessions.add(logged(DateTime.now(), [LoggedSet(30, 0)], id: 'dips'));- fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 100)], id: 'bench'));- expect(fit.personalRecords.map((r) => r.id), ['bench', 'dips']);- expect(fit.personalRecords.first.kind, PrKind.weight);- });- });-- group('#92 inicio de semana', () {- test('empezar en domingo mueve toda la semana', () {- fit.setWeekStart(DateTime.sunday);- expect(fit.weekStartDate.weekday, DateTime.sunday);- expect(fit.weekdayAt(0), DateTime.sunday);- expect(fit.dateForWeekday(fit.todayIndex).day, DateTime.now().day);- });-- test('se guarda con el resto de ajustes', () {- fit.setWeekStart(DateTime.saturday);- expect(fit.toJson()['weekStart'], DateTime.saturday);- fit.setWeekStart(4);- expect(fit.weekStartDay, DateTime.saturday, reason: 'solo lunes, sábado o domingo');- });- });-- group('#117 objetivo semanal por días', () {- test('dos sesiones el mismo día son un día', () {- fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 60)]));- fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 60)]));- expect(fit.daysDoneThisWeek, 1);- });-- test('marcar y desmarcar un día lo deja como estaba', () {- final before = fit.daysDoneThisWeek;- fit.toggleCheckin(fit.todayIndex);- expect(fit.daysDoneThisWeek, before + 1);- fit.toggleCheckin(fit.todayIndex);- expect(fit.daysDoneThisWeek, before);- expect(fit.currentStreak, 0);- });- });-- group('#122 salir del entreno', () {- test('salir pausa y deja volver donde estabas', () {- fit.startRoutine(routineOf(['Barbell Bench Press']));- fit.endCountdown();- fit.stepOutOfSession();- expect(fit.route, 'home');- expect(fit.sessionPaused, isTrue);- expect(fit.sessionParked, isTrue);-- fit.stepBackIntoSession();- expect(fit.route, 'session');- expect(fit.sessionPaused, isFalse);- });-- test('empezar otra cosa con uno aparcado vuelve al aparcado', () {- fit.startRoutine(routineOf(['Barbell Bench Press']));- fit.endCountdown();- final session = fit.session;- fit.stepOutOfSession();- fit.startRoutine(routineOf(['Barbell Squat']));- expect(fit.session, same(session));- expect(fit.route, 'session');- });- });-- group('#102 guardar la rutina', () {- test('sin cambios no hay nada que guardar', () {- fit.startRoutine(routineOf(['Barbell Bench Press']));- expect(fit.sessionRoutine, isNotNull);- expect(fit.sessionEditedRoutine, isFalse);- });-- test('añadir un ejercicio se puede llevar a la rutina', () {- final r = routineOf(['Barbell Bench Press']);- fit.startRoutine(r);- fit.addExerciseToSession(idOf('Barbell Squat'));- expect(fit.sessionEditedRoutine, isTrue);-- fit.saveSessionIntoRoutine();- expect(r.exerciseIds, [idOf('Barbell Bench Press'), idOf('Barbell Squat')]);- expect(fit.sessionEditedRoutine, isFalse);- });-- test('los cambios se enseñan antes de guardarlos', () {- final r = routineOf(['Barbell Bench Press', 'Barbell Squat', 'Barbell Deadlift']);- fit.startRoutine(r);- fit.removeSessionExercise(2);- fit.addExerciseToSession(idOf('Barbell Curl'));- fit.reorderSessionExercise(2, 0);- final changes = fit.sessionRoutineChanges;- expect(changes.added.map((e) => e.id), [idOf('Barbell Curl')]);- expect(changes.removed.map((e) => e.id), [idOf('Barbell Deadlift')]);- expect(changes.reordered, isTrue);- expect(r.exerciseIds, hasLength(3), reason: 'nada cambia hasta aceptar');- });-- test('una sesión suelta se guarda con el nombre elegido', () {- fit.startRoutine(routineOf(['Barbell Bench Press']));- fit.session!.routineId = null;- final id = fit.saveSessionAsRoutine('Pecho');- expect(fit.routines.firstWhere((r) => r.id == id).name, 'Pecho');- expect(fit.sessionRoutine?.id, id, reason: 'el botón no vuelve a salir');- });- });-- group('#115 sin material', () {- tearDown(fit.clearExFilters);-- test('no enseña lo que necesita barra', () {- fit.toggleNoGearFilter();- final ids = fit.exercisesMatching('').map((e) => e.id).toSet();- expect(ids, isNot(contains(idOf('Pull-up'))));- expect(ids, isNot(contains('seal-jack')), reason: 'su dibujo es una estación de fondos');- expect(ids, isNot(contains('outdoor-run')), reason: 'el dibujo es una cinta');- expect(ids, contains(idOf('Push-up')));- });-- test('elegir material lo apaga y al revés', () {- fit.toggleNoGearFilter();- fit.setEquipmentFilter('Barbell');- expect(fit.exNoGearOnly, isFalse);- fit.toggleNoGearFilter();- expect(fit.exEquipmentFilter, isNull);- });- });-- test('#89 solo los creados por ti', () {- final id = fit.addCustomExercise(name: 'Mi press', primary: 'chest', equipment: 'Dumbbell');- fit.toggleMineFilter();- expect(fit.exercisesMatching('').map((e) => e.id), [id]);- fit.clearExFilters();- });-- group('#120 calentamiento y #106 cardio', () {- test('los ejercicios sin peso también calientan', () {- fit.startRoutine(routineOf(['Push-up']));- fit.addWarmupSets(0);- expect(fit.hasWarmup(0), isTrue);- });-- test('el calentamiento propone movilidad y el cardio solo cardio', () {- fit.startWorkout();- fit.startKindWorkout('warmup');- expect(fit.sessionPicks, isNotEmpty);- expect(fit.reviewExercises().where((e) => const ['Machine', 'Cable'].contains(e.equipment)), isEmpty);- fit.startKindWorkout('cardio');- final cardio = fit.reviewExercises().map((e) => e.id).toSet();- expect(cardio, containsAll(['skierg', 'battle-ropes', 'running']));- expect(cardio.every((id) => fit.isCardio(id) || kCardioExtras.contains(id)), isTrue);- fit.closeTrain();- });- });-- group('#119 archivar', () {- test('un archivado desaparece de todo y vuelve al restaurarlo', () {- final id = idOf('Pull-up');- fit.toggleArchived(id);- expect(fit.exercisesMatching('').map((e) => e.id), isNot(contains(id)));- expect(fit.trainSearchResults('pull').map((e) => e.id), isNot(contains(id)));- expect(fit.getFilteredExercises(['back']).map((e) => e.id), isNot(contains(id)));- expect(fit.recommendedExercises(40).map((e) => e.id), isNot(contains(id)));-- fit.toggleArchivedFilter();- expect(fit.exercisesMatching('').map((e) => e.id), [id]);-- fit.toggleArchived(id);- expect(fit.exArchivedOnly, isFalse, reason: 'sin archivados el filtro se apaga');- expect(fit.exercisesMatching('').map((e) => e.id), contains(id));- });-- test('se guarda en la copia', () {- fit.toggleArchived(idOf('Pull-up'));- expect(fit.toJson()['archived'], [idOf('Pull-up')]);- });- });-- test('#95 los recomendados se pueden quitar y se guarda', () {- expect(fit.showRecommended, isTrue);- fit.toggleRecommended();- expect(fit.toJson()['showRecs'], isFalse);- });-- test('#111 las marcas del vídeo se guardan y se van con el vídeo', () {- final id = idOf('Barbell Bench Press');- fit.setVideoMark(id, 1, 40000);- expect(fit.videoMark(id, 1), 40000);- expect(fit.toJson()['marks'], {id: {'1': 40000}});- fit.setVideoMark(id, 1, null);- expect(fit.videoMarks, isEmpty);- fit.setVideoMark(id, 0, 1000);- fit.clearExerciseMedia(id);- expect(fit.videoMark(id, 0), isNull);- });-- group('#86 varias rutinas al día', () {- test('apagado, un día solo tiene una rutina', () {- final a = routineOf(['Barbell Bench Press']);- final b = routineOf(['Barbell Squat']);- final today = DateTime.now().weekday;- fit.togglePlanDay(today, a.id);- fit.togglePlanDay(today, b.id);- expect(fit.planIdsOn(today), [b.id]);- });-- test('encendido, van en orden y el día acaba cuando se hacen todas', () {- fit.toggleMultiPlan();- final a = routineOf(['Barbell Bench Press']);- final b = routineOf(['Barbell Squat']);- final today = DateTime.now().weekday;- fit.togglePlanDay(today, a.id);- fit.togglePlanDay(today, b.id);- expect(fit.todayRoutine, same(a));- expect(fit.todayPlanDone, isFalse);-- fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 60)]));- expect(fit.todayRoutine, same(b));- expect(fit.todayPlanDone, isFalse);-- fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 100)]));- expect(fit.todayPlanDone, isTrue);- });-- test('#157 repetir una rutina no cuenta como hacer la otra', () {- fit.toggleMultiPlan();- final a = routineOf(['Barbell Bench Press']);- final b = routineOf(['Barbell Squat']);- final c = routineOf(['Barbell Deadlift']);- final today = DateTime.now().weekday;- fit.togglePlanDay(today, a.id);- fit.togglePlanDay(today, b.id);- LoggedSession done(String id) => LoggedSession(DateTime.now(), 1800, const [], routineId: id);-- fit.sessions.add(done(a.id));- fit.sessions.add(done(a.id));- fit.sessions.add(done(c.id));- expect(fit.todayPlanDone, isFalse);- expect(fit.todayRoutine, same(b));-- fit.sessions.add(done(b.id));- expect(fit.todayPlanDone, isTrue);- expect(LoggedSession.fromJson(done(b.id).toJson()).routineId, b.id);- });-- test('#156 al acabar una rutina ofrece la siguiente del día', () {- fit.toggleMultiPlan();- final a = routineOf(['Barbell Bench Press']);- final b = routineOf(['Barbell Squat']);- final today = DateTime.now().weekday;- fit.togglePlanDay(today, a.id);- fit.togglePlanDay(today, b.id);-- fit.startRoutine(a);- fit.toggleSet(0, 0);- fit.finishSession();- expect(fit.sessions.last.routineId, a.id);- expect(fit.nextRoutineToday, same(b));-- fit.startNextRoutine();- expect(fit.session?.routineId, b.id);- expect(fit.session?.complete, isFalse);- fit.toggleSet(0, 0);- fit.finishSession();- expect(fit.nextRoutineToday, isNull);- expect(fit.todayPlanDone, isTrue);- });-- test('#157 hacer la segunda primero deja pendiente la primera', () {- fit.toggleMultiPlan();- final a = routineOf(['Barbell Bench Press']);- final b = routineOf(['Barbell Squat']);- final today = DateTime.now().weekday;- fit.togglePlanDay(today, a.id);- fit.togglePlanDay(today, b.id);- fit.sessions.add(LoggedSession(DateTime.now(), 1800, const [], routineId: b.id));- expect(fit.todayRoutine, same(a));- expect(fit.todayPlanDone, isFalse);- });-- test('borrar la primera deja la segunda y se guarda', () {- fit.toggleMultiPlan();- final a = routineOf(['Barbell Bench Press']);- final b = routineOf(['Barbell Squat']);- final c = routineOf(['Barbell Deadlift']);- fit.togglePlanDay(1, a.id);- fit.togglePlanDay(1, b.id);- fit.togglePlanDay(1, c.id);- fit.deleteRoutine(a.id);- expect(fit.planIdsOn(1), [b.id, c.id]);- expect(fit.toJson()['planExtras'], {'1': [c.id]});- fit.toggleMultiPlan();- expect(fit.planIdsOn(1), [b.id], reason: 'apagado se ignoran las extra');- });- });-- group('texto para la IA', () {- test('un usuario nuevo pide empezar suave y que le pregunten', () {- final text = fit.planRequestText();- expect(text, contains(t.planNoHistory));- expect(text, contains(t.planAskFirst));- expect(text, contains(t.planDays(fit.weeklyTarget)));- });-- test('con historial lleva los entrenos y las mejores series', () {- fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 100)], id: idOf('Barbell Bench Press')));- final text = fit.planRequestText();- expect(text, isNot(contains(t.planNoHistory)));- expect(text, contains(t.planHistory(1)));- expect(text, contains(t.planBestLifts));- });- });-- group('#107 entreno pasado con su hora', () {- test('la hora y la duración elegidas llegan al historial', () {- final day = DateTime.now().subtract(const Duration(days: 2));- fit.startRoutine(routineOf(['Barbell Bench Press']), on: day);- fit.setManualStart(18 * 60 + 30);- fit.setManualMinutes(45);- fit.stepOutOfSession();- fit.stepBackIntoSession();- expect(fit.manualMinutes, 45, reason: 'salir y volver no toca la duración');- fit.toggleSet(0, 0);- fit.finishSession();- final s = fit.sessions.last;- expect(s.durationSec, 45 * 60);- expect(s.date, DateTime(day.year, day.month, day.day, 19, 15));- });- });-- group('#99 músculos secundarios propios', () {- test('se guardan, viajan en la copia y cuentan en las series', () {- final id = fit.addCustomExercise(- name: 'Thruster', primary: 'quads', equipment: 'Dumbbell', secondary: ['shoulders', 'quads', 'triceps']);- final ex = fit.exerciseById(id)!;- expect(ex.secondary, ['shoulders', 'triceps'], reason: 'sin repetir el principal');- final json = ex.toJson();- expect(json['s'], ['shoulders', 'triceps']);- fit.sessions.add(logged(DateTime.now(), [LoggedSet(8, 20), LoggedSet(8, 20)], id: id, primary: 'quads'));- expect(fit.muscleSetsOver(7)['shoulders'], 1);- });- });-- group('#88 pausar el temporizador', () {- test('pausar guarda lo que queda y terminar ya marca la serie', () {- fit.startRoutine(routineOf(['Plank']));- fit.endCountdown();- fit.setExerciseMode(idOf('Plank'), 'time');- fit.startHold(0, 0);- final lead = fit.holdLead;- fit.toggleHoldPause();- expect(fit.holdPaused, isTrue);- expect(fit.holdLead, lead);- fit.toggleHoldPause();- expect(fit.holdPaused, isFalse);- fit.toggleHoldPause();- fit.completeHold();- expect(fit.session!.exercises.first.sets.first.done, isTrue);- expect(fit.holding, isFalse);- });- });-- test('#105 las notas de un ejercicio se abren en lista y atrás vuelve', () {- fit.openExercise(idOf('Plank'));- fit.goNotes(exerciseId: idOf('Plank'), all: true);- expect(fit.notesAllView, isTrue);- fit.backFromNotes();- expect(fit.route, 'exercise-detail');- });-- test('#125 la prensa usa su propio carro en la calculadora', () {- final press = idOf('Leg Press');- expect(fit.plateHint('Machine', 150, id: press), isNull);- fit.setExerciseBar(press, 50);- expect(fit.plateHint('Machine', 150, id: press), '25×2');- expect(fit.toJson()['barKg'], {press: 50.0});- });-- group('#85 racha con calendario', () {- test('un día sin rutina no rompe la racha', () {- final today = DateTime.now();- final yesterday = DateTime(today.year, today.month, today.day - 1);- final before = DateTime(today.year, today.month, today.day - 2, 18);- fit.sessions.add(logged(today, [LoggedSet(5, 60)]));- fit.sessions.add(logged(before, [LoggedSet(5, 60)]));- expect(fit.currentStreak, 1);-- final r = routineOf(['Barbell Bench Press']);- for (var d = 1; d <= 7; d++) {- if (d != yesterday.weekday) fit.assignRoutineToDay(d, r.id);- }- expect(fit.currentStreak, 2);- });- });-}diff --git a/test/requests_29sep_test.dart b/test/requests_29sep_test.dartdeleted file mode 100644index 06bd6bd..0000000--- a/test/requests_29sep_test.dart+++ /dev/null@@ -1,91 +0,0 @@-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.resetAllData();- fit.setUnits('kg');- });-- const bench = 'EIeI8Vf';-- LoggedSession logged(DateTime at, List<LoggedSet> sets, {String id = bench}) =>- LoggedSession(at, 1800, [LoggedExercise(id, 'Barbell Bench Press', 'chest', sets)]);-- group('#138 una semana por columna', () {- test('cada columna empieza el primer día de la semana y hoy cae en su fila', () {- for (final start in [DateTime.monday, DateTime.sunday]) {- fit.setWeekStart(start);- final cells = fit.heatmapWeeks;- expect(cells.length % 7, 0);- expect(fit.heatmapWeekDate(0).weekday, start);- final today = DateTime.now();- final i = cells.length - 7 + fit.todayIndex;- final d = fit.heatmapWeekDate(i);- expect((d.year, d.month, d.day), (today.year, today.month, today.day));- expect(cells.skip(i + 1).every((l) => l == -1), isTrue);- }- });-- test('un entreno de hoy se pinta en la casilla de hoy', () {- fit.sessions.add(logged(DateTime.now(), [LoggedSet(8, 60)]));- final cells = fit.heatmapWeeks;- expect(cells[cells.length - 7 + fit.todayIndex], greaterThan(0));- });-- test('los días y meses vienen encendidos y apagarlos se guarda', () {- expect(fit.heatmapLabels, isTrue);- fit.toggleHeatmapLabels();- fit.persistNow();- fit.loadFromStore();- expect(fit.heatmapLabels, isFalse);- });- });-- group('#127 ideas de FitNotes', () {- test('el objetivo mide el mejor peso y se guarda con su fecha', () {- fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 100), LoggedSet(3, 110)]));- final due = DateTime.now().add(const Duration(days: 30));- fit.setExerciseGoal(bench, 140, due);- expect(fit.goalBest(bench), 110);- fit.persistNow();- fit.loadFromStore();- final g = fit.exerciseGoals[bench]!;- expect(g.target, 140);- expect((g.due!.year, g.due!.month, g.due!.day), (due.year, due.month, due.day));- fit.clearExerciseGoal(bench);- expect(fit.exerciseGoals, isEmpty);- });-- test('el objetivo de un ejercicio sin peso va en repeticiones', () {- fit.sessions.add(logged(DateTime.now(), [LoggedSet(12, 0)], id: 'I4hDWkc'));- expect(fit.goalKind('I4hDWkc'), PrKind.reps);- expect(fit.goalBest('I4hDWkc'), 12);- });-- test('el entreno se copia como texto con sus series y totales', () {- final s = logged(DateTime(2026, 9, 29, 18), [LoggedSet(8, 60), LoggedSet(6, 70)]);- final text = fit.workoutText(s);- expect(text, contains('60 kg × 8'));- expect(text, contains('70 kg × 6'));- expect(text, contains('30 min'));- expect(text.split('\n').last, contains('14'));- });-- test('el porcentaje del máximo da un peso que se puede cargar', () {- fit.bumpRmWeight(100 - fit.rmWeight);- fit.bumpRmReps(1 - fit.rmReps);- fit.bumpRmPct(72 - fit.rmPct);- final w = fit.rmAtPct;- expect((w - 72.6).abs(), lessThan(2.6));- expect(w % 1.25, closeTo(0, 1e-9));- });- });-}diff --git a/test/rest_timer_test.dart b/test/rest_timer_test.dartnew file mode 100644index 0000000..0550a97--- /dev/null+++ b/test/rest_timer_test.dart@@ -0,0 +1,133 @@+import 'dart:convert';+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();++ group('#204 descanso a mano', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ Routine routineOf(List<String> ids) {+ final id = fit.createRoutine('Core');+ for (final ex in ids) {+ fit.toggleRoutineExercise(id, ex);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ void rest() {+ final bench = fit.matchExerciseByName('Bench Press')!.id;+ fit.startRoutine(routineOf([bench]));+ fit.endCountdown();+ fit.toggleSet(0, 0);+ expect(fit.session!.restRemaining, isNotNull);+ }++ test('fija el descanso al tiempo elegido', () {+ rest();+ fit.setRest(200);+ expect(fit.restTotal, 200);+ expect(fit.session!.restRemaining, inInclusiveRange(199, 200));+ fit.skipRest();+ });++ test('cero lo salta y el tope es de diez minutos', () {+ rest();+ fit.setRest(5000);+ expect(fit.session!.restRemaining, inInclusiveRange(599, 600));+ fit.setRest(0);+ expect(fit.session!.restRemaining, isNull);+ });++ test('con la sesión en pausa se queda congelado en el tiempo nuevo', () {+ rest();+ fit.toggleSessionPause();+ fit.setRest(90);+ expect(fit.session!.restFrozen, 90);+ expect(fit.session!.restRemaining, 90);+ fit.toggleSessionPause();+ expect(fit.session!.restRemaining, inInclusiveRange(89, 90));+ fit.skipRest();+ });+ });++ group('descanso', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ Routine routine(String name, [List<String>? ids]) {+ final id = fit.createRoutine(name);+ for (final e in ids ?? [bench()]) {+ fit.toggleRoutineExercise(id, e);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ test('quitar segundos baja la barra y sumar la alarga', () {+ final r = routine('A');+ fit.setRoutineRest(r.id, bench(), 120);+ fit.startRoutine(r);+ fit.endCountdown();+ fit.toggleSet(0, 0);+ expect(fit.restTotal, 120);+ fit.nudgeRest(-15);+ fit.nudgeRest(-15);+ expect(fit.restTotal, 120);+ expect(fit.session!.restRemaining, lessThanOrEqualTo(90));+ fit.nudgeRest(60);+ expect(fit.restTotal, greaterThanOrEqualTo(fit.session!.restRemaining!));+ fit.skipRest();+ });++ test('cuando el aviso nativo dice que acabó, se cierra el descanso', () {+ final r = routine('A');+ fit.startRoutine(r);+ fit.endCountdown();+ fit.toggleSet(0, 0);+ final s = fit.session!;+ s.restEndsAt = DateTime.now().subtract(const Duration(seconds: 1));+ final tick = fit.restDoneTick;+ fit.restElapsed();+ expect(s.restEndsAt, isNull);+ expect(fit.restDoneTick, tick + 1);+ fit.restElapsed();+ expect(fit.restDoneTick, tick + 1);+ });+ });++ group('#218 segundo aviso', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ test('solo acepta las opciones de la hoja y se guarda', () {+ expect(fit.trainAgainMin, 0);+ fit.setTrainAgain(45);+ expect(fit.trainAgainMin, 0);+ fit.setTrainAgain(120);+ final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;+ fit.resetAllData();+ expect(fit.trainAgainMin, 0);+ fit.applyBackup(data);+ expect(fit.trainAgainMin, 120);+ });+ });+}diff --git a/test/rotation_test.dart b/test/rotation_test.dartnew file mode 100644index 0000000..e93ea8b--- /dev/null+++ b/test/rotation_test.dart@@ -0,0 +1,221 @@+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();++ group('rotación', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ Routine routine(String name) {+ final id = fit.createRoutine(name);+ fit.toggleRoutineExercise(id, bench());+ return fit.routines.firstWhere((r) => r.id == id);+ }++ void train(Routine r, {DateTime? on}) {+ fit.startRoutine(r, on: on);+ fit.endCountdown();+ fit.toggleSet(0, 0);+ fit.finishSession();+ }++ DateTime day(int offset) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day + offset, 10);+ }++ test('la siguiente es la que sigue a la última, sin mirar el día', () {+ final a = routine('A'), b = routine('B'), c = routine('C');+ fit.setRotation(true);+ for (final r in [a, b, c]) {+ fit.toggleRotationRoutine(r.id);+ }+ expect(fit.rotating, isTrue);+ expect(fit.todayRoutine?.id, a.id);+ expect(fit.routinesOn(day(3)).single.id, a.id);++ train(a);+ expect(fit.rotationNext?.id, b.id);+ expect(fit.rotationStep, 1);+ expect(fit.todayPlanDone, isTrue);+ expect(fit.routinesOn(day(1)).single.id, b.id);++ fit.skipRotation();+ expect(fit.rotationNext?.id, c.id);+ fit.restartRotation();+ expect(fit.rotationNext?.id, a.id);+ });++ test('al terminar la última vuelve a la primera', () {+ final a = routine('A'), b = routine('B');+ fit.setRotation(true);+ fit.toggleRotationRoutine(a.id);+ fit.toggleRotationRoutine(b.id);+ fit.setRotationNext(b.id);+ train(b);+ expect(fit.rotationNext?.id, a.id);+ expect(fit.rotationStep, 0);+ });++ test('se guarda, y borrar una rutina pasa a la siguiente', () {+ final a = routine('A'), b = routine('B'), c = routine('C');+ fit.setRotation(true);+ for (final r in [a, b, c]) {+ fit.toggleRotationRoutine(r.id);+ }+ fit.setRotationNext(b.id);+ fit.reorderRotation(2, 0);+ expect(fit.rotationIds, [c.id, a.id, b.id]);++ fit.persistNow();+ fit.rotationIds.clear();+ fit.rotation = false;+ fit.loadFromStore();+ expect(fit.rotating, isTrue);+ expect(fit.rotationIds, [c.id, a.id, b.id]);+ expect(fit.rotationNext?.id, b.id);++ fit.deleteRoutine(b.id);+ expect(fit.rotationIds, [c.id, a.id]);+ expect(fit.rotationNext?.id, c.id);+ });++ test('al encenderla se llena con el plan semanal y al apagarla vuelve la semana', () {+ final a = routine('A'), b = routine('B');+ fit.assignRoutineToDay(DateTime.monday, a.id);+ fit.assignRoutineToDay(DateTime.thursday, b.id);+ fit.setRotation(true);+ expect(fit.rotationIds, [a.id, b.id]);+ fit.setRotation(false);+ expect(fit.weeklyPlan[DateTime.monday], a.id);+ expect(fit.weeklyPlan[DateTime.thursday], b.id);+ });+ });++ group('rotación a fondo', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ Routine routine(String name, [List<String>? ids]) {+ final id = fit.createRoutine(name);+ for (final e in ids ?? [bench()]) {+ fit.toggleRoutineExercise(id, e);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ void train(Routine r) {+ fit.startRoutine(r);+ fit.endCountdown();+ fit.toggleSet(0, 0);+ fit.finishSession();+ }++ void close() => fit.saveAndExit();++ DateTime day(int offset, [int hour = 10]) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day + offset, hour);+ }++ Routine rotate(List<Routine> list) {+ fit.setRotation(true);+ for (final r in list) {+ if (!fit.rotationIds.contains(r.id)) fit.toggleRotationRoutine(r.id);+ }+ return list.first;+ }++ test('A, B, C seguidas en días distintos dan la vuelta entera', () {+ final a = routine('A'), b = routine('B'), c = routine('C');+ rotate([a, b, c]);+ final seen = <String>[];+ for (var i = 0; i < 4; i++) {+ final next = fit.rotationNext!;+ seen.add(next.name);+ train(next);+ close();+ }+ expect(seen, ['A', 'B', 'C', 'A']);+ expect(fit.rotationNext?.id, b.id);+ });++ test('hoy enseña la hecha y mañana la siguiente', () {+ final a = routine('A'), b = routine('B');+ rotate([a, b]);+ train(a);+ close();+ expect(fit.routinesOn(DateTime.now()).single.id, a.id);+ expect(fit.pendingRoutinesOn(DateTime.now()), isEmpty);+ expect(fit.routinesOn(day(1)).single.id, b.id);+ expect(fit.routinesOn(day(-1)), isEmpty);+ });++ test('una rutina fuera de la rotación no la mueve', () {+ final a = routine('A'), b = routine('B'), x = routine('X');+ rotate([a, b]);+ train(x);+ close();+ expect(fit.rotationNext?.id, a.id);+ });++ test('hacer la B cuando tocaba la A salta a la C', () {+ final a = routine('A'), b = routine('B'), c = routine('C');+ rotate([a, b, c]);+ train(b);+ close();+ expect(fit.rotationNext?.id, c.id);+ });++ test('volver al entreno desde el resumen no avanza dos veces', () {+ final a = routine('A'), b = routine('B'), c = routine('C');+ rotate([a, b, c]);+ train(a);+ expect(fit.rotationNext?.id, b.id);+ fit.continueSession();+ expect(fit.rotationNext?.id, a.id);+ fit.finishSession();+ expect(fit.rotationNext?.id, b.id);+ close();+ expect(fit.sessions.length, 1);+ });++ test('quitar la que tocaba pasa a la primera y vaciarla vuelve a la semana', () {+ final a = routine('A'), b = routine('B');+ fit.assignRoutineToDay(DateTime.now().weekday, a.id);+ rotate([a, b]);+ fit.setRotationNext(b.id);+ fit.toggleRotationRoutine(b.id);+ expect(fit.rotationNext?.id, a.id);+ fit.toggleRotationRoutine(a.id);+ expect(fit.rotating, isFalse);+ expect(fit.routinesOn(DateTime.now()).single.id, a.id);+ });++ test('nada de rutinas vacías ni ids sueltos al cargar', () {+ final a = routine('A'), b = routine('B');+ rotate([a, b]);+ fit.rotationIds.add('no-existe');+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.rotationRoutines.map((r) => r.id), [a.id, b.id]);+ });+ });+}diff --git a/test/routines_test.dart b/test/routines_test.dartnew file mode 100644index 0000000..240421f--- /dev/null+++ b/test/routines_test.dart@@ -0,0 +1,413 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/catalog/program_templates.dart';+import 'package:gymmane/l10n/l10n.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();++ group('planned routines', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineWith(List<String> ids, {String name = 'Push'}) {+ final id = fit.createRoutine(name);+ for (final ex in ids) {+ fit.toggleRoutineExercise(id, ex);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ test('planned sets open the workout with their type, reps and weight', () {+ final bench = idOf('Barbell Bench Press');+ final r = routineWith([bench]);+ fit.setPlannedSets(r.id, bench, const [+ PlannedSet(reps: 12, weightKg: 30, kind: SetKind.warmup),+ PlannedSet(reps: 8, weightKg: 70),+ PlannedSet(reps: 6, weightKg: 75, kind: SetKind.drop),+ ]);+ expect(fit.routineSets(r, bench), 2);+ fit.startRoutine(r);+ final sets = fit.session!.exercises.single.sets;+ expect(sets.map((s) => s.kind), [SetKind.warmup, SetKind.normal, SetKind.drop]);+ expect(sets.map((s) => s.reps), [12, 8, 6]);+ expect(sets.map((s) => s.weight), [30, 70, 75]);+ });++ test('the set stepper grows and shrinks the plan, never below one working set', () {+ final bench = idOf('Barbell Bench Press');+ final r = routineWith([bench]);+ fit.setPlannedSets(r.id, bench, const [+ PlannedSet(kind: SetKind.warmup),+ PlannedSet(reps: 5, weightKg: 100),+ ]);+ fit.bumpRoutineSets(r.id, bench, 2);+ expect(fit.routineSets(r, bench), 3);+ expect(fit.plannedSets(r, bench).last.weightKg, 100);+ fit.bumpRoutineSets(r.id, bench, -5);+ expect(fit.routineSets(r, bench), 1);+ expect(fit.plannedSets(r, bench).first.kind, SetKind.warmup);+ });++ test('a finished workout saved as routine keeps its sets and supersets', () {+ final ids = [idOf('Barbell Bench Press'), idOf('Barbell Bent Over Row')];+ final r = routineWith(ids);+ fit.toggleChain(r.id, ids.first);+ fit.startRoutine(r);+ fit.setSessionWeight(0, 0, 62.5);+ final saved = fit.saveSessionAsRoutine('Copy');+ final made = fit.routines.firstWhere((x) => x.id == saved);+ expect(made.chained, contains(ids.first));+ expect(fit.plannedSets(made, ids.first).first.weightKg, 62.5);+ });+ });++ group('#212 series añadidas en la rutina', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ String squat() => fit.matchExerciseByName('Barbell Squat')!.id;++ Routine routine(String name, [List<String>? ids]) {+ final id = fit.createRoutine(name);+ for (final e in ids ?? [bench()]) {+ fit.toggleRoutineExercise(id, e);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ void train(Routine r) {+ fit.startRoutine(r);+ fit.endCountdown();+ fit.toggleSet(0, 0);+ fit.finishSession();+ }++ test('añadir una serie se ofrece guardar y queda en la rutina', () {+ final r = routine('A', [bench(), squat()]);+ expect(fit.routineSets(r, bench()), 3);+ fit.startRoutine(r);+ fit.endCountdown();+ fit.addSet(0);+ fit.removeSet(1, 2);+ fit.toggleSet(0, 0);+ fit.finishSession();+ expect(fit.sessionEditedRoutine, isTrue);+ final changes = fit.sessionRoutineChanges;+ expect(changes.added, isEmpty);+ expect([for (final c in changes.sets) (c.ex.id, c.from, c.to)], [(bench(), 3, 4), (squat(), 3, 2)]);+ fit.saveSessionIntoRoutine();+ expect(fit.routineSets(r, bench()), 4);+ expect(fit.routineSets(r, squat()), 2);+ expect(fit.sessionEditedRoutine, isFalse);+ });++ test('con series planificadas copia la última', () {+ final r = routine('A');+ fit.setPlannedSets(r.id, bench(), const [+ PlannedSet(kind: SetKind.warmup, reps: 10),+ PlannedSet(reps: 8, weightKg: 60),+ PlannedSet(reps: 6, weightKg: 70),+ ]);+ fit.startRoutine(r);+ fit.endCountdown();+ fit.addSet(0);+ fit.toggleSet(0, 0);+ fit.finishSession();+ fit.saveSessionIntoRoutine();+ final plan = fit.plannedSets(r, bench());+ expect(plan.length, 4);+ expect(plan.first.kind, SetKind.warmup);+ expect(plan.last.reps, 6);+ expect(plan.last.weightKg, 70);+ });++ test('sin cambios no molesta', () {+ final r = routine('A');+ train(r);+ expect(fit.sessionEditedRoutine, isFalse);+ });+ });++ group('#102 guardar la rutina', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineOf(List<String> names) {+ final id = fit.createRoutine('Push');+ for (final name in names) {+ fit.toggleRoutineExercise(id, idOf(name));+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ test('sin cambios no hay nada que guardar', () {+ fit.startRoutine(routineOf(['Barbell Bench Press']));+ expect(fit.sessionRoutine, isNotNull);+ expect(fit.sessionEditedRoutine, isFalse);+ });++ test('añadir un ejercicio se puede llevar a la rutina', () {+ final r = routineOf(['Barbell Bench Press']);+ fit.startRoutine(r);+ fit.addExerciseToSession(idOf('Barbell Squat'));+ expect(fit.sessionEditedRoutine, isTrue);++ fit.saveSessionIntoRoutine();+ expect(r.exerciseIds, [idOf('Barbell Bench Press'), idOf('Barbell Squat')]);+ expect(fit.sessionEditedRoutine, isFalse);+ });++ test('los cambios se enseñan antes de guardarlos', () {+ final r = routineOf(['Barbell Bench Press', 'Barbell Squat', 'Barbell Deadlift']);+ fit.startRoutine(r);+ fit.removeSessionExercise(2);+ fit.addExerciseToSession(idOf('Barbell Curl'));+ fit.reorderSessionExercise(2, 0);+ final changes = fit.sessionRoutineChanges;+ expect(changes.added.map((e) => e.id), [idOf('Barbell Curl')]);+ expect(changes.removed.map((e) => e.id), [idOf('Barbell Deadlift')]);+ expect(changes.reordered, isTrue);+ expect(r.exerciseIds, hasLength(3), reason: 'nada cambia hasta aceptar');+ });++ test('una sesión suelta se guarda con el nombre elegido', () {+ fit.startRoutine(routineOf(['Barbell Bench Press']));+ fit.session!.routineId = null;+ final id = fit.saveSessionAsRoutine('Pecho');+ expect(fit.routines.firstWhere((r) => r.id == id).name, 'Pecho');+ expect(fit.sessionRoutine?.id, id, reason: 'el botón no vuelve a salir');+ });+ });++ group('series y planes de rutina', () {+ 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('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('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('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('la Recommended Routine es una sola rutina puesta lunes, miércoles y viernes', () {+ final made = fit.applyTemplate(kProgramTemplates.firstWhere((x) => x.id == 'rr'));+ expect(made, 1);+ final id = fit.routinesInGroup('Recommended Routine').single.id;+ expect(fit.weeklyPlan, {1: id, 3: id, 5: id});+ });++ 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('Copy');+ final made = fit.routines.firstWhere((x) => x.id == id);+ expect(made.exerciseIds, [bench()]);+ expect(fit.routineSets(made, bench()), 4);+ });+ });+ });++ group('naming a routine', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ test('a new routine starts unnamed so the field shows its hint', () {+ final id = fit.createRoutine();+ expect(fit.routines.single.name, '');+ expect(fit.routineTitle(fit.routines.single), t.newRoutineName);+ fit.renameRoutine(id, 'Empuje');+ expect(fit.routineTitle(fit.routines.single), 'Empuje');+ });++ test('clearing the name to retype it does not stick the old one', () {+ final id = fit.createRoutine('Viejo');+ fit.renameRoutine(id, '');+ expect(fit.routines.single.name, '');+ fit.renameRoutine(id, 'Nuevo');+ expect(fit.routines.single.name, 'Nuevo');+ });+ });+}diff --git a/test/settings_test.dart b/test/settings_test.dartnew file mode 100644index 0000000..6a25ad0--- /dev/null+++ b/test/settings_test.dart@@ -0,0 +1,116 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/services/rest_alarm.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ group('#181 negro AMOLED', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ test('es un tema oscuro aparte y se recuerda', () {+ fit.setThemePref('amoled');+ expect(fit.dark, isTrue);+ expect(fit.themeMode, ThemeMode.dark);+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.themePref, 'amoled');+ fit.setThemePref('dark');+ expect(fit.themePref, 'dark');+ });+ });++ group('#206 fotos tapadas en Progreso', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ test('se recuerda al reiniciar', () {+ expect(fit.hideShots, isFalse);+ fit.toggleHideShots();+ fit.persistNow();+ fit.hideShots = false;+ fit.loadFromStore();+ expect(fit.hideShots, isTrue);+ fit.resetAllData();+ expect(fit.hideShots, isFalse);+ });+ });++ group('settings', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ test('the theme can follow the phone and older backups still load', () {+ fit.setThemePref('system');+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.themePref, 'system');+ fit.applyBackup({'dark': false});+ expect(fit.themePref, 'light');+ fit.setThemePref('dark');+ });++ test('the rest alarm style is kept and handed to the alarm', () {+ fit.setAlarmStyle('vibrate');+ expect(RestAlarm.instance.style, 'vibrate');+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.alarmStyle, 'vibrate');+ fit.setAlarmStyle('loud');+ });++ test('height reads in feet and inches for imperial users', () {+ fit.setUnits('lb');+ expect(fit.heightLabel(175), '5′ 9″');+ fit.setUnits('kg');+ expect(fit.heightLabel(175), '175 cm');+ });+ });++ group('#92 inicio de semana', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ test('empezar en domingo mueve toda la semana', () {+ fit.setWeekStart(DateTime.sunday);+ expect(fit.weekStartDate.weekday, DateTime.sunday);+ expect(fit.weekdayAt(0), DateTime.sunday);+ expect(fit.dateForWeekday(fit.todayIndex).day, DateTime.now().day);+ });++ test('se guarda con el resto de ajustes', () {+ fit.setWeekStart(DateTime.saturday);+ expect(fit.toJson()['weekStart'], DateTime.saturday);+ fit.setWeekStart(4);+ expect(fit.weekStartDay, DateTime.saturday, reason: 'solo lunes, sábado o domingo');+ });+ });+}diff --git a/test/audit_test.dart b/test/stats_totals_test.dartsimilarity index 100%rename from test/audit_test.dartrename to test/stats_totals_test.dartdiff --git a/test/new_tools_test.dart b/test/strength_calculators_test.dartsimilarity index 100%rename from test/new_tools_test.dartrename to test/strength_calculators_test.dartdiff --git a/test/supersets_test.dart b/test/supersets_test.dartnew file mode 100644index 0000000..79ae149--- /dev/null+++ b/test/supersets_test.dart@@ -0,0 +1,184 @@+import 'package:flutter_test/flutter_test.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();++ group('#177 saltar dentro de una superserie', () {+ late List<String> ids;++ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ ids = fit.allExercises.take(6).map((e) => e.id).toList();+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String routineWith(String name, List<String> exs) {+ final r = fit.createRoutine(name);+ for (final id in exs) {+ fit.toggleRoutineExercise(r, id);+ }+ return r;+ }++ void finish(int exIdx) {+ for (final st in fit.session!.exercises[exIdx].sets) {+ st.done = true;+ }+ }++ test('la flecha sale de la cadena como al completar la serie', () {+ routineWith('Cadena', ids);+ fit.startRoutine(fit.routines.single);+ final s = fit.session!;+ for (var i = 0; i < 4; i++) {+ s.exercises[i].linkedNext = true;+ }+ for (final i in [0, 1, 3, 4]) {+ finish(i);+ }+ s.currentIndex = 2;++ fit.nextExercise();+ expect(s.currentIndex, 5);+ });++ test('dentro de la cadena va al siguiente que aún tiene series', () {+ routineWith('Cadena', ids);+ fit.startRoutine(fit.routines.single);+ final s = fit.session!;+ for (var i = 0; i < 4; i++) {+ s.exercises[i].linkedNext = true;+ }+ finish(1);+ s.currentIndex = 0;++ fit.nextExercise();+ expect(s.currentIndex, 2);+ });++ test('fuera de una cadena sigue yendo al siguiente de la lista', () {+ routineWith('Suelta', ids.take(3).toList());+ fit.startRoutine(fit.routines.single);+ fit.nextExercise();+ expect(fit.session!.currentIndex, 1);+ });+ });++ group('#266 superserie sin rutina', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ fit.autoAdvance = false;+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ test('se encadena y se separa dentro de la sesión libre', () {+ fit.startWorkout();+ fit.toggleMuscle('chest');+ fit.trainContinue();+ fit.startSession();+ fit.addExerciseToSession(fit.matchExerciseByName('Barbell Squat')!.id);+ final s = fit.session!;+ expect(s.routineId, isNull);+ final last = s.exercises.length - 1;+ fit.toggleSessionLink(last - 1);+ expect(s.exercises[last - 1].linkedNext, isTrue);+ fit.toggleSessionLink(last);+ expect(s.exercises[last].linkedNext, isFalse);+ fit.toggleSessionLink(last - 1);+ expect(s.exercises[last - 1].linkedNext, isFalse);+ });+ });++ group('superseries', () {+ 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);+ }++ ({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);+ });+ });+}diff --git a/test/theme_test.dart b/test/theme_test.dartnew file mode 100644index 0000000..ae2f255--- /dev/null+++ b/test/theme_test.dart@@ -0,0 +1,61 @@+import 'dart:math' as math;+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:gymmane/theme/app_colors.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ group('light theme belongs to the same family as dark', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ double lin(double c) => c <= 0.03928 ? c / 12.92 : math.pow((c + 0.055) / 1.055, 2.4).toDouble();+ double lum(Color c) => 0.2126 * lin(c.r) + 0.7152 * lin(c.g) + 0.0722 * lin(c.b);+ double contrast(Color a, Color b) {+ final la = lum(a), lb = lum(b);+ return (math.max(la, lb) + 0.05) / (math.min(la, lb) + 0.05);+ }++ double warmth(Color c) => (c.r - c.b) * 255;++ test('light neutrals are warm, not cold grey', () {+ for (final c in [GymColors.light.bg, GymColors.light.bgRaised2, GymColors.light.border]) {+ expect(warmth(c), greaterThan(6), reason: 'neutro frío: $c');+ }+ });++ test('every text colour on light is actually readable', () {+ final bg = GymColors.light.bg;+ expect(contrast(bg, GymColors.light.text), greaterThan(7), reason: 'principal, AAA');+ expect(contrast(bg, GymColors.light.textSecondary), greaterThan(4.5), reason: 'secundario, AA');++ expect(contrast(bg, GymColors.light.textTertiary), greaterThan(3), reason: 'terciario');+ });++ test('the light accent reads on bone', () {++ expect(contrast(GymColors.light.bg, GymColors.light.accent), greaterThanOrEqualTo(4.5));+ });++ test('dark text stays readable too', () {+ final bg = GymColors.dark.bg;+ expect(contrast(bg, GymColors.dark.text), greaterThan(7));+ expect(contrast(bg, GymColors.dark.textSecondary), greaterThan(4.5));+ });++ test('action colour flips with the theme but keeps its contrast', () {+ expect(contrast(GymColors.dark.ember, GymColors.dark.onEmber), greaterThan(7));+ expect(contrast(GymColors.light.ember, GymColors.light.onEmber), greaterThan(7));+ });+ });+}diff --git a/test/timed_and_cardio_test.dart b/test/timed_and_cardio_test.dartnew file mode 100644index 0000000..39867d9--- /dev/null+++ b/test/timed_and_cardio_test.dart@@ -0,0 +1,453 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.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();++ group('#183 ejercicio por tiempo sin peso', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ test('uno propio por tiempo con barra empieza sin peso', () {+ final id = fit.addCustomExercise(+ name: 'Sweep', primary: 'abdomen', equipment: 'Barbell', mode: 'time');+ expect(fit.isRepsOnly(id), isTrue);+ });++ test('si ya lo hizo con peso, el peso sigue', () {+ final id = fit.addCustomExercise(+ name: 'Sweep', primary: 'abdomen', equipment: 'Barbell', mode: 'time');+ fit.sessions.add(LoggedSession(DateTime.now(), 600, [+ LoggedExercise(id, 'Sweep', 'abdomen', [LoggedSet(0, 10, sec: 30)]),+ ]));+ expect(fit.isRepsOnly(id), isFalse);+ });++ test('se puede volver a poner el peso', () {+ final id = fit.addCustomExercise(+ name: 'Sweep', primary: 'abdomen', equipment: 'Barbell', mode: 'time');+ fit.toggleRepsOnly(id);+ expect(fit.isRepsOnly(id), isFalse);+ });++ test('los de carga siguen con peso y los de reps no cambian', () {+ expect(fit.isRepsOnly('kettlebell-farmer-carry'), isFalse);+ expect(fit.isRepsOnly('cable-pallof-hold'), isFalse);+ expect(fit.isRepsOnly('jump-rope'), isTrue);+ final barbell = fit.allExercises.firstWhere((e) => e.equipment == 'Barbell' && fit.modeOf(e.id).isEmpty);+ expect(fit.isRepsOnly(barbell.id), isFalse);+ });+ });++ group('#173 cardio', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ Routine routineOf(List<String> ids) {+ final id = fit.createRoutine('Cardio');+ for (final ex in ids) {+ fit.toggleRoutineExercise(id, ex);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ test('el filtro rápido de cardio solo deja cardio y no cuenta como filtro de la hoja', () {+ fit.setKindFilter('cardio');+ final list = fit.exercisesFiltered;+ expect(list, isNotEmpty);+ expect(list.every((e) => fit.kindOf(e) == 'cardio'), isTrue);+ expect(list.map((e) => e.id), containsAll(['running', 'jump-rope']));+ fit.setKindFilter('cardio');+ expect(fit.exKindFilter, isNull);+ });++ test('las series de cardio llevan reloj y las de peso no', () {+ expect(fit.runsClock('running'), isTrue);+ expect(fit.runsClock('cable-pallof-hold'), fit.isTimed('cable-pallof-hold'));+ final barbell = fit.allExercises.firstWhere((e) => fit.modeOf(e.id).isEmpty);+ expect(fit.runsClock(barbell.id), isFalse);+ });++ test('una carrera larga no se corta a la hora', () {+ fit.startRoutine(routineOf(['running']));+ fit.endCountdown();+ fit.session!.exercises.first.sets.first.sec = 90 * 60;+ fit.startHold(0, 0);+ expect(fit.holdTotal, 90 * 60);+ fit.stopHold();+ });++ test('terminar antes guarda el tiempo que se ha corrido', () {+ fit.startRoutine(routineOf(['running']));+ fit.endCountdown();+ fit.session!.exercises.first.sets.first.sec = 1200;+ fit.startHold(0, 0);+ final start = DateTime.now().subtract(const Duration(seconds: 300));+ fit.holdStartsAt = start;+ fit.holdEndsAt = start.add(const Duration(seconds: 1200));+ fit.toggleHoldPause();+ fit.completeHold();+ final set = fit.session!.exercises.first.sets.first;+ expect(set.done, isTrue);+ expect(set.sec, inInclusiveRange(299, 301));+ });++ test('un aguante terminado antes sigue guardando lo planeado', () {+ final plank = fit.matchExerciseByName('Plank')!.id;+ fit.startRoutine(routineOf([plank]));+ fit.endCountdown();+ fit.setExerciseMode(plank, 'time');+ final planned = fit.session!.exercises.first.sets.first.sec;+ fit.startHold(0, 0);+ final start = DateTime.now().subtract(const Duration(seconds: 10));+ fit.holdStartsAt = start;+ fit.holdEndsAt = start.add(Duration(seconds: fit.holdTotal));+ fit.toggleHoldPause();+ fit.completeHold();+ expect(fit.session!.exercises.first.sets.first.sec, planned);+ });+ });++ group('#213 cada lado', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ Routine routineOf(List<String> ids) {+ final id = fit.createRoutine('Core');+ for (final ex in ids) {+ fit.toggleRoutineExercise(id, ex);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ Future<void> endSide() async {+ final past = DateTime.now().subtract(const Duration(milliseconds: 50));+ fit.holdStartsAt = past.subtract(Duration(seconds: fit.holdTotal));+ fit.holdEndsAt = past;+ await Future<void>.delayed(const Duration(milliseconds: 300));+ }++ test('la plancha lateral viene por lados y se puede quitar y volver a poner', () async {+ expect(fit.isEachSide('side-plank-hold'), isTrue);+ expect(fit.isEachSide('plank-hold'), isFalse);+ fit.toggleEachSide('side-plank-hold');+ fit.toggleEachSide('plank-hold');+ expect(fit.isEachSide('side-plank-hold'), isFalse);+ expect(fit.isEachSide('plank-hold'), isTrue);++ fit.persistNow();+ fit.eachSide.clear();+ fit.eachSideOff.clear();+ fit.loadFromStore();+ expect(fit.isEachSide('side-plank-hold'), isFalse);+ expect(fit.isEachSide('plank-hold'), isTrue);++ fit.toggleEachSide('side-plank-hold');+ expect(fit.eachSideOff, isNot(contains('side-plank-hold')));+ expect(fit.eachSide, isNot(contains('side-plank-hold')));+ });++ test('solo cuenta en ejercicios por tiempo', () {+ fit.setExerciseMode('side-plank-hold', 'weight');+ expect(fit.isEachSide('side-plank-hold'), isFalse);+ fit.setExerciseMode('side-plank-hold', 'time');+ expect(fit.isEachSide('side-plank-hold'), isTrue);+ });++ test('corre un lado, avisa de cambiar y descansa solo tras el segundo', () async {+ fit.startRoutine(routineOf(['side-plank-hold']));+ fit.endCountdown();+ final set = fit.session!.exercises.first.sets.first;+ fit.startHold(0, 0);+ expect(fit.holdSides, 2);+ expect(fit.holdLength('side-plank-hold', 30), '0:30 × 2');++ await endSide();+ expect(fit.holding, isTrue);+ expect(fit.holdSide, 1);+ expect(fit.switchingSides, isTrue);+ expect(set.done, isFalse);+ expect(fit.session!.restRemaining, isNull);++ await endSide();+ expect(fit.holding, isFalse);+ expect(set.done, isTrue);+ expect(fit.session!.restRemaining, isNotNull);+ fit.skipRest();+ });++ test('un aguante normal sigue siendo de una vez', () async {+ fit.startRoutine(routineOf(['plank-hold']));+ fit.endCountdown();+ fit.startHold(0, 0);+ expect(fit.holdSides, 1);+ await endSide();+ expect(fit.holding, isFalse);+ expect(fit.session!.exercises.first.sets.first.done, isTrue);+ fit.skipRest();+ });++ test('pararlo deja todo como al principio', () {+ fit.startRoutine(routineOf(['side-plank-hold']));+ fit.endCountdown();+ fit.startHold(0, 0);+ fit.stopHold();+ expect(fit.holdSide, 0);+ expect(fit.holdSides, 1);+ expect(fit.session!.exercises.first.sets.first.done, isFalse);+ });+ });++ group('cardio and timed work', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineWith(List<String> ids, {String name = 'Push'}) {+ final id = fit.createRoutine(name);+ for (final ex in ids) {+ fit.toggleRoutineExercise(id, ex);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ test('a run opens with time and distance, and remembers them', () {+ final run = idOf('Outdoor Run');+ expect(fit.modeOf(run), 'cardio');+ expect(fit.restFor(run), 0);+ final r = routineWith([run]);+ expect(fit.routineSets(r, run), 1);+ fit.startRoutine(r);+ final st = fit.session!.exercises.single.sets.single;+ expect(st.sec, 1200);+ fit.setSessionKm(0, 0, 5.2);+ fit.setSessionSeconds(0, 0, 1800);+ fit.toggleSet(0, 0);+ fit.finishSession();+ fit.saveAndExit();+ final logged = fit.lastSetsFor(run).single;+ expect(logged.km, 5.2);+ expect(fit.loggedSetLabel(logged), '5.2 km · 30:00');+ fit.startRoutine(r);+ expect(fit.session!.exercises.single.sets.single.km, 5.2);+ expect(fit.nextTarget(run), isNull);+ });++ test('miles show for imperial users', () {+ fit.setUnits('lb');+ expect(fit.distanceLabel(1.609344), '1 mi');+ fit.setUnits('kg');+ });++ test('a plank opens with seconds and the hold can start and stop', () {+ final plank = idOf('Plank');+ expect(fit.modeOf(plank), 'time');+ fit.startRoutine(routineWith([plank]));+ final sets = fit.session!.exercises.single.sets;+ expect(sets.first.sec, 30);+ fit.startHold(0, 0);+ expect(fit.holding, isTrue);+ expect(fit.holdRemaining, 30);+ expect(fit.holdLead, inInclusiveRange(4, 5));+ fit.stopHold();+ expect(fit.holding, isFalse);+ expect(sets.first.done, isFalse);+ });++ test('how an exercise is logged can be changed and changed back', () {+ final rope = idOf('Jump Rope');+ expect(fit.modeOf(rope), 'time');+ fit.setExerciseMode(rope, '');+ expect(fit.modeOf(rope), '');+ fit.setExerciseMode(rope, 'time');+ expect(fit.modeOverride.containsKey(rope), isFalse);+ });++ test('timed and cardio sets keep their fields through json', () {+ final s = SessionSet(0, 20, true, sec: 45, km: null, kind: SetKind.restPause);+ final back = SessionSet.fromJson(s.toJson());+ expect(back.sec, 45);+ expect(back.kind, SetKind.restPause);+ final l = LoggedSet.fromJson(LoggedSet(0, 0, sec: 600, km: 2.5).toJson());+ expect(l.km, 2.5);+ expect(l.oneRm, 0);+ });+ });++ group('cronómetro', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ test('#236 el cronómetro solo en ejercicios con reloj', () {+ expect(fit.runsClock('plank-hold'), isTrue);+ expect(fit.runsClock(fit.matchExerciseByName('Bench Press')!.id), isFalse);+ });+ });++ group('#219 calorías de caminar y correr', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ LoggedSession walk(String id, double km, int sec, {int dur = 0, double? incline}) {+ final s = LoggedSession(DateTime.now().copyWith(hour: 12), dur == 0 ? sec : dur, [+ LoggedExercise(id, id, 'quads', [LoggedSet(0, 0, sec: sec, km: km)], incline: incline),+ ]);+ fit.sessions.add(s);+ return s;+ }++ setUp(() => fit.addBodyweight(70));++ test('caminar 5 km en una hora con 70 kg: 175 activas y ~249 en total (ACSM)', () {+ final s = walk('walking', 5, 3600);+ final c = fit.cardioKcal(s, s.exercises.first)!;+ expect(c.active, 175);+ expect(c.total, closeTo(249, 1));+ expect(c.own, isFalse);+ });++ test('a partir de 7,2 km/h usa la fórmula de correr', () {+ final s = walk('running', 10, 3000);+ expect(fit.cardioKcal(s, s.exercises.first)!.active, 700);+ });++ test('la inclinación suma: 3 km en 30 min al 10 % son 294 activas', () {+ final s = walk('treadmill-incline-walk', 3, 1800, incline: 10);+ expect(fit.cardioKcal(s, s.exercises.first)!.active, 294);+ });++ test('cada serie es un tramo y se calcula por separado', () {+ final s = LoggedSession(DateTime.now().copyWith(hour: 12), 4800, [+ LoggedExercise('running', 'Running', 'quads', [+ LoggedSet(0, 0, sec: 1800, km: 2.5),+ LoggedSet(0, 0, sec: 3000, km: 10),+ ]),+ ]);+ fit.sessions.add(s);+ final walkPart = (0.1 * (2500 / 30)) * 70 * 30 / 200;+ expect(fit.cardioKcal(s, s.exercises.first)!.active, (walkPart + 700).round());+ });++ test('el valor del reloj manda sobre el estimado y se puede volver atrás', () {+ final s = walk('walking', 5, 3600);+ final e = s.exercises.first;+ fit.setLoggedKcal(e, 210);+ expect(fit.cardioKcal(s, e)!.active, 210);+ expect(fit.cardioKcal(s, e)!.own, isTrue);+ fit.setLoggedKcal(e, null);+ expect(fit.cardioKcal(s, e)!.active, 175);+ });++ test('bici, elíptica o remo no se estiman con la fórmula de caminar', () {+ final s = walk('cycling', 20, 3600);+ expect(fit.cardioKcal(s, s.exercises.first), isNull);+ });++ test('un ejercicio propio que se llama carrera sí se estima', () {+ final id = fit.addCustomExercise(name: 'Carrera por el parque', primary: 'quads', equipment: 'Bodyweight', mode: 'cardio');+ final s = LoggedSession(DateTime.now().copyWith(hour: 12), 3600, [+ LoggedExercise(id, 'Carrera por el parque', 'quads', [LoggedSet(0, 0, sec: 3600, km: 5)]),+ ]);+ fit.sessions.add(s);+ expect(fit.cardioKcal(s, s.exercises.first)!.active, 175);+ });++ test('las kcal quemadas del día usan el cardio y el resto como pesas', () {+ walk('walking', 5, 3600, dur: 5400);+ expect(fit.burnedOn(DateTime.now()), 175 + 140);+ });++ test('la inclinación y el valor propio se guardan', () async {+ final s = walk('walking', 5, 3600);+ fit.setLoggedIncline(s.exercises.first, 4);+ fit.setLoggedKcal(s.exercises.first, 300);+ await pumpEventQueue();+ fit.loadFromStore();+ final e = fit.sessions.last.exercises.first;+ expect(e.incline, 4);+ expect(e.kcal, 300);+ });++ test('la siguiente sesión hereda la última inclinación de ese ejercicio', () {+ final s = walk('treadmill-incline-walk', 3, 1800);+ fit.setLoggedIncline(s.exercises.first, 12);+ expect(fit.lastIncline('treadmill-incline-walk'), 12);+ });+ });++ group('#88 pausar el temporizador', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineOf(List<String> names) {+ final id = fit.createRoutine('Push');+ for (final name in names) {+ fit.toggleRoutineExercise(id, idOf(name));+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ test('pausar guarda lo que queda y terminar ya marca la serie', () {+ fit.startRoutine(routineOf(['Plank']));+ fit.endCountdown();+ fit.setExerciseMode(idOf('Plank'), 'time');+ fit.startHold(0, 0);+ final lead = fit.holdLead;+ fit.toggleHoldPause();+ expect(fit.holdPaused, isTrue);+ expect(fit.holdLead, lead);+ fit.toggleHoldPause();+ expect(fit.holdPaused, isFalse);+ fit.toggleHoldPause();+ fit.completeHold();+ expect(fit.session!.exercises.first.sets.first.done, isTrue);+ expect(fit.holding, isFalse);+ });+ });+}diff --git a/test/train_step2_test.dart b/test/train_picks_test.dartsimilarity index 100%rename from test/train_step2_test.dartrename to test/train_picks_test.dartdiff --git a/test/weekly_plan_test.dart b/test/weekly_plan_test.dartnew file mode 100644index 0000000..a075a5c--- /dev/null+++ b/test/weekly_plan_test.dart@@ -0,0 +1,349 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.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();++ group('mover la sesión de hoy', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ Routine routine(String name) {+ final id = fit.createRoutine(name);+ fit.toggleRoutineExercise(id, bench());+ return fit.routines.firstWhere((r) => r.id == id);+ }++ DateTime day(int offset) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day + offset, 10);+ }++ test('pasa a otro día sin tocar el plan semanal y se deshace', () {+ final a = routine('A');+ final today = DateTime.now();+ fit.assignRoutineToDay(today.weekday, a.id);+ final undo = fit.moveRoutineDay(a.id, today, day(2));+ expect(undo, isNotNull);+ expect(fit.routinesOn(today), isEmpty);+ expect(fit.routinesOn(day(2)).single.id, a.id);+ expect(fit.weeklyPlan[today.weekday], a.id);+ expect(fit.movedOn(today), isTrue);+ expect(fit.isTrainingDay(today), isFalse);++ fit.persistNow();+ fit.planMoves.clear();+ fit.loadFromStore();+ expect(fit.routinesOn(day(2)).single.id, a.id);++ undo!();+ expect(fit.routinesOn(today).single.id, a.id);+ expect(fit.movedOn(day(2)), isFalse);+ });++ test('volver al plan quita el cambio de ese día', () {+ final a = routine('A');+ final today = DateTime.now();+ fit.assignRoutineToDay(today.weekday, a.id);+ fit.moveRoutineDay(a.id, today, day(1));+ fit.undoMoves(today);+ expect(fit.routinesOn(today).single.id, a.id);+ });+ });++ group('mover el día a fondo', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ Routine routine(String name, [List<String>? ids]) {+ final id = fit.createRoutine(name);+ for (final e in ids ?? [bench()]) {+ fit.toggleRoutineExercise(id, e);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ DateTime day(int offset, [int hour = 10]) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day + offset, hour);+ }++ test('a un día que ya tiene rutina se suman las dos', () {+ final a = routine('A'), b = routine('B');+ final today = DateTime.now();+ fit.toggleMultiPlan();+ fit.assignRoutineToDay(today.weekday, a.id);+ fit.assignRoutineToDay(day(1).weekday, b.id);+ fit.moveRoutineDay(a.id, today, day(1));+ expect(fit.routinesOn(day(1)).map((r) => r.id), [b.id, a.id]);+ expect(fit.routinesOn(today), isEmpty);+ expect(fit.routinesOn(day(8)).map((r) => r.id), [b.id]);+ });++ test('mover dos veces y deshacer la segunda deja la primera', () {+ final a = routine('A');+ final today = DateTime.now();+ fit.assignRoutineToDay(today.weekday, a.id);+ fit.moveRoutineDay(a.id, today, day(1));+ final undo = fit.moveRoutineDay(a.id, day(1), day(2))!;+ expect(fit.routinesOn(day(2)).single.id, a.id);+ expect(fit.routinesOn(day(1)), isEmpty);+ undo();+ expect(fit.routinesOn(day(1)).single.id, a.id);+ expect(fit.routinesOn(day(2)), isEmpty);+ });++ test('no mueve lo que no está ese día ni al mismo día', () {+ final a = routine('A');+ final today = DateTime.now();+ expect(fit.moveRoutineDay(a.id, today, day(1)), isNull);+ fit.assignRoutineToDay(today.weekday, a.id);+ expect(fit.moveRoutineDay(a.id, today, DateTime.now()), isNull);+ expect(fit.planMoves, isEmpty);+ });++ test('los cambios viejos se borran solos', () {+ final a = routine('A');+ fit.planMoves['2001-01-01'] = [a.id];+ final today = DateTime.now();+ fit.assignRoutineToDay(today.weekday, a.id);+ fit.moveRoutineDay(a.id, today, day(1));+ expect(fit.planMoves.containsKey('2001-01-01'), isFalse);+ });++ test('borrar la rutina la quita también de los días movidos', () {+ final a = routine('A');+ final today = DateTime.now();+ fit.assignRoutineToDay(today.weekday, a.id);+ fit.moveRoutineDay(a.id, today, day(1));+ fit.deleteRoutine(a.id);+ expect(fit.routinesOn(day(1)), isEmpty);+ });+ });++ group('#158 planes guardados', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ late String a, b, c;+ setUp(() {+ a = fit.createRoutine('A');+ b = fit.createRoutine('B');+ c = fit.createRoutine('C');+ fit.assignRoutineToDay(1, a);+ fit.assignRoutineToDay(3, b);+ });++ test('guardar la semana y cambiar a otra sin perder la primera', () {+ fit.savePlanAs('Invierno');+ fit.savePlanAs('Verano', empty: true);+ expect(fit.weeklyPlan, isEmpty);+ fit.assignRoutineToDay(2, c);+ fit.switchPlan(fit.savedPlans.first.id);+ expect(fit.weeklyPlan, {1: a, 3: b});+ fit.switchPlan(fit.savedPlans.last.id);+ expect(fit.weeklyPlan, {2: c});+ });++ test('los cambios en la semana van al plan elegido', () {+ fit.savePlanAs('Invierno');+ fit.assignRoutineToDay(5, c);+ fit.savePlanAs('Viaje', empty: true);+ fit.switchPlan(fit.savedPlans.first.id);+ expect(fit.weeklyPlan, {1: a, 3: b, 5: c});+ });++ test('empezar vacío sin haber guardado conserva la semana como «Mi plan»', () {+ fit.savePlanAs('Reddit', empty: true);+ expect(fit.savedPlans.map((p) => p.name), [t.planMine, 'Reddit']);+ fit.switchPlan(fit.savedPlans.first.id);+ expect(fit.weeklyPlan, {1: a, 3: b});+ });++ test('borrar una rutina la quita de todos los planes', () {+ fit.savePlanAs('Invierno');+ fit.savePlanAs('Verano');+ fit.deleteRoutine(a);+ for (final p in fit.savedPlansLive) {+ expect(p.uses(a), isFalse);+ }+ fit.switchPlan(fit.savedPlans.first.id);+ expect(fit.weeklyPlan, {3: b});+ });++ test('borrar un plan deja la semana como está', () {+ fit.savePlanAs('Invierno');+ fit.deletePlan(fit.savedPlans.first.id);+ expect(fit.savedPlans, isEmpty);+ expect(fit.currentPlanId, '');+ expect(fit.weeklyPlan, {1: a, 3: b});+ });++ test('los planes, el elegido y sus cambios se guardan al reabrir', () async {+ fit.savePlanAs('Invierno');+ fit.savePlanAs('Verano', empty: true);+ fit.assignRoutineToDay(6, c);+ fit.renamePlan(fit.currentPlanId, 'Verano 2027');+ fit.persistNow();+ await pumpEventQueue();+ fit.loadFromStore();+ expect(fit.savedPlans.map((p) => p.name), ['Invierno', 'Verano 2027']);+ expect(fit.currentPlanId, fit.savedPlans.last.id);+ expect(fit.weeklyPlan, {6: c});+ fit.switchPlan(fit.savedPlans.first.id);+ expect(fit.weeklyPlan, {1: a, 3: b});+ fit.switchPlan(fit.savedPlans.last.id);+ expect(fit.weeklyPlan, {6: c});+ });++ test('un nombre vacío no crea nada', () {+ fit.savePlanAs(' ');+ expect(fit.savedPlans, isEmpty);+ });+ });++ group('#86 varias rutinas al día', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineOf(List<String> names) {+ final id = fit.createRoutine('Push');+ for (final name in names) {+ fit.toggleRoutineExercise(id, idOf(name));+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ LoggedSession logged(DateTime at, List<LoggedSet> sets, {String id = 'push', String primary = 'chest'}) =>+ LoggedSession(at, 600, [LoggedExercise(id, id, primary, sets)]);++ test('apagado, un día solo tiene una rutina', () {+ final a = routineOf(['Barbell Bench Press']);+ final b = routineOf(['Barbell Squat']);+ final today = DateTime.now().weekday;+ fit.togglePlanDay(today, a.id);+ fit.togglePlanDay(today, b.id);+ expect(fit.planIdsOn(today), [b.id]);+ });++ test('encendido, van en orden y el día acaba cuando se hacen todas', () {+ fit.toggleMultiPlan();+ final a = routineOf(['Barbell Bench Press']);+ final b = routineOf(['Barbell Squat']);+ final today = DateTime.now().weekday;+ fit.togglePlanDay(today, a.id);+ fit.togglePlanDay(today, b.id);+ expect(fit.todayRoutine, same(a));+ expect(fit.todayPlanDone, isFalse);++ fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 60)]));+ expect(fit.todayRoutine, same(b));+ expect(fit.todayPlanDone, isFalse);++ fit.sessions.add(logged(DateTime.now(), [LoggedSet(5, 100)]));+ expect(fit.todayPlanDone, isTrue);+ });++ test('#157 repetir una rutina no cuenta como hacer la otra', () {+ fit.toggleMultiPlan();+ final a = routineOf(['Barbell Bench Press']);+ final b = routineOf(['Barbell Squat']);+ final c = routineOf(['Barbell Deadlift']);+ final today = DateTime.now().weekday;+ fit.togglePlanDay(today, a.id);+ fit.togglePlanDay(today, b.id);+ LoggedSession done(String id) => LoggedSession(DateTime.now(), 1800, const [], routineId: id);++ fit.sessions.add(done(a.id));+ fit.sessions.add(done(a.id));+ fit.sessions.add(done(c.id));+ expect(fit.todayPlanDone, isFalse);+ expect(fit.todayRoutine, same(b));++ fit.sessions.add(done(b.id));+ expect(fit.todayPlanDone, isTrue);+ expect(LoggedSession.fromJson(done(b.id).toJson()).routineId, b.id);+ });++ test('#156 al acabar una rutina ofrece la siguiente del día', () {+ fit.toggleMultiPlan();+ final a = routineOf(['Barbell Bench Press']);+ final b = routineOf(['Barbell Squat']);+ final today = DateTime.now().weekday;+ fit.togglePlanDay(today, a.id);+ fit.togglePlanDay(today, b.id);++ fit.startRoutine(a);+ fit.toggleSet(0, 0);+ fit.finishSession();+ expect(fit.sessions.last.routineId, a.id);+ expect(fit.nextRoutineToday, same(b));++ fit.startNextRoutine();+ expect(fit.session?.routineId, b.id);+ expect(fit.session?.complete, isFalse);+ fit.toggleSet(0, 0);+ fit.finishSession();+ expect(fit.nextRoutineToday, isNull);+ expect(fit.todayPlanDone, isTrue);+ });++ test('#157 hacer la segunda primero deja pendiente la primera', () {+ fit.toggleMultiPlan();+ final a = routineOf(['Barbell Bench Press']);+ final b = routineOf(['Barbell Squat']);+ final today = DateTime.now().weekday;+ fit.togglePlanDay(today, a.id);+ fit.togglePlanDay(today, b.id);+ fit.sessions.add(LoggedSession(DateTime.now(), 1800, const [], routineId: b.id));+ expect(fit.todayRoutine, same(a));+ expect(fit.todayPlanDone, isFalse);+ });++ test('borrar la primera deja la segunda y se guarda', () {+ fit.toggleMultiPlan();+ final a = routineOf(['Barbell Bench Press']);+ final b = routineOf(['Barbell Squat']);+ final c = routineOf(['Barbell Deadlift']);+ fit.togglePlanDay(1, a.id);+ fit.togglePlanDay(1, b.id);+ fit.togglePlanDay(1, c.id);+ fit.deleteRoutine(a.id);+ expect(fit.planIdsOn(1), [b.id, c.id]);+ expect(fit.toJson()['planExtras'], {'1': [c.id]});+ fit.toggleMultiPlan();+ expect(fit.planIdsOn(1), [b.id], reason: 'apagado se ignoran las extra');+ });+ });+}diff --git a/test/weights_test.dart b/test/weights_test.dartnew file mode 100644index 0000000..b8b075a--- /dev/null+++ b/test/weights_test.dart@@ -0,0 +1,179 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.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();++ group('salto de peso', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ test('los botones suman el salto elegido', () {+ final bench = idOf('Barbell Bench Press');+ fit.sessionPicks+ ..clear()+ ..add(bench);+ fit.startSession();+ fit.setSessionWeight(0, 0, 60);++ fit.setWeightStep(2);+ fit.bumpSessionWeight(0, 0, 1);+ expect(fit.session!.exercises[0].sets[0].weight, 62);+ });++ test('kg y lb guardan su propio salto y uno raro no entra', () {+ fit.setWeightStep(1);+ fit.setWeightStep(3);+ expect(fit.weightStep, 1);++ fit.setUnits('lb');+ expect(fit.weightStep, 5);+ fit.setWeightStep(10);+ expect(fit.weightStep, 10);++ fit.setUnits('kg');+ expect(fit.weightStep, 1);+ expect(fit.toJson()['stepKg'], 1);+ expect(fit.toJson()['stepLb'], 10);+ });++ test('los calentamientos siguen redondeando a discos', () {+ fit.setWeightStep(1);+ expect(fit.plateStep, 2.5);+ });+ });++ group('#240 barra propia', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ setAppLanguage('en');+ });++ test('sin elegir nada, la barra es la olímpica', () {+ expect(fit.plateBarDisplay, 20);+ expect(fit.defaultBar, 20);+ });++ test('una barra de otro peso calcula los discos sobre ella', () {+ fit.setPlateBar(12.5);+ fit.plateTarget = 52.5;+ expect(fit.plateBreakdown.map((p) => '${fmt(p.weight)}x${p.count}'), ['20x1']);+ });++ test('la barra elegida se recuerda al reabrir y vale para toda la app', () async {+ fit.setPlateBar(7);+ fit.persistNow();+ await pumpEventQueue();+ fit.loadFromStore();+ expect(fit.plateBarDisplay, 7);+ expect(fit.defaultBar, 7);+ expect(fit.barFor('x'), 7);+ });++ test('borrar los datos vuelve a la barra de 20', () {+ fit.setPlateBar(15);+ fit.resetAllData();+ expect(fit.plateBarDisplay, 20);+ });+ });++ group('#272 pesos de cuarto de kilo', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ fit.autoAdvance = false;+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ test('61,25 no se redondea y lo raro sigue a un decimal', () {+ expect(fit.weightValue(61.25), anyOf('61.25', '61,25'));+ expect(fit.weightValue(61.33), anyOf('61.3', '61,3'));+ expect(fit.weightValue(60), '60');+ });++ test('la regla baja a 0,25 con saltos de 1,25', () {+ fit.setWeightStep(1.25);+ expect(fit.rulerStep, 0.25);+ fit.setWeightStep(2.5);+ expect(fit.rulerStep, 0.5);+ });+ });++ group('carro de la prensa', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ test('#125 la prensa usa su propio carro en la calculadora', () {+ final press = idOf('Leg Press');+ expect(fit.plateHint('Machine', 150, id: press), isNull);+ fit.setExerciseBar(press, 50);+ expect(fit.plateHint('Machine', 150, id: press), '25×2');+ expect(fit.toJson()['barKg'], {press: 50.0});+ });+ });++ group('discos del sitio', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ 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);+ });+ });+}diff --git a/test/flow_test.dart b/test/workout_flow_test.dartsimilarity index 100%rename from test/flow_test.dartrename to test/workout_flow_test.dartdiff --git a/test/workout_session_test.dart b/test/workout_session_test.dartnew file mode 100644index 0000000..4f35f25--- /dev/null+++ b/test/workout_session_test.dart@@ -0,0 +1,489 @@+import 'dart:convert';+import 'package:flutter_test/flutter_test.dart';+import 'package:gymmane/l10n/l10n.dart';+import 'package:gymmane/models/note.dart';+import 'package:gymmane/models/workout.dart';+import 'package:gymmane/services/local_store.dart';+import 'package:gymmane/services/plan_share.dart';+import 'package:gymmane/state/fit_state.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ group('#160 nombre del entreno libre', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ Routine routineOf(List<String> ids) {+ final id = fit.createRoutine('Cardio');+ for (final ex in ids) {+ fit.toggleRoutineExercise(id, ex);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ LoggedSession finishFree() {+ fit.startRoutine(routineOf(['running']));+ fit.endCountdown();+ fit.session!.routineId = null;+ fit.toggleSet(0, 0);+ fit.finishSession();+ return fit.filedSession!;+ }++ test('se le pone nombre al acabar y se guarda', () {+ final s = finishFree();+ expect(fit.sessionTitle(s), isNull);+ fit.renameSession(s, ' Pierna ');+ expect(s.name, 'Pierna');+ expect(fit.sessionTitle(s), 'Pierna');+ expect(LoggedSession.fromJson(s.toJson()).name, 'Pierna');+ expect(fit.workoutText(s).split('\n').first, 'Pierna');+ });++ test('seguir entrenando y volver a acabar no pierde el nombre', () {+ final s = finishFree();+ fit.renameSession(s, 'Torso');+ fit.continueSession();+ expect(fit.session!.name, 'Torso');+ fit.finishSession();+ expect(fit.filedSession!.name, 'Torso');+ });++ test('reabrir un entreno guardado conserva el nombre', () {+ final s = finishFree();+ fit.renameSession(s, 'Brazos');+ fit.saveAndExit();+ fit.resumeLoggedSession(fit.sessions.last);+ expect(fit.session!.name, 'Brazos');+ });++ test('las de rutina se titulan con la rutina si no se renombran', () {+ final r = routineOf(['running']);+ fit.renameRoutine(r.id, 'Cardio suave');+ fit.startRoutine(fit.routines.firstWhere((x) => x.id == r.id));+ fit.endCountdown();+ fit.toggleSet(0, 0);+ fit.finishSession();+ expect(fit.sessionTitle(fit.filedSession!), 'Cardio suave');+ });+ });++ group('vista en lista', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ String bench() => fit.matchExerciseByName('Bench Press')!.id;++ Routine routine(String name) {+ final id = fit.createRoutine(name);+ fit.toggleRoutineExercise(id, bench());+ return fit.routines.firstWhere((r) => r.id == id);+ }++ DateTime day(int offset) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day + offset, 10);+ }++ test('el ajuste se guarda y por defecto son tarjetas', () {+ expect(fit.sessionLayout, 'cards');+ fit.setSessionLayout('list');+ fit.persistNow();+ fit.sessionLayout = 'cards';+ fit.loadFromStore();+ expect(fit.listLayout, isTrue);+ });++ test('marcar una serie de otro ejercicio lo pone delante y descansa con su tiempo', () {+ final id = fit.createRoutine('L');+ final squat = fit.matchExerciseByName('Barbell Squat')!.id;+ fit.toggleRoutineExercise(id, bench());+ fit.toggleRoutineExercise(id, squat);+ fit.setRoutineRest(id, squat, 200);+ fit.startRoutine(fit.routines.firstWhere((r) => r.id == id));+ fit.endCountdown();+ fit.toggleSetAt(1, 0);+ expect(fit.session!.currentIndex, 1);+ expect(fit.restTotal, 200);+ fit.skipRest();+ });++ test('copiar la serie anterior y mover ejercicios', () {+ fit.sessions.add(LoggedSession(day(-2), 600, [+ LoggedExercise(bench(), 'Bench Press', 'chest', [LoggedSet(6, 82.5)]),+ ]));+ final r = routine('P');+ fit.startRoutine(r);+ fit.endCountdown();+ fit.copyPreviousSet(0, 0);+ final st = fit.session!.exercises.first.sets.first;+ expect(st.reps, 6);+ expect(st.weight, 82.5);++ fit.addExerciseToSession(fit.matchExerciseByName('Barbell Squat')!.id);+ final first = fit.session!.exercises.first.id;+ fit.moveSessionExercise(0, 1);+ expect(fit.session!.exercises[1].id, first);+ fit.moveSessionExercise(1, -1);+ expect(fit.session!.exercises[0].id, first);+ });+ });++ group('sets inside a live workout', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineWith(List<String> ids, {String name = 'Push'}) {+ final id = fit.createRoutine(name);+ for (final ex in ids) {+ fit.toggleRoutineExercise(id, ex);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ test('changing a set carries over to the sets that still match it', () {+ final r = routineWith([idOf('Barbell Bench Press')]);+ fit.startRoutine(r);+ final sets = fit.session!.exercises.first.sets;+ for (var j = 0; j < sets.length; j++) {+ fit.setSessionWeight(0, j, 60);+ fit.setSessionReps(0, j, 10);+ }+ fit.setSessionWeight(0, sets.length - 1, 70);++ fit.setSessionWeight(0, 0, 62.5);+ fit.setSessionReps(0, 0, 8);+ expect(sets.first.weight, 62.5);+ for (var j = 1; j < sets.length - 1; j++) {+ expect(sets[j].weight, 62.5);+ expect(sets[j].reps, 8);+ }+ expect(sets.last.weight, 70);+ expect(sets.last.reps, 8);+ });++ test('a set can be removed and brought back', () {+ final r = routineWith([idOf('Barbell Bench Press')]);+ fit.startRoutine(r);+ final sets = fit.session!.exercises.single.sets;+ final before = sets.length;+ final gone = fit.removeSet(0, 1)!;+ expect(sets.length, before - 1);+ fit.insertSet(0, 1, gone);+ expect(sets.length, before);+ expect(identical(sets[1], gone), isTrue);+ });++ test('a warm-up added by mistake goes away in one tap', () {+ final r = routineWith([idOf('Barbell Bench Press')]);+ fit.startRoutine(r);+ final working = fit.session!.exercises.single.sets.length;+ fit.addWarmupSets(0);+ expect(fit.hasWarmup(0), isTrue);+ fit.removeWarmupSets(0);+ expect(fit.hasWarmup(0), isFalse);+ expect(fit.session!.exercises.single.sets.length, working);+ });++ test('jumping and reordering keep the exercise you are on', () {+ final ids = [idOf('Barbell Bench Press'), idOf('Barbell Full Squat'), idOf('Pull Up')];+ final r = routineWith(ids);+ fit.toggleChain(r.id, ids[0]);+ fit.startRoutine(r);+ fit.goToExercise(1);+ expect(fit.currentExercise!.id, ids[1]);+ fit.reorderSessionExercise(2, 0);+ expect(fit.session!.exercises.first.id, ids[2]);+ expect(fit.currentExercise!.id, ids[1]);+ expect(fit.session!.exercises.every((e) => !e.linkedNext || e.id != ids[2]), isTrue);+ });+ });++ group('terminar el entreno solo', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ Routine oneSetEach(List<String> names) {+ final id = fit.createRoutine('Push');+ for (final name in names) {+ final ex = fit.matchExerciseByName(name)!.id;+ fit.toggleRoutineExercise(id, ex);+ fit.bumpRoutineSets(id, ex, -2);+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ Future<void> wait(Duration d) => Future<void>.delayed(d + const Duration(milliseconds: 200));++ group('#67 terminar solo', () {+ test('al marcar la última serie del último ejercicio se abre el resumen', () async {+ fit.startRoutine(oneSetEach(['Barbell Bench Press', 'Barbell Squat']));+ fit.endCountdown();+ expect(fit.route, 'session');++ fit.toggleSet(0, 0);+ await wait(WorkoutState.advanceDelay);+ expect(fit.session!.currentIndex, 1);++ fit.toggleSet(1, 0);+ expect(fit.isSessionComplete, isFalse, reason: 'primero se ve el tic marcado');+ await wait(WorkoutState.finishDelay);+ expect(fit.isSessionComplete, isTrue);+ expect(fit.sessions, hasLength(1));+ });++ test('desmarcar a tiempo lo cancela', () async {+ fit.startRoutine(oneSetEach(['Barbell Bench Press']));+ fit.endCountdown();+ fit.toggleSet(0, 0);+ fit.toggleSet(0, 0);+ await wait(WorkoutState.finishDelay);+ expect(fit.isSessionComplete, isFalse);+ });++ test('con el paso automático apagado espera al botón', () async {+ fit.toggleAutoAdvance();+ fit.startRoutine(oneSetEach(['Barbell Bench Press']));+ fit.endCountdown();+ fit.toggleSet(0, 0);+ await wait(WorkoutState.finishDelay);+ expect(fit.isSessionComplete, isFalse);+ fit.toggleAutoAdvance();+ });++ test('si quedan series atrás, vuelve a ellas en vez de terminar', () async {+ fit.startRoutine(oneSetEach(['Barbell Bench Press', 'Barbell Squat']));+ fit.endCountdown();+ fit.goToExercise(1);+ fit.toggleSet(1, 0);+ await wait(WorkoutState.finishDelay);+ expect(fit.isSessionComplete, isFalse);+ expect(fit.session!.currentIndex, 0);+ });+ });++ test('#58 el paso automático queda contado para avisar del cambio', () async {+ fit.startRoutine(oneSetEach(['Barbell Bench Press', 'Barbell Squat']));+ fit.endCountdown();+ final before = fit.autoMoves;+ fit.goToExercise(1);+ expect(fit.autoMoves, before, reason: 'moverse a mano no avisa');+ fit.goToExercise(0);+ fit.toggleSet(0, 0);+ await wait(WorkoutState.advanceDelay);+ expect(fit.autoMoves, before + 1);+ });++ test('el check puesto a mano se quita con otro toque', () {+ final today = fit.todayIndex;+ fit.toggleCheckin(today);+ expect(fit.isDayDone(today), isTrue);+ fit.toggleCheckin(today);+ expect(fit.isDayDone(today), isFalse);+ expect(fit.dateForWeekday(today).day, DateTime.now().day);+ });+ });++ group('#224 notas en el entreno', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ });++ DateTime ago(int days, [int hour = 18]) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day - days, hour);+ }++ DateTime dayAgo(int days) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day - days);+ }++ void logged(String id, int days, List<LoggedSet> sets) =>+ fit.sessions.add(LoggedSession(ago(days), 1200, [LoggedExercise(id, id, 'back', sets)]));++ test('una nota fijada sale siempre en el entreno', () {+ fit.saveNote(exerciseId: 'row', date: ago(10), kind: NoteKind.note, text: 'Asiento en el 2', pinned: true);+ logged('row', 5, [LoggedSet(8, 40)]);+ expect(fit.workoutNotesFor('row').map((n) => n.text), ['Asiento en el 2']);+ });++ test('una nota sin fijar y que no es plan no molesta', () {+ fit.saveNote(exerciseId: 'row', date: ago(1), kind: NoteKind.done, text: 'Buen día');+ expect(fit.workoutNotesFor('row'), isEmpty);+ });++ test('la próxima vez sale hoy, la próxima vez y luego desaparece', () {+ fit.saveNote(exerciseId: 'row', date: ago(0), kind: NoteKind.plan, text: 'Sube a 45');+ expect(fit.workoutNotesFor('row').single.text, 'Sube a 45');+ final old = fit.notes.single;+ fit.notes[0] = GymNote(+ id: old.id,+ exerciseId: 'row',+ date: dayAgo(3),+ kind: NoteKind.plan,+ text: old.text,+ createdAt: old.createdAt,+ );+ logged('row', 3, [LoggedSet(8, 40)]);+ expect(fit.workoutNotesFor('row').single.text, 'Sube a 45');+ logged('row', 1, [LoggedSet(8, 45)]);+ expect(fit.workoutNotesFor('row'), isEmpty);+ });++ test('solo sale el plan más reciente', () {+ fit.saveNote(exerciseId: 'row', date: ago(2), kind: NoteKind.plan, text: 'Viejo');+ fit.saveNote(exerciseId: 'row', date: ago(1), kind: NoteKind.plan, text: 'Nuevo');+ expect(fit.workoutNotesFor('row').map((n) => n.text), ['Nuevo']);+ });++ test('fijar y soltar se guarda, y una nota general no se puede fijar', () {+ fit.saveNote(exerciseId: 'row', date: ago(0), kind: NoteKind.note, text: 'Polea 19');+ final id = fit.notes.single.id;+ fit.setNotePinned(id, true);+ final data = jsonDecode(jsonEncode(fit.toJson())) as Map<String, dynamic>;+ fit.applyBackup(data);+ expect(fit.noteById(id)!.pinned, isTrue);+ fit.setNotePinned(id, false);+ expect(fit.workoutNotesFor('row'), isEmpty);+ fit.saveNote(exerciseId: '', date: ago(0), kind: NoteKind.note, text: 'General', pinned: true);+ expect(fit.notes.last.pinned, isFalse);+ });++ test('editar sin decir nada conserva la chincheta', () {+ fit.saveNote(exerciseId: 'row', date: ago(0), kind: NoteKind.note, text: 'A', pinned: true);+ final id = fit.notes.single.id;+ fit.saveNote(id: id, exerciseId: 'row', date: ago(0), kind: NoteKind.note, text: 'B');+ expect(fit.noteById(id)!.pinned, isTrue);+ });+ });++ group('series cluster y duplicadas', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.onboarded = true;+ fit.setUnits('kg');+ setAppLanguage('en');+ });++ group('#250 series cluster', () {+ test('es un tipo de serie más y no rompe los guardados viejos', () {+ expect(SetKind.values.last, SetKind.cluster);+ expect(setKindFrom(SetKind.restPause.index), SetKind.restPause);+ final back = LoggedSet.fromJson(LoggedSet(9, 80, kind: SetKind.cluster).toJson());+ expect(back.kind, SetKind.cluster);+ expect(back.counts, isTrue);+ });++ test('viaja en el plan compartido', () {+ final plans = parsePlan('{"name":"A","exercises":[{"name":"Barbell Full Squat",'+ '"plan":[{"type":"cluster","reps":12,"weight":100}]}]}');+ expect(plans.single.items.single.plan.single.kind, SetKind.cluster.index);+ fit.applyPlan(plans);+ final r = fit.routines.single;+ expect(fit.exportPlanJson([r]), contains('"type": "cluster"'));+ });+ });++ group('deslizar para duplicar una serie', () {+ test('la copia va justo debajo, sin marcar, y se puede deshacer', () {+ fit.startWorkout();+ fit.toggleMuscle('chest');+ fit.trainContinue();+ fit.startSession();+ final sets = fit.session!.exercises.first.sets;+ final before = sets.length;+ fit.setSessionReps(0, 0, 7);+ fit.setSessionWeight(0, 0, 42.5);+ fit.toggleSet(0, 0);+ final copy = fit.duplicateSet(0, 0)!;+ expect(sets.length, before + 1);+ expect(identical(sets[1], copy), isTrue);+ expect(copy.done, isFalse);+ expect((copy.reps, copy.weight), (7, 42.5));+ fit.removeSetObject(0, copy);+ expect(sets.length, before);+ expect(sets.contains(copy), isFalse);+ });+ });+ });++ group('#122 salir del entreno', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ tearDown(() {+ if (fit.session != null) fit.saveAndExit();+ });++ String idOf(String name) => fit.matchExerciseByName(name)!.id;++ Routine routineOf(List<String> names) {+ final id = fit.createRoutine('Push');+ for (final name in names) {+ fit.toggleRoutineExercise(id, idOf(name));+ }+ return fit.routines.firstWhere((r) => r.id == id);+ }++ test('salir pausa y deja volver donde estabas', () {+ fit.startRoutine(routineOf(['Barbell Bench Press']));+ fit.endCountdown();+ fit.stepOutOfSession();+ expect(fit.route, 'home');+ expect(fit.sessionPaused, isTrue);+ expect(fit.sessionParked, isTrue);++ fit.stepBackIntoSession();+ expect(fit.route, 'session');+ expect(fit.sessionPaused, isFalse);+ });++ test('empezar otra cosa con uno aparcado vuelve al aparcado', () {+ fit.startRoutine(routineOf(['Barbell Bench Press']));+ fit.endCountdown();+ final session = fit.session;+ fit.stepOutOfSession();+ fit.startRoutine(routineOf(['Barbell Squat']));+ expect(fit.session, same(session));+ expect(fit.route, 'session');+ });+ });+}