Files
pluriwave/test/pantallas/pantalla_alarma_sonando_test.dart
T
Javier Bautista Fernández 29f7d54e85
Build & Deploy PluriWave / Análisis de código (push) Successful in 25s
Build & Deploy PluriWave / Build APK + AAB release (push) Successful in 2m25s
fix(alarm): fail-safe alarm system overhaul (SDD alarm-system-overhaul, slice A)
Root-cause fix for the unstoppable-alarm incident (alarm rang 15 minutes,
only uninstall silenced it) plus systematic hardening of every stop path.

Native (Kotlin):
- Verified stop: stopActiveAlarm now derives its result from the real
  post-teardown state (companion instance + synchronous stopEverything +
  activeRingingId check) instead of reporting unconditional success.
- Atomic teardown: every stop path (stop action, notification button,
  snooze, missed, onDestroy, startForeground failure) funnels through one
  stopEverything() covering audio, wakelock, notification, foreground
  state and firing-record cleanup; player.release() guarded.
- Bounded ringing: 10-minute auto-silence armed via AlarmManager fires a
  FIRED->MISSED transition with a localized missed-alarm notification;
  repeating alarms keep their native rearm, deleted alarms never produce
  ghost MISSED notifications.
- Durable firing record with onStartCommand re-validation (resurrection
  guard) and boot-time stale cleanup; firing records cleared on every
  refuse/mismatch/cancel path.
- New notification-only dismissal channel (dismissAlarmNotificationOnly)
  so UI-level dedup can never kill a live ring's audio.

Flutter (Dart):
- Stop/disable/edit/delete of a ringing alarm always attempt to silence
  it; on native-query failure the stop falls back toward silence via the
  id-scoped legacy stop.
- Verified-stop results surface failures: the ringing screen keeps
  dismiss-by-design on success, but on a verified failure it stays up
  with a persistent force-stop banner (guarded against double-dismiss)
  and auto-dismisses if the ring ends externally (missed/notification).
- Missed events sync alarm bookkeeping without opening the ringing UI.
- 4 new l10n keys translated across all 13 locales (ARB guard green).

550 tests green, analyzer clean. Reviewed in 3 adversarial 4-lens rounds
(2 deterministic + 1 refuter-corroborated critical fixed); formal
gentle-ai receipt waived by maintainer authorization (correction scope
legitimately exceeded the frozen genesis paths). On-device QA checklist
in openspec/changes/alarm-system-overhaul/tasks.md pending before
archive.
2026-07-22 23:52:36 +02:00

