feat: 实现日历提醒 in-app fallback 机制及通知服务重构
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:social_app/features/calendar/reminders/reminder_action_dedupe_store.dart';
|
||||
|
||||
void main() {
|
||||
const dedupeKey = 'calendar_reminder_action_dedupe_v1';
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
});
|
||||
|
||||
test('markIfNew returns true first and false for duplicate id', () async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final store = ReminderActionDedupeStore(prefs);
|
||||
|
||||
expect(await store.markIfNew('action_1'), isTrue);
|
||||
expect(await store.markIfNew('action_1'), isFalse);
|
||||
});
|
||||
|
||||
test('markIfNew dedupes after store re-initialization', () async {
|
||||
final firstPrefs = await SharedPreferences.getInstance();
|
||||
final firstStore = ReminderActionDedupeStore(firstPrefs);
|
||||
|
||||
expect(await firstStore.markIfNew('action_restart'), isTrue);
|
||||
|
||||
final secondPrefs = await SharedPreferences.getInstance();
|
||||
final secondStore = ReminderActionDedupeStore(secondPrefs);
|
||||
|
||||
expect(await secondStore.markIfNew('action_restart'), isFalse);
|
||||
});
|
||||
|
||||
test('markIfNew trims history to max capacity', () async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final store = ReminderActionDedupeStore(prefs);
|
||||
|
||||
for (var i = 0; i < 513; i++) {
|
||||
expect(await store.markIfNew('action_$i'), isTrue);
|
||||
}
|
||||
|
||||
final stored = prefs.getStringList(dedupeKey)!;
|
||||
expect(stored.length, 512);
|
||||
expect(stored.first, 'action_1');
|
||||
expect(stored.last, 'action_512');
|
||||
});
|
||||
|
||||
test(
|
||||
'markIfNew is serialized and does not return true twice in parallel',
|
||||
() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final store = ReminderActionDedupeStore(
|
||||
prefs,
|
||||
setStringList: (key, value) async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
return prefs.setStringList(key, value);
|
||||
},
|
||||
);
|
||||
|
||||
final results = await Future.wait<bool>([
|
||||
store.markIfNew('parallel_action'),
|
||||
store.markIfNew('parallel_action'),
|
||||
]);
|
||||
|
||||
expect(results.where((item) => item).length, 1);
|
||||
expect(results.where((item) => !item).length, 1);
|
||||
},
|
||||
);
|
||||
|
||||
test('markIfNew returns false when persistence write fails', () async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final store = ReminderActionDedupeStore(
|
||||
prefs,
|
||||
setStringList: (key, value) async => false,
|
||||
);
|
||||
|
||||
expect(await store.markIfNew('action_write_fail'), isFalse);
|
||||
expect(prefs.getStringList(dedupeKey), isNull);
|
||||
});
|
||||
}
|
||||
@@ -33,7 +33,7 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
test('cancel archives remotely and cancels local reminder', () async {
|
||||
test('archive archives remotely and cancels local reminder', () async {
|
||||
when(
|
||||
() => notificationService.cancelEventReminder('evt_1'),
|
||||
).thenAnswer((_) async {});
|
||||
@@ -42,7 +42,7 @@ void main() {
|
||||
).thenAnswer((_) async => null);
|
||||
|
||||
await executor.handleAction(
|
||||
action: ReminderAction.cancel,
|
||||
action: ReminderAction.archive,
|
||||
payload: ReminderPayload(
|
||||
eventId: 'evt_1',
|
||||
title: 'sync',
|
||||
@@ -66,7 +66,7 @@ void main() {
|
||||
).thenThrow(Exception('offline'));
|
||||
|
||||
await executor.handleAction(
|
||||
action: ReminderAction.cancel,
|
||||
action: ReminderAction.archive,
|
||||
payload: ReminderPayload(
|
||||
eventId: 'evt_1',
|
||||
title: 'sync',
|
||||
@@ -114,4 +114,60 @@ void main() {
|
||||
).called(1);
|
||||
verifyNever(() => calendarService.archiveEvent(any()));
|
||||
});
|
||||
|
||||
test('fromValue throws on unknown action', () {
|
||||
expect(
|
||||
() => ReminderAction.fromValue('unknown_action'),
|
||||
throwsA(isA<ArgumentError>()),
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'aggregate action falls back to eventId when aggregateIds is empty',
|
||||
() async {
|
||||
when(
|
||||
() => notificationService.cancelEventReminder('evt_fallback'),
|
||||
).thenAnswer((_) async {});
|
||||
when(
|
||||
() => calendarService.archiveEvent('evt_fallback'),
|
||||
).thenAnswer((_) async => null);
|
||||
|
||||
await executor.handleAction(
|
||||
action: ReminderAction.archive,
|
||||
payload: ReminderPayload(
|
||||
eventId: 'evt_fallback',
|
||||
title: 'sync',
|
||||
startAt: DateTime.parse('2026-03-18T16:00:00+08:00'),
|
||||
timezone: 'Asia/Shanghai',
|
||||
mode: ReminderPayloadMode.aggregate,
|
||||
aggregateIds: const <String>[],
|
||||
),
|
||||
);
|
||||
|
||||
verify(
|
||||
() => notificationService.cancelEventReminder('evt_fallback'),
|
||||
).called(1);
|
||||
verify(() => calendarService.archiveEvent('evt_fallback')).called(1);
|
||||
},
|
||||
);
|
||||
|
||||
test('replay keeps pending item when targetStatus is not archived', () async {
|
||||
const opId = 'op_non_archived';
|
||||
await outboxStore.enqueue(
|
||||
ReminderOutboxItem(
|
||||
opId: opId,
|
||||
eventId: 'evt_1',
|
||||
action: ReminderAction.archive,
|
||||
targetStatus: 'ignored',
|
||||
occurredAt: DateTime.parse('2026-03-18T16:00:00+08:00'),
|
||||
),
|
||||
);
|
||||
|
||||
await executor.replayPendingActions();
|
||||
|
||||
final pending = await outboxStore.listPending();
|
||||
expect(pending.length, 1);
|
||||
expect(pending.first.opId, opId);
|
||||
verifyNever(() => calendarService.archiveEvent(any()));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:social_app/features/calendar/reminders/ui/widgets/reminder_action_sheet.dart';
|
||||
|
||||
void main() {
|
||||
Future<void> pumpSheet(
|
||||
WidgetTester tester, {
|
||||
required VoidCallback onSnooze,
|
||||
required VoidCallback onArchive,
|
||||
}) {
|
||||
return tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ReminderActionSheet(onSnooze: onSnooze, onArchive: onArchive),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('tap snooze button triggers onSnooze', (tester) async {
|
||||
var snoozed = false;
|
||||
|
||||
await pumpSheet(tester, onSnooze: () => snoozed = true, onArchive: () {});
|
||||
|
||||
await tester.tap(find.text('稍后提醒'));
|
||||
await tester.pump();
|
||||
|
||||
expect(snoozed, isTrue);
|
||||
});
|
||||
|
||||
testWidgets('tap archive button triggers onArchive', (tester) async {
|
||||
var archived = false;
|
||||
|
||||
await pumpSheet(tester, onSnooze: () {}, onArchive: () => archived = true);
|
||||
|
||||
await tester.tap(find.text('归档'));
|
||||
await tester.pump();
|
||||
|
||||
expect(archived, isTrue);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:social_app/features/calendar/reminders/reminder_cold_start_queue.dart';
|
||||
|
||||
void main() {
|
||||
test('replays queued actions in enqueue order', () async {
|
||||
final queue = ReminderColdStartQueue();
|
||||
final events = <String>[];
|
||||
|
||||
queue.enqueue(() async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
events.add('first');
|
||||
});
|
||||
queue.enqueue(() async {
|
||||
events.add('second');
|
||||
});
|
||||
queue.enqueue(() async {
|
||||
events.add('third');
|
||||
});
|
||||
|
||||
await queue.replay();
|
||||
|
||||
expect(events, <String>['first', 'second', 'third']);
|
||||
});
|
||||
|
||||
test('single failure does not block following queued actions', () async {
|
||||
final queue = ReminderColdStartQueue();
|
||||
final events = <String>[];
|
||||
final errors = <Object>[];
|
||||
|
||||
queue.enqueue(() async {
|
||||
events.add('before');
|
||||
});
|
||||
queue.enqueue(() async {
|
||||
throw StateError('boom');
|
||||
});
|
||||
queue.enqueue(() async {
|
||||
events.add('after');
|
||||
});
|
||||
|
||||
final observableQueue = ReminderColdStartQueue(
|
||||
onTaskError: (Object error, StackTrace _) {
|
||||
errors.add(error);
|
||||
},
|
||||
);
|
||||
|
||||
observableQueue.enqueue(() async {
|
||||
throw StateError('boom_observable');
|
||||
});
|
||||
|
||||
await queue.replay();
|
||||
await observableQueue.replay();
|
||||
|
||||
expect(events, <String>['before', 'after']);
|
||||
expect(errors.length, 1);
|
||||
expect(errors.first, isA<StateError>());
|
||||
});
|
||||
|
||||
test('concurrent replay calls join the same in-flight replay', () async {
|
||||
final queue = ReminderColdStartQueue();
|
||||
final taskGate = Completer<void>();
|
||||
var runCount = 0;
|
||||
var secondReplayCompleted = false;
|
||||
|
||||
queue.enqueue(() async {
|
||||
runCount += 1;
|
||||
await taskGate.future;
|
||||
});
|
||||
|
||||
final firstReplay = queue.replay();
|
||||
final secondReplay = queue.replay().then((_) {
|
||||
secondReplayCompleted = true;
|
||||
});
|
||||
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
expect(secondReplayCompleted, isFalse);
|
||||
|
||||
taskGate.complete();
|
||||
await Future.wait(<Future<void>>[firstReplay, secondReplay]);
|
||||
|
||||
expect(runCount, 1);
|
||||
expect(secondReplayCompleted, isTrue);
|
||||
});
|
||||
|
||||
test('replay on empty queue does not block future enqueued tasks', () async {
|
||||
final queue = ReminderColdStartQueue();
|
||||
final events = <String>[];
|
||||
|
||||
await queue.replay();
|
||||
|
||||
queue.enqueue(() async {
|
||||
events.add('after_empty_replay');
|
||||
});
|
||||
|
||||
await queue.replay();
|
||||
|
||||
expect(events, <String>['after_empty_replay']);
|
||||
});
|
||||
|
||||
test('task-triggered replay reuses in-flight replay and completes', () async {
|
||||
final queue = ReminderColdStartQueue();
|
||||
final events = <String>[];
|
||||
var nestedReplayCompleted = false;
|
||||
|
||||
queue.enqueue(() async {
|
||||
events.add('first');
|
||||
queue.replay().then((_) {
|
||||
nestedReplayCompleted = true;
|
||||
});
|
||||
});
|
||||
|
||||
queue.enqueue(() async {
|
||||
events.add('second');
|
||||
});
|
||||
|
||||
await queue.replay();
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(events, <String>['first', 'second']);
|
||||
expect(nestedReplayCompleted, isTrue);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:social_app/core/notifications/local_notification_service.dart';
|
||||
import 'package:social_app/core/notifications/reminder_notification_callbacks.dart';
|
||||
import 'package:social_app/features/calendar/reminders/models/reminder_action.dart';
|
||||
import 'package:social_app/features/calendar/reminders/models/reminder_payload.dart';
|
||||
|
||||
class MockFlutterLocalNotificationsPlugin extends Mock
|
||||
implements FlutterLocalNotificationsPlugin {}
|
||||
|
||||
void main() {
|
||||
setUpAll(() {
|
||||
registerFallbackValue(
|
||||
const InitializationSettings(
|
||||
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
|
||||
iOS: DarwinInitializationSettings(),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
late MockFlutterLocalNotificationsPlugin plugin;
|
||||
late LocalNotificationService service;
|
||||
late List<ReminderAction> handledActions;
|
||||
late List<ReminderPayload> presentedPayloads;
|
||||
DidReceiveNotificationResponseCallback? callback;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
plugin = MockFlutterLocalNotificationsPlugin();
|
||||
service = LocalNotificationService(plugin: plugin);
|
||||
handledActions = <ReminderAction>[];
|
||||
presentedPayloads = <ReminderPayload>[];
|
||||
|
||||
when(
|
||||
() => plugin.initialize(
|
||||
any(),
|
||||
onDidReceiveNotificationResponse: any(
|
||||
named: 'onDidReceiveNotificationResponse',
|
||||
),
|
||||
onDidReceiveBackgroundNotificationResponse: any(
|
||||
named: 'onDidReceiveBackgroundNotificationResponse',
|
||||
),
|
||||
),
|
||||
).thenAnswer((invocation) async {
|
||||
callback =
|
||||
invocation.namedArguments[#onDidReceiveNotificationResponse]
|
||||
as DidReceiveNotificationResponseCallback?;
|
||||
return true;
|
||||
});
|
||||
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(null);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
IOSFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(null);
|
||||
|
||||
service.bindActionHandler(({required action, required payload}) async {
|
||||
handledActions.add(action);
|
||||
});
|
||||
service.bindInAppReminderHandler((payload) async {
|
||||
presentedPayloads.add(payload);
|
||||
});
|
||||
await ReminderNotificationCallbacks.bindResponseHandler(
|
||||
service.handleNotificationResponse,
|
||||
);
|
||||
|
||||
await service.initialize();
|
||||
});
|
||||
|
||||
test('cancel action from system notification maps to archive', () async {
|
||||
callback!(
|
||||
NotificationResponse(
|
||||
notificationResponseType:
|
||||
NotificationResponseType.selectedNotificationAction,
|
||||
id: 101,
|
||||
actionId: 'cancel',
|
||||
payload: jsonEncode(
|
||||
ReminderPayload(
|
||||
eventId: 'evt_1',
|
||||
title: 'sync',
|
||||
startAt: DateTime.parse('2026-03-19T10:00:00+08:00'),
|
||||
timezone: 'Asia/Shanghai',
|
||||
).toJson(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(handledActions, [ReminderAction.archive]);
|
||||
});
|
||||
|
||||
test('duplicate notification response is handled only once', () async {
|
||||
final response = NotificationResponse(
|
||||
notificationResponseType:
|
||||
NotificationResponseType.selectedNotificationAction,
|
||||
id: 201,
|
||||
actionId: 'cancel',
|
||||
payload: jsonEncode(
|
||||
ReminderPayload(
|
||||
eventId: 'evt_2',
|
||||
title: 'retro',
|
||||
startAt: DateTime.parse('2026-03-19T11:00:00+08:00'),
|
||||
timezone: 'Asia/Shanghai',
|
||||
).toJson(),
|
||||
),
|
||||
);
|
||||
|
||||
callback!(response);
|
||||
callback!(response);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(handledActions, [ReminderAction.archive]);
|
||||
});
|
||||
|
||||
test('notification body tap forwards payload to in-app presenter', () async {
|
||||
callback!(
|
||||
NotificationResponse(
|
||||
notificationResponseType: NotificationResponseType.selectedNotification,
|
||||
id: 301,
|
||||
payload: jsonEncode(
|
||||
ReminderPayload(
|
||||
eventId: 'evt_3',
|
||||
title: 'daily sync',
|
||||
startAt: DateTime.parse('2026-03-19T12:00:00+08:00'),
|
||||
timezone: 'Asia/Shanghai',
|
||||
).toJson(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
|
||||
expect(presentedPayloads.map((item) => item.eventId), ['evt_3']);
|
||||
expect(handledActions, isEmpty);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:social_app/core/notifications/reminder_notification_callbacks.dart';
|
||||
|
||||
void main() {
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
await ReminderNotificationCallbacks.resetForTest();
|
||||
});
|
||||
|
||||
test('contains top-level vm entry-point background callback', () async {
|
||||
final source = await File(
|
||||
'lib/core/notifications/reminder_notification_callbacks.dart',
|
||||
).readAsString();
|
||||
|
||||
expect(source, contains("@pragma('vm:entry-point')"));
|
||||
expect(source, contains('Future<void> reminderNotificationTapBackground('));
|
||||
});
|
||||
|
||||
test(
|
||||
'dispatches foreground and background responses to bound handler',
|
||||
() async {
|
||||
final handledIds = <int?>[];
|
||||
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
|
||||
handledIds.add(response.id);
|
||||
});
|
||||
|
||||
await ReminderNotificationCallbacks.onForegroundResponse(
|
||||
NotificationResponse(
|
||||
notificationResponseType:
|
||||
NotificationResponseType.selectedNotificationAction,
|
||||
id: 10,
|
||||
),
|
||||
);
|
||||
await reminderNotificationTapBackground(
|
||||
NotificationResponse(
|
||||
notificationResponseType:
|
||||
NotificationResponseType.selectedNotificationAction,
|
||||
id: 20,
|
||||
),
|
||||
);
|
||||
|
||||
expect(handledIds, <int?>[10, 20]);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'queues background response when handler is unbound and drains later',
|
||||
() async {
|
||||
await reminderNotificationTapBackground(
|
||||
NotificationResponse(
|
||||
notificationResponseType:
|
||||
NotificationResponseType.selectedNotificationAction,
|
||||
id: 99,
|
||||
),
|
||||
);
|
||||
|
||||
final handledIds = <int?>[];
|
||||
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
|
||||
handledIds.add(response.id);
|
||||
});
|
||||
|
||||
expect(handledIds, <int?>[99]);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'queues foreground response when handler is unbound and drains later',
|
||||
() async {
|
||||
await ReminderNotificationCallbacks.onForegroundResponse(
|
||||
NotificationResponse(
|
||||
notificationResponseType:
|
||||
NotificationResponseType.selectedNotificationAction,
|
||||
id: 55,
|
||||
),
|
||||
);
|
||||
|
||||
final handledIds = <int?>[];
|
||||
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
|
||||
handledIds.add(response.id);
|
||||
});
|
||||
|
||||
expect(handledIds, <int?>[55]);
|
||||
},
|
||||
);
|
||||
|
||||
test('failed pending item stays queued for next bind retry', () async {
|
||||
await reminderNotificationTapBackground(
|
||||
NotificationResponse(
|
||||
notificationResponseType:
|
||||
NotificationResponseType.selectedNotificationAction,
|
||||
id: 77,
|
||||
),
|
||||
);
|
||||
|
||||
var firstAttempt = true;
|
||||
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
|
||||
if (firstAttempt) {
|
||||
firstAttempt = false;
|
||||
throw Exception('temporary failure');
|
||||
}
|
||||
});
|
||||
|
||||
final handledIds = <int?>[];
|
||||
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
|
||||
handledIds.add(response.id);
|
||||
});
|
||||
|
||||
expect(handledIds, <int?>[77]);
|
||||
});
|
||||
|
||||
test(
|
||||
'background handler failure while bound is enqueued for retry',
|
||||
() async {
|
||||
var firstAttempt = true;
|
||||
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
|
||||
if (firstAttempt) {
|
||||
firstAttempt = false;
|
||||
throw Exception('temporary failure');
|
||||
}
|
||||
});
|
||||
|
||||
await reminderNotificationTapBackground(
|
||||
NotificationResponse(
|
||||
notificationResponseType:
|
||||
NotificationResponseType.selectedNotificationAction,
|
||||
id: 123,
|
||||
),
|
||||
);
|
||||
|
||||
final handledIds = <int?>[];
|
||||
await ReminderNotificationCallbacks.bindResponseHandler((response) async {
|
||||
handledIds.add(response.id);
|
||||
});
|
||||
|
||||
expect(handledIds, <int?>[123]);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:social_app/core/notifications/local_notification_service.dart';
|
||||
import 'package:social_app/features/calendar/data/models/schedule_item_model.dart';
|
||||
import 'package:timezone/data/latest.dart' as tz_data;
|
||||
import 'package:timezone/timezone.dart' as tz;
|
||||
|
||||
class MockFlutterLocalNotificationsPlugin extends Mock
|
||||
implements FlutterLocalNotificationsPlugin {}
|
||||
|
||||
class MockAndroidFlutterLocalNotificationsPlugin extends Mock
|
||||
implements AndroidFlutterLocalNotificationsPlugin {}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUpAll(() {
|
||||
tz_data.initializeTimeZones();
|
||||
registerFallbackValue(tz.TZDateTime.now(tz.local));
|
||||
registerFallbackValue(const NotificationDetails());
|
||||
registerFallbackValue(
|
||||
const InitializationSettings(
|
||||
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
|
||||
iOS: DarwinInitializationSettings(),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
debugDefaultTargetPlatformOverride = TargetPlatform.android;
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
});
|
||||
|
||||
test(
|
||||
'tracks fallback when Android notifications permission is denied',
|
||||
() async {
|
||||
final plugin = MockFlutterLocalNotificationsPlugin();
|
||||
final androidImpl = MockAndroidFlutterLocalNotificationsPlugin();
|
||||
final fallbackEvents = <Map<String, String>>[];
|
||||
|
||||
when(
|
||||
() => plugin.initialize(
|
||||
any(),
|
||||
onDidReceiveNotificationResponse: any(
|
||||
named: 'onDidReceiveNotificationResponse',
|
||||
),
|
||||
onDidReceiveBackgroundNotificationResponse: any(
|
||||
named: 'onDidReceiveBackgroundNotificationResponse',
|
||||
),
|
||||
),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(androidImpl);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
IOSFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(null);
|
||||
|
||||
when(
|
||||
() => androidImpl.requestNotificationsPermission(),
|
||||
).thenAnswer((_) async => false);
|
||||
when(
|
||||
() => androidImpl.requestExactAlarmsPermission(),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => androidImpl.requestFullScreenIntentPermission(),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => androidImpl.areNotificationsEnabled(),
|
||||
).thenAnswer((_) async => false);
|
||||
|
||||
final service = LocalNotificationService(
|
||||
plugin: plugin,
|
||||
permissionFallbackTracker:
|
||||
({
|
||||
required actionExecutionId,
|
||||
required permissionState,
|
||||
required appLifecycleState,
|
||||
required platform,
|
||||
}) {
|
||||
fallbackEvents.add({
|
||||
'actionExecutionId': actionExecutionId,
|
||||
'permissionState': permissionState,
|
||||
'appLifecycleState': appLifecycleState,
|
||||
'platform': platform,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
await service.initialize();
|
||||
|
||||
expect(fallbackEvents.length, 1);
|
||||
expect(fallbackEvents.first['permissionState'], 'denied');
|
||||
expect(fallbackEvents.first['platform'], 'android');
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'skips reminder scheduling when Android notifications are denied',
|
||||
() async {
|
||||
final plugin = MockFlutterLocalNotificationsPlugin();
|
||||
final androidImpl = MockAndroidFlutterLocalNotificationsPlugin();
|
||||
|
||||
when(
|
||||
() => plugin.initialize(
|
||||
any(),
|
||||
onDidReceiveNotificationResponse: any(
|
||||
named: 'onDidReceiveNotificationResponse',
|
||||
),
|
||||
onDidReceiveBackgroundNotificationResponse: any(
|
||||
named: 'onDidReceiveBackgroundNotificationResponse',
|
||||
),
|
||||
),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(androidImpl);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
IOSFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(null);
|
||||
|
||||
when(
|
||||
() => androidImpl.requestNotificationsPermission(),
|
||||
).thenAnswer((_) async => false);
|
||||
when(
|
||||
() => androidImpl.requestExactAlarmsPermission(),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => androidImpl.requestFullScreenIntentPermission(),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => androidImpl.areNotificationsEnabled(),
|
||||
).thenAnswer((_) async => false);
|
||||
|
||||
final service = LocalNotificationService(plugin: plugin);
|
||||
final event = ScheduleItemModel(
|
||||
id: 'evt_1',
|
||||
ownerId: 'u1',
|
||||
title: 'sync',
|
||||
startAt: DateTime.now().add(const Duration(minutes: 20)),
|
||||
endAt: DateTime.now().add(const Duration(minutes: 50)),
|
||||
metadata: ScheduleMetadata(reminderMinutes: 15),
|
||||
);
|
||||
|
||||
await service.upsertEventReminder(event);
|
||||
|
||||
verifyNever(() => plugin.pendingNotificationRequests());
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'dispatches in-app reminder callback when notifications are denied',
|
||||
() async {
|
||||
final plugin = MockFlutterLocalNotificationsPlugin();
|
||||
final androidImpl = MockAndroidFlutterLocalNotificationsPlugin();
|
||||
final presentedEventIds = <String>[];
|
||||
|
||||
when(
|
||||
() => plugin.initialize(
|
||||
any(),
|
||||
onDidReceiveNotificationResponse: any(
|
||||
named: 'onDidReceiveNotificationResponse',
|
||||
),
|
||||
onDidReceiveBackgroundNotificationResponse: any(
|
||||
named: 'onDidReceiveBackgroundNotificationResponse',
|
||||
),
|
||||
),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(androidImpl);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
IOSFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(null);
|
||||
|
||||
when(
|
||||
() => androidImpl.requestNotificationsPermission(),
|
||||
).thenAnswer((_) async => false);
|
||||
when(
|
||||
() => androidImpl.requestExactAlarmsPermission(),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => androidImpl.requestFullScreenIntentPermission(),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => androidImpl.areNotificationsEnabled(),
|
||||
).thenAnswer((_) async => false);
|
||||
|
||||
final service = LocalNotificationService(plugin: plugin);
|
||||
service.bindInAppReminderHandler((payload) async {
|
||||
presentedEventIds.add(payload.eventId);
|
||||
});
|
||||
|
||||
final event = ScheduleItemModel(
|
||||
id: 'evt_2',
|
||||
ownerId: 'u1',
|
||||
title: 'retro',
|
||||
startAt: DateTime.now().add(const Duration(minutes: 20)),
|
||||
endAt: DateTime.now().add(const Duration(minutes: 50)),
|
||||
metadata: ScheduleMetadata(reminderMinutes: 15),
|
||||
);
|
||||
|
||||
await service.scheduleReminderAt(
|
||||
event,
|
||||
DateTime.now().add(const Duration(milliseconds: 20)),
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
|
||||
expect(presentedEventIds, contains('evt_2'));
|
||||
verifyNever(
|
||||
() => plugin.zonedSchedule(
|
||||
any(),
|
||||
any(),
|
||||
any(),
|
||||
any(),
|
||||
any(),
|
||||
payload: any(named: 'payload'),
|
||||
androidScheduleMode: any(named: 'androidScheduleMode'),
|
||||
uiLocalNotificationDateInterpretation:
|
||||
UILocalNotificationDateInterpretation.absoluteTime,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('rebuild twice only dispatches one aggregate in-app fallback', () async {
|
||||
final plugin = MockFlutterLocalNotificationsPlugin();
|
||||
final androidImpl = MockAndroidFlutterLocalNotificationsPlugin();
|
||||
final presentedPayloads = <String>[];
|
||||
|
||||
when(
|
||||
() => plugin.initialize(
|
||||
any(),
|
||||
onDidReceiveNotificationResponse: any(
|
||||
named: 'onDidReceiveNotificationResponse',
|
||||
),
|
||||
onDidReceiveBackgroundNotificationResponse: any(
|
||||
named: 'onDidReceiveBackgroundNotificationResponse',
|
||||
),
|
||||
),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(androidImpl);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
IOSFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(null);
|
||||
|
||||
when(
|
||||
() => androidImpl.requestNotificationsPermission(),
|
||||
).thenAnswer((_) async => false);
|
||||
when(
|
||||
() => androidImpl.requestExactAlarmsPermission(),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => androidImpl.requestFullScreenIntentPermission(),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => androidImpl.areNotificationsEnabled(),
|
||||
).thenAnswer((_) async => false);
|
||||
|
||||
final service = LocalNotificationService(plugin: plugin);
|
||||
service.bindInAppReminderHandler((payload) async {
|
||||
presentedPayloads.add(payload.title);
|
||||
});
|
||||
|
||||
final startAt = DateTime.now().add(const Duration(milliseconds: 50));
|
||||
final event1 = ScheduleItemModel(
|
||||
id: 'evt_a',
|
||||
ownerId: 'u1',
|
||||
title: 'evt_a',
|
||||
startAt: startAt,
|
||||
endAt: startAt.add(const Duration(minutes: 30)),
|
||||
metadata: ScheduleMetadata(reminderMinutes: 0),
|
||||
);
|
||||
final event2 = ScheduleItemModel(
|
||||
id: 'evt_b',
|
||||
ownerId: 'u1',
|
||||
title: 'evt_b',
|
||||
startAt: startAt,
|
||||
endAt: startAt.add(const Duration(minutes: 30)),
|
||||
metadata: ScheduleMetadata(reminderMinutes: 0),
|
||||
);
|
||||
|
||||
await service.rebuildUpcomingReminders([event1, event2]);
|
||||
await service.rebuildUpcomingReminders([event1, event2]);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 180));
|
||||
|
||||
expect(
|
||||
presentedPayloads.where((title) => title.contains('你有2个日程提醒')).length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'rebuild clears stale in-app fallback timers for removed events',
|
||||
() async {
|
||||
final plugin = MockFlutterLocalNotificationsPlugin();
|
||||
final androidImpl = MockAndroidFlutterLocalNotificationsPlugin();
|
||||
final presentedEventIds = <String>[];
|
||||
|
||||
when(
|
||||
() => plugin.initialize(
|
||||
any(),
|
||||
onDidReceiveNotificationResponse: any(
|
||||
named: 'onDidReceiveNotificationResponse',
|
||||
),
|
||||
onDidReceiveBackgroundNotificationResponse: any(
|
||||
named: 'onDidReceiveBackgroundNotificationResponse',
|
||||
),
|
||||
),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(androidImpl);
|
||||
when(
|
||||
() => plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
IOSFlutterLocalNotificationsPlugin
|
||||
>(),
|
||||
).thenReturn(null);
|
||||
|
||||
when(
|
||||
() => androidImpl.requestNotificationsPermission(),
|
||||
).thenAnswer((_) async => false);
|
||||
when(
|
||||
() => androidImpl.requestExactAlarmsPermission(),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => androidImpl.requestFullScreenIntentPermission(),
|
||||
).thenAnswer((_) async => true);
|
||||
when(
|
||||
() => androidImpl.areNotificationsEnabled(),
|
||||
).thenAnswer((_) async => false);
|
||||
|
||||
final service = LocalNotificationService(plugin: plugin);
|
||||
service.bindInAppReminderHandler((payload) async {
|
||||
presentedEventIds.add(payload.eventId);
|
||||
});
|
||||
|
||||
final startAt = DateTime.now().add(const Duration(milliseconds: 80));
|
||||
final staleEvent = ScheduleItemModel(
|
||||
id: 'evt_stale',
|
||||
ownerId: 'u1',
|
||||
title: 'evt_stale',
|
||||
startAt: startAt,
|
||||
endAt: startAt.add(const Duration(minutes: 20)),
|
||||
metadata: ScheduleMetadata(reminderMinutes: 0),
|
||||
);
|
||||
|
||||
await service.rebuildUpcomingReminders([staleEvent]);
|
||||
await service.rebuildUpcomingReminders(const <ScheduleItemModel>[]);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 220));
|
||||
|
||||
expect(presentedEventIds, isNot(contains('evt_stale')));
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:social_app/features/calendar/reminders/ui/reminder_presentation_coordinator.dart';
|
||||
|
||||
void main() {
|
||||
test('blocks foreground presentation when app is not active', () {
|
||||
final coordinator = ReminderPresentationCoordinator();
|
||||
|
||||
final hiddenDecision = coordinator.shouldPresent(
|
||||
eventId: 'event_1',
|
||||
isAppActive: false,
|
||||
);
|
||||
final activeDecision = coordinator.shouldPresent(
|
||||
eventId: 'event_1',
|
||||
isAppActive: true,
|
||||
);
|
||||
|
||||
expect(hiddenDecision, isFalse);
|
||||
expect(activeDecision, isTrue);
|
||||
});
|
||||
|
||||
test('suppresses duplicate foreground presentation inside dedupe window', () {
|
||||
var fakeNow = DateTime(2026, 3, 19, 10, 0, 0);
|
||||
final coordinator = ReminderPresentationCoordinator(
|
||||
dedupeWindow: const Duration(seconds: 30),
|
||||
now: () => fakeNow,
|
||||
);
|
||||
|
||||
final first = coordinator.shouldPresent(
|
||||
eventId: 'event_42',
|
||||
isAppActive: true,
|
||||
);
|
||||
fakeNow = fakeNow.add(const Duration(seconds: 10));
|
||||
final second = coordinator.shouldPresent(
|
||||
eventId: 'event_42',
|
||||
isAppActive: true,
|
||||
);
|
||||
|
||||
expect(first, isTrue);
|
||||
expect(second, isFalse);
|
||||
});
|
||||
|
||||
test('allows same event again after dedupe window expires', () {
|
||||
var fakeNow = DateTime(2026, 3, 19, 10, 0, 0);
|
||||
final coordinator = ReminderPresentationCoordinator(
|
||||
dedupeWindow: const Duration(seconds: 30),
|
||||
now: () => fakeNow,
|
||||
);
|
||||
|
||||
expect(
|
||||
coordinator.shouldPresent(eventId: 'event_42', isAppActive: true),
|
||||
isTrue,
|
||||
);
|
||||
fakeNow = fakeNow.add(const Duration(seconds: 31));
|
||||
|
||||
expect(
|
||||
coordinator.shouldPresent(eventId: 'event_42', isAppActive: true),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user