feat: 实现日历提醒 in-app fallback 机制及通知服务重构

This commit is contained in:
zl-q
2026-03-20 01:30:34 +08:00
parent 7fd536e976
commit d574128815
55 changed files with 4565 additions and 647 deletions
@@ -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,
);
});
}
@@ -0,0 +1,36 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:social_app/features/home/ui/controllers/home_keyboard_inset_calculator.dart';
void main() {
test('subtracts bottom safe area from keyboard inset', () {
final inset = HomeKeyboardInsetCalculator.compute(
rawViewInsetBottom: 336,
bottomViewPadding: 34,
);
expect(inset, 302);
});
test('returns zero when keyboard is effectively hidden', () {
final inset = HomeKeyboardInsetCalculator.compute(
rawViewInsetBottom: 6,
bottomViewPadding: 34,
);
expect(inset, 0);
});
test('follows keyboard fallback immediately when inset decreases', () {
final openedInset = HomeKeyboardInsetCalculator.compute(
rawViewInsetBottom: 336,
bottomViewPadding: 34,
);
final collapsedInset = HomeKeyboardInsetCalculator.compute(
rawViewInsetBottom: 120,
bottomViewPadding: 34,
);
expect(openedInset, 302);
expect(collapsedInset, 86);
});
}
@@ -0,0 +1,70 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:social_app/features/settings/data/services/settings_user_cache.dart';
import 'package:social_app/features/users/data/models/user_response.dart';
void main() {
test('getOrLoad calls loader only once when cache exists', () async {
final cache = SettingsUserCache();
var loadCalls = 0;
Future<UserResponse> loader() async {
loadCalls += 1;
return const UserResponse(id: 'u1', username: 'first');
}
final first = await cache.getOrLoad(loader);
final second = await cache.getOrLoad(loader);
expect(first.username, 'first');
expect(second.username, 'first');
expect(loadCalls, 1);
});
test('invalidate forces next load', () async {
final cache = SettingsUserCache();
var loadCalls = 0;
Future<UserResponse> loader() async {
loadCalls += 1;
return UserResponse(id: 'u$loadCalls', username: 'user$loadCalls');
}
final first = await cache.getOrLoad(loader);
cache.invalidate();
final second = await cache.getOrLoad(loader);
expect(first.id, 'u1');
expect(second.id, 'u2');
expect(loadCalls, 2);
});
test(
'invalidate blocks stale inflight response from repopulating cache',
() async {
final cache = SettingsUserCache();
final completer = Completer<UserResponse>();
var loadCalls = 0;
Future<UserResponse> slowLoader() {
loadCalls += 1;
return completer.future;
}
final pending = cache.getOrLoad(slowLoader);
cache.invalidate();
completer.complete(const UserResponse(id: 'u1', username: 'stale'));
await pending;
final fresh = await cache.getOrLoad(() async {
loadCalls += 1;
return const UserResponse(id: 'u2', username: 'fresh');
});
expect(fresh.id, 'u2');
expect(cache.cachedUser?.id, 'u2');
expect(loadCalls, 2);
},
);
}
@@ -0,0 +1,130 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:social_app/core/api/i_api_client.dart';
import 'package:social_app/core/di/injection.dart';
import 'package:social_app/features/friends/data/friends_api.dart';
import 'package:social_app/features/settings/data/services/settings_user_cache.dart';
import 'package:social_app/features/settings/ui/screens/settings_screen.dart';
import 'package:social_app/features/users/data/models/user_response.dart';
import 'package:social_app/features/users/data/users_api.dart';
class _TestApiClient implements IApiClient {
@override
Future<Response<T>> delete<T>(String path, {data, Options? options}) async {
return Response<T>(requestOptions: RequestOptions(path: path));
}
@override
Future<Response<T>> get<T>(String path, {Options? options}) async {
return Response<T>(requestOptions: RequestOptions(path: path));
}
@override
Future<Stream<String>> getSseLines(
String path, {
Map<String, String>? headers,
}) async {
return const Stream<String>.empty();
}
@override
Future<Response<T>> patch<T>(String path, {data, Options? options}) async {
return Response<T>(requestOptions: RequestOptions(path: path));
}
@override
Future<Response<T>> post<T>(String path, {data, Options? options}) async {
return Response<T>(requestOptions: RequestOptions(path: path));
}
}
class _FakeUsersApi extends UsersApi {
_FakeUsersApi(super.client);
int getMeCalls = 0;
@override
Future<UserResponse> getMe() async {
getMeCalls += 1;
return const UserResponse(
id: 'u1',
username: 'Linksy',
phone: '13800000000',
);
}
}
class _FakeFriendsApi extends FriendsApi {
_FakeFriendsApi(super.client);
@override
Future<List<FriendResponse>> getFriends() async {
return const [];
}
}
void main() {
late _FakeUsersApi usersApi;
setUp(() {
final apiClient = _TestApiClient();
if (sl.isRegistered<UsersApi>()) {
sl.unregister<UsersApi>();
}
if (sl.isRegistered<FriendsApi>()) {
sl.unregister<FriendsApi>();
}
if (sl.isRegistered<SettingsUserCache>()) {
sl.unregister<SettingsUserCache>();
}
usersApi = _FakeUsersApi(apiClient);
sl.registerSingleton<UsersApi>(usersApi);
sl.registerSingleton<FriendsApi>(_FakeFriendsApi(apiClient));
sl.registerSingleton<SettingsUserCache>(SettingsUserCache());
});
tearDown(() async {
if (sl.isRegistered<UsersApi>()) {
await sl.unregister<UsersApi>();
}
if (sl.isRegistered<FriendsApi>()) {
await sl.unregister<FriendsApi>();
}
if (sl.isRegistered<SettingsUserCache>()) {
await sl.unregister<SettingsUserCache>();
}
});
testWidgets('settings screen removes account row and shows logout button', (
tester,
) async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await tester.pump();
expect(find.text('我的账户'), findsNothing);
expect(find.text('退出登录'), findsOneWidget);
});
testWidgets('settings profile hero shows edit icon entry', (tester) async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await tester.pump();
expect(find.byKey(settingsProfileEditButtonKey), findsOneWidget);
});
testWidgets('settings screen re-entry uses cached user', (tester) async {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await tester.pump();
await tester.pump();
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await tester.pump();
await tester.pump();
expect(usersApi.getMeCalls, 1);
});
}
@@ -0,0 +1,135 @@
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:social_app/features/todo/data/todo_api.dart';
import 'package:social_app/core/api/i_api_client.dart';
class MockApiClient extends Mock implements IApiClient {}
class FakeRequestOptions extends Fake implements RequestOptions {}
void main() {
late TodoApi todoApi;
late MockApiClient mockClient;
setUpAll(() {
registerFallbackValue(FakeRequestOptions());
});
setUp(() {
mockClient = MockApiClient();
todoApi = TodoApi(mockClient);
});
group('TodoApi.updateTodo - cross-quadrant drag', () {
test(
'calls PATCH with priority when moving to different quadrant',
() async {
const todoId = 'todo-123';
const targetPriority = 2;
when(
() => mockClient.patch(any(), data: any(named: 'data')),
).thenAnswer(
(_) async => Response(
requestOptions: RequestOptions(path: '/api/v1/todos/$todoId'),
data: {
'id': todoId,
'owner_id': 'user-1',
'title': 'Test Todo',
'priority': targetPriority,
'status': 'pending',
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T00:00:00Z',
},
),
);
final result = await todoApi.updateTodo(
todoId,
priority: targetPriority,
);
expect(result.priority, targetPriority);
verify(
() => mockClient.patch(
'/api/v1/todos/$todoId',
data: {'priority': targetPriority},
),
).called(1);
},
);
test('throws when API fails - triggers rollback', () async {
const todoId = 'todo-123';
when(
() => mockClient.patch(any(), data: any(named: 'data')),
).thenThrow(Exception('Network error'));
expect(() => todoApi.updateTodo(todoId, priority: 2), throwsException);
});
});
group('Quadrant priority mapping', () {
test('priority 1 = important urgent (Q1)', () async {
when(() => mockClient.patch(any(), data: any(named: 'data'))).thenAnswer(
(_) async => Response(
requestOptions: RequestOptions(path: '/api/v1/todos/todo-1'),
data: {
'id': 'todo-1',
'owner_id': 'user-1',
'title': 'Q1 Todo',
'priority': 1,
'status': 'pending',
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T00:00:00Z',
},
),
);
final result = await todoApi.updateTodo('todo-1', priority: 1);
expect(result.priority, 1);
});
test('priority 2 = important not urgent (Q3)', () async {
when(() => mockClient.patch(any(), data: any(named: 'data'))).thenAnswer(
(_) async => Response(
requestOptions: RequestOptions(path: '/api/v1/todos/todo-2'),
data: {
'id': 'todo-2',
'owner_id': 'user-1',
'title': 'Q3 Todo',
'priority': 2,
'status': 'pending',
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T00:00:00Z',
},
),
);
final result = await todoApi.updateTodo('todo-2', priority: 2);
expect(result.priority, 2);
});
test('priority 3 = urgent not important (Q2)', () async {
when(() => mockClient.patch(any(), data: any(named: 'data'))).thenAnswer(
(_) async => Response(
requestOptions: RequestOptions(path: '/api/v1/todos/todo-3'),
data: {
'id': 'todo-3',
'owner_id': 'user-1',
'title': 'Q2 Todo',
'priority': 3,
'status': 'pending',
'created_at': '2024-01-01T00:00:00Z',
'updated_at': '2024-01-01T00:00:00Z',
},
),
);
final result = await todoApi.updateTodo('todo-3', priority: 3);
expect(result.priority, 3);
});
});
}
@@ -0,0 +1,20 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('AndroidManifest declares ActionBroadcastReceiver', () {
final manifestFile = File('android/app/src/main/AndroidManifest.xml');
expect(manifestFile.existsSync(), isTrue);
final manifestContent = manifestFile.readAsStringSync();
expect(
manifestContent,
contains(
'com.dexterous.flutterlocalnotifications.ActionBroadcastReceiver',
),
);
});
}
@@ -0,0 +1,22 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('AppDelegate registers flutter local notifications callback', () {
final appDelegateFile = File('ios/Runner/AppDelegate.swift');
expect(appDelegateFile.existsSync(), isTrue);
final appDelegateContent = appDelegateFile.readAsStringSync();
expect(
appDelegateContent,
contains('FlutterLocalNotificationsPlugin.setPluginRegistrantCallback'),
);
expect(
appDelegateContent,
contains('GeneratedPluginRegistrant.register(with: registry)'),
);
});
}