294 lines
10 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pluriwave/estado/estado_alarmas.dart';
import 'package:pluriwave/estado/estado_radio.dart';
import 'package:pluriwave/l10n/gen/app_localizations.dart';
import 'package:pluriwave/modelos/alarma_musical.dart';
import 'package:pluriwave/modelos/emisora.dart';
import 'package:pluriwave/pantallas/pantalla_alarma_sonando.dart';
import 'package:pluriwave/servicios/servicio_alarmas.dart';
import 'package:pluriwave/servicios/servicio_alarmas_android.dart';
import 'package:pluriwave/servicios/servicio_audio.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../helpers/fakes.dart';
import '../helpers/fakes_alarmas.dart';
class _Entorno {
_Entorno({
required this.estadoAlarmas,
required this.android,
required this.audio,
});
final EstadoAlarmas estadoAlarmas;
final FakePuertoAlarmasAndroid android;
final FakeServicioAudio audio;
}
Future<_Entorno> _montarPantalla(
WidgetTester tester, {
int snoozeMinutos = 5,
int fadeInSegundos = 0,
}) async {
tester.view.physicalSize = const Size(1440, 3200);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final audio = FakeServicioAudio();
audio.emitirEstado(EstadoReproduccion.reproduciendo);
final radio = EstadoRadio(
audio: audio,
favoritos: FakeServicioFavoritos(),
radio: FakeServicioRadio(),
servicioEcualizador: FakeServicioEcualizador(),
servicioGrabacion: FakeServicioGrabacionRadioInactiva(),
iniciarAutomaticamente: false,
);
addTearDown(radio.dispose);
final android = FakePuertoAlarmasAndroid();
// Mutable clock: the alarm is saved at 7:00 and the screen mounts at ring
// time (7:30:10), so snooze anchors to the RINGING occurrence — the only
// scenario the ringing screen can exist in.
var ahora = DateTime(2026, 6, 11, 7, 0);
final estadoAlarmas = EstadoAlarmas(
servicio: ServicioAlarmas(reloj: () => ahora),
android: android,
iniciarAutomaticamente: false,
);
addTearDown(estadoAlarmas.dispose);
addTearDown(android.dispose);
await estadoAlarmas.guardarAlarma(
AlarmaMusical(
id: 'ring1',
nombre: 'Despertar',
hora: 7,
minuto: 30,
tipoProgramacion: TipoProgramacionAlarma.diaria,
diasSemana: const [],
snoozeMinutos: snoozeMinutos,
fadeInSegundos: fadeInSegundos,
emisora: const Emisora(
uuid: 'e1',
nombre: 'Radio Uno',
url: 'https://radio.example/stream',
),
),
);
// The screen mounts at ring time: 10s after the 7:30 occurrence fired.
ahora = DateTime(2026, 6, 11, 7, 30, 10);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider<EstadoRadio>.value(value: radio),
ChangeNotifierProvider<EstadoAlarmas>.value(value: estadoAlarmas),
],
child: MaterialApp(
locale: const Locale('es'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
// A real Scaffold (not a bare SizedBox) is required: the
// ScaffoldMessenger only displays a SnackBar through a currently
// registered ScaffoldState, and the ringing screen's own Scaffold
// pops off the tree by the time the SS-3a force-stop SnackBar shows
// (mirrors pantalla_alarma_sonando_dismiss_guard_test.dart).
home: const Scaffold(body: SizedBox.shrink()),
),
),
);
final navigator = tester.state<NavigatorState>(find.byType(Navigator));
unawaited(
navigator.push(
MaterialPageRoute<void>(
builder:
(_) =>
PantallaAlarmaSonando(alarma: estadoAlarmas.alarmas.single),
fullscreenDialog: true,
),
),
);
await tester.pumpAndSettle();
return _Entorno(estadoAlarmas: estadoAlarmas, android: android, audio: audio);
}
void main() {
final l10n = lookupAppLocalizations(const Locale('es'));
setUp(() {
SharedPreferences.setMockInitialValues({});
});
testWidgets(
'muestra botones de posponer 3/5/10 mas el personalizado (S2-R1-A/C)',
(tester) async {
await _montarPantalla(tester, snoozeMinutos: 7);
expect(find.text(l10n.alarmSnoozeOptionLabel(3)), findsOneWidget);
expect(find.text(l10n.alarmSnoozeOptionLabel(5)), findsOneWidget);
expect(find.text(l10n.alarmSnoozeOptionLabel(7)), findsOneWidget);
expect(find.text(l10n.alarmSnoozeOptionLabel(10)), findsOneWidget);
expect(find.text(l10n.stopAlarmAction), findsOneWidget);
},
);
testWidgets(
'no duplica el boton cuando snoozeMinutos coincide con una opcion fija',
(tester) async {
await _montarPantalla(tester, snoozeMinutos: 5);
expect(find.text(l10n.alarmSnoozeOptionLabel(3)), findsOneWidget);
expect(find.text(l10n.alarmSnoozeOptionLabel(5)), findsOneWidget);
expect(find.text(l10n.alarmSnoozeOptionLabel(10)), findsOneWidget);
},
);
testWidgets(
'posponer 5 min pospone la alarma y cierra la pantalla (S2-R1-B)',
(tester) async {
final entorno = await _montarPantalla(tester, snoozeMinutos: 5);
await tester.tap(find.text(l10n.alarmSnoozeOptionLabel(5)));
await tester.pumpAndSettle();
final alarma = entorno.estadoAlarmas.alarmas.single;
expect(alarma.snoozeHasta, DateTime(2026, 6, 11, 7, 35));
expect(find.byType(PantallaAlarmaSonando), findsNothing);
// posponerAlarma oculta la notificacion nativa (mismo stop path que
// el boton de detener) y reprograma con el snooze.
expect(entorno.android.ocultadas, contains('ring1'));
expect(
entorno.android.programadas.last.snoozeHasta,
DateTime(2026, 6, 11, 7, 35),
);
},
);
group('detener y el force-stop de fallback', () {
testWidgets(
'detener fallido NO cierra la pantalla y muestra el banner de forzar '
'detencion; forzar detencion con exito si la cierra (SS-3a/SS-3b)',
(tester) async {
final entorno = await _montarPantalla(tester);
entorno.android.fallaDetener = true;
await tester.tap(find.text(l10n.stopAlarmAction));
await tester.pumpAndSettle();
// Verified stop failure (Finding A): the alarm is still ringing, so
// the ringing screen must stay up — dismissing here would hide the
// only retry affordance while the native ring keeps sounding.
expect(find.byType(PantallaAlarmaSonando), findsOneWidget);
expect(find.text(l10n.alarmStopFailedMessage), findsOneWidget);
expect(find.text(l10n.alarmForceStopAction), findsOneWidget);
// Retry via the banner's own action succeeds this time (SS-3b).
entorno.android.fallaDetener = false;
await tester.tap(find.text(l10n.alarmForceStopAction));
await tester.pumpAndSettle();
expect(find.byType(PantallaAlarmaSonando), findsNothing);
},
);
testWidgets(
'detener confirmado no muestra el banner de fallo (SS-3c)',
(tester) async {
final entorno = await _montarPantalla(tester);
await tester.tap(find.text(l10n.stopAlarmAction));
await tester.pumpAndSettle();
expect(find.byType(PantallaAlarmaSonando), findsNothing);
expect(find.text(l10n.alarmStopFailedMessage), findsNothing);
expect(entorno.android.detencionesActivas, isNotEmpty);
},
);
testWidgets(
'forzar detencion: invocacion superpuesta es no-op y tras un fallo '
'el boton sigue funcionando (RES-2)',
(tester) async {
final entorno = await _montarPantalla(tester);
entorno.android.fallaDetener = true;
await tester.tap(find.text(l10n.stopAlarmAction));
await tester.pumpAndSettle();
final llamadasPrevias = entorno.android.detencionesActivas.length;
entorno.android.detenerActivoGate = Completer<void>();
await tester.tap(find.text(l10n.alarmForceStopAction));
await tester.pump();
await tester.tap(find.text(l10n.alarmForceStopAction));
await tester.pump();
expect(
entorno.android.detencionesActivas.length,
llamadasPrevias + 1,
reason: 'la segunda invocacion superpuesta debe ser no-op',
);
entorno.android.detenerActivoGate!.complete();
await tester.pumpAndSettle();
// Fallo confirmado: el banner sigue y el guard debe haberse
// reseteado para permitir un reintento.
expect(find.byType(PantallaAlarmaSonando), findsOneWidget);
entorno.android.fallaDetener = false;
await tester.tap(find.text(l10n.alarmForceStopAction));
await tester.pumpAndSettle();
expect(find.byType(PantallaAlarmaSonando), findsNothing);
},
);
});
group('reconciliacion de fin de ring externo (RES-1)', () {
testWidgets(
'si la alarma se registra como perdida externamente, la pantalla se '
'auto-cierra',
(tester) async {
final entorno = await _montarPantalla(tester);
entorno.android.emitirEvento(
EventoAlarmaAndroid(
alarmaId: 'ring1',
titulo: 'Despertar',
accion: EventoAlarmaAndroid.accionMissed,
),
);
await tester.pumpAndSettle();
expect(find.byType(PantallaAlarmaSonando), findsNothing);
},
);
});
group('salidas del ring fuera de los botones', () {
testWidgets(
'el boton atras del sistema se comporta como Detener: finaliza la '
'ejecucion y cierra',
(tester) async {
final entorno = await _montarPantalla(tester);
// Simulate the SYSTEM back (routes through PopScope via the
// binding), not a direct Navigator.pop: a plain pop only runs
// dispose(), which would leave no alarm UI anywhere to stop the
// ring (native audio teardown is driven by finalizarEjecucion, the
// same path Detener uses).
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.byType(PantallaAlarmaSonando), findsNothing);
expect(
entorno.android.ocultadas,
contains('ring1'),
reason:
'atras debe finalizar la ejecucion (mismo camino que Detener)',
);
},
);
});
}