LifeMate — Personal, Family & Learning Companion

fix/personal-upgrade-delivery-guard
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
dart 284 lines 10.8 KB
Raw
1 import 'dart:async';
2 import 'package:flutter/foundation.dart';
3 import 'package:flutter/services.dart';
4 import 'package:flutter_test/flutter_test.dart';
5 import 'package:lifemate/standalone/reminders.dart';
6 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
7 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
8 import 'package:shared_preferences_platform_interface/types.dart';
9
10 final class FailingOffPreferences extends InMemorySharedPreferencesAsync {
11 FailingOffPreferences() : super.empty();
12 bool failOff = false;
13 @override
14 Future<bool> setBool(
15 String key, bool value, SharedPreferencesOptions options) {
16 if (!value && failOff) throw StateError('Preference disk unavailable');
17 return super.setBool(key, value, options);
18 }
19 }
20
21 void main() {
22 TestWidgetsFlutterBinding.ensureInitialized();
23 const channel = MethodChannel('lifeguide/device_planner_reminders');
24 const profile = '11111111-1111-4111-8111-111111111111';
25 const item = '22222222-2222-4222-8222-222222222222';
26 final now = DateTime.utc(2026, 10, 19, 8);
27 final calls = <MethodCall>[];
28 late StandaloneReminderPort port;
29 late FailingOffPreferences preferences;
30 bool nativeEnabled = false, active = false, supported = true;
31 int scheduled = 0;
32 List<dynamic> payload = [];
33 Future<void> Function(MethodCall)? intercept;
34 LocalPersonalReminder row(
35 {String id = item,
36 String profileId = profile,
37 DateTime? at,
38 bool completed = false,
39 bool archived = false}) =>
40 LocalPersonalReminder(
41 id: id,
42 planItemId: id,
43 profileId: profileId,
44 scheduledAt: at ?? now.add(const Duration(hours: 1)),
45 completed: completed,
46 archived: archived);
47 String idAt(int index) =>
48 '${index.toRadixString(16).padLeft(8, '0')}-2222-4222-8222-222222222222';
49
50 setUp(() {
51 debugDefaultTargetPlatformOverride = TargetPlatform.android;
52 preferences = FailingOffPreferences();
53 SharedPreferencesAsyncPlatform.instance = preferences;
54 port = StandaloneReminderPort(now: () => now);
55 nativeEnabled = false;
56 active = false;
57 supported = true;
58 scheduled = 0;
59 payload = [];
60 calls.clear();
61 intercept = null;
62 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
63 .setMockMethodCallHandler(channel, (call) async {
64 calls.add(call);
65 if (intercept != null) await intercept!(call);
66 if (!supported) {
67 return {
68 'supported': false,
69 'enabled': false,
70 'permissionGranted': false,
71 'active': false,
72 'scheduledCount': 0,
73 'timing': 'approximate'
74 };
75 }
76 if (call.method == 'setEnabled') {
77 nativeEnabled = (call.arguments as Map)['enabled'] == true;
78 if (!nativeEnabled) {
79 active = false;
80 scheduled = 0;
81 payload = [];
82 }
83 }
84 if (call.method == 'activate') active = true;
85 if (call.method == 'replace') {
86 payload = (call.arguments as Map)['reminders'] as List;
87 scheduled = payload.length;
88 }
89 if (call.method == 'deactivate') {
90 active = false;
91 scheduled = 0;
92 payload = [];
93 }
94 if (['status', 'requestPermission', 'requestExactAlarmAccess']
95 .contains(call.method)) {
96 return {
97 'supported': true,
98 'enabled': nativeEnabled,
99 'permissionGranted': true,
100 'active': active,
101 'scheduledCount': scheduled,
102 'timing': 'approximate',
103 'activeScope': active ? 'device-planner:v1:$profile' : null,
104 'validUntilEpochMs': active
105 ? now.add(const Duration(days: 31)).millisecondsSinceEpoch
106 : null,
107 'exactAlarmSupported': true,
108 'canScheduleExactAlarms': false
109 };
110 }
111 return true;
112 });
113 });
114 tearDown(() {
115 debugDefaultTargetPlatformOverride = null;
116 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
117 .setMockMethodCallHandler(channel, null);
118 });
119
120 test('opening and reconciliation remain OFF without permission prompts',
121 () async {
122 expect((await port.status(profileId: profile)).enabled, isFalse);
123 final result = await port
124 .reconcile([row()], companionName: 'همراه من', profileId: profile);
125 expect(result.enabled, isFalse);
126 expect(result.active, isFalse);
127 expect(calls.map((call) => call.method), isNot(contains('activate')));
128 expect(
129 calls.map((call) => call.method), isNot(contains('requestPermission')));
130 });
131 test(
132 'explicit enable selects next 28 days and soonest 128 with opaque payload',
133 () async {
134 final rows = List.generate(
135 130, (i) => row(id: idAt(i), at: now.add(Duration(minutes: 130 - i))));
136 rows.addAll([
137 row(id: idAt(131), at: now.subtract(const Duration(seconds: 1))),
138 row(id: idAt(132), at: now.add(const Duration(days: 29))),
139 row(id: idAt(133), completed: true),
140 row(id: idAt(134), archived: true)
141 ]);
142 final result =
143 await port.enable(rows, companionName: 'همراه من', profileId: profile);
144 expect(result.enabled, isTrue);
145 expect(result.active, isTrue);
146 expect(result.eligibleCount, 130);
147 expect(result.selectedCount, 128);
148 expect(result.scheduledCount, 128);
149 expect(calls.where((call) => call.method == 'requestPermission'),
150 hasLength(1));
151 final activation = calls.singleWhere((call) => call.method == 'activate');
152 expect((activation.arguments as Map)['validUntilEpochMs'],
153 now.add(const Duration(days: 31)).millisecondsSinceEpoch);
154 expect((payload.first as Map)['id'], idAt(129));
155 expect((payload.last as Map)['id'], idAt(2));
156 expect(
157 (payload.first as Map).keys,
158 unorderedEquals(
159 ['id', 'planItemId', 'scheduledAtEpochMs', 'companionName']));
160 });
161 test('completed and archived stay cancelled after restored choice', () async {
162 await port.enable([row()], companionName: 'همراه من', profileId: profile);
163 await port.suspendUntilReconcile(profileId: profile);
164 expect(nativeEnabled, isTrue);
165 expect(active, isFalse);
166 calls.clear();
167 final reopened = StandaloneReminderPort(now: () => now);
168 final result = await reopened.reconcile(
169 [row(completed: true), row(id: idAt(3), archived: true)],
170 companionName: 'همراه من', profileId: profile);
171 expect(result.enabled, isTrue);
172 expect(result.scheduledCount, 0);
173 expect(payload, isEmpty);
174 expect(
175 calls.map((call) => call.method), isNot(contains('requestPermission')));
176 });
177 test('suspension invalidates in-flight scheduling and fresh DB read restores',
178 () async {
179 await port.enable([row()], companionName: 'همراه من', profileId: profile);
180 final entered = Completer<void>(), release = Completer<void>();
181 intercept = (call) async {
182 if (call.method == 'activate' && !entered.isCompleted) {
183 entered.complete();
184 await release.future;
185 }
186 };
187 calls.clear();
188 final updating =
189 port.reconcile([row()], companionName: 'همراه من', profileId: profile);
190 await entered.future;
191 final suspending = port.suspendUntilReconcile(profileId: profile);
192 release.complete();
193 await Future.wait([updating, suspending]);
194 expect(active, isFalse);
195 expect(nativeEnabled, isTrue);
196 expect(calls.map((call) => call.method), isNot(contains('replace')));
197 intercept = null;
198 await StandaloneReminderPort(now: () => now)
199 .reconcile([row()], companionName: 'همراه من', profileId: profile);
200 expect(active, isTrue);
201 expect(scheduled, 1);
202 });
203 test('OFF invalidates an activation already in flight', () async {
204 final entered = Completer<void>(), release = Completer<void>();
205 intercept = (call) async {
206 if (call.method == 'activate') {
207 entered.complete();
208 await release.future;
209 }
210 };
211 final enabling =
212 port.enable([row()], companionName: 'همراه من', profileId: profile);
213 await entered.future;
214 final disabling = port.disable(profileId: profile);
215 release.complete();
216 await Future.wait([enabling, disabling]);
217 expect(nativeEnabled, isFalse);
218 expect(active, isFalse);
219 expect(calls.map((call) => call.method), isNot(contains('replace')));
220 await StandaloneReminderPort(now: () => now)
221 .reconcile([row()], companionName: 'همراه من', profileId: profile);
222 expect(active, isFalse);
223 });
224 test('failed Dart OFF write cancels native; stale ON cannot resurrect',
225 () async {
226 await port.enable([row()], companionName: 'همراه من', profileId: profile);
227 preferences.failOff = true;
228 await expectLater(port.disable(profileId: profile), throwsStateError);
229 expect(nativeEnabled, isFalse);
230 expect(active, isFalse);
231 final result = await StandaloneReminderPort(now: () => now)
232 .reconcile([row()], companionName: 'همراه من', profileId: profile);
233 expect(result.enabled, isFalse);
234 expect(result.active, isFalse);
235 expect(scheduled, 0);
236 });
237 test('invalid profiles, IDs, timestamps and names never schedule', () async {
238 for (final invalid in [
239 row(profileId: idAt(5)),
240 row(id: 'not-a-uuid'),
241 row(at: DateTime(2026, 10, 19, 9))
242 ]) {
243 expect(
244 () => port
245 .enable([invalid], companionName: 'همراه من', profileId: profile),
246 throwsArgumentError);
247 }
248 expect(
249 () => port
250 .enable([row()], companionName: 'bad\nname', profileId: profile),
251 throwsArgumentError);
252 expect(
253 () => port.enable([row()],
254 companionName: List.filled(41, '👩‍🔬').join(), profileId: profile),
255 throwsArgumentError);
256 expect(calls, isEmpty);
257 });
258 test('unsupported native build and missing plugin are honest', () async {
259 supported = false;
260 final unavailable = await port
261 .enable([row()], companionName: 'همراه من', profileId: profile);
262 expect(unavailable.supported, isFalse);
263 expect(unavailable.enabled, isFalse);
264 await port.disable(profileId: profile);
265 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
266 .setMockMethodCallHandler(channel, null);
267 expect(
268 (await StandaloneReminderPort().status(profileId: profile)).supported,
269 isFalse);
270 });
271 test('non-Android never reaches native or claims background support',
272 () async {
273 debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
274 expect(
275 (await port
276 .enable([row()], companionName: 'همراه من', profileId: profile))
277 .supported,
278 isFalse);
279 await port
280 .reconcile([row()], companionName: 'همراه من', profileId: profile);
281 await port.disable(profileId: profile);
282 expect(calls, isEmpty);
283 });
284 }