LifeMate — Personal, Family & Learning Companion

feat/local-signing-preflight
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 490 lines 21.3 KB
Raw
1 import 'dart:io';
2 import 'dart:ui' as ui;
3
4 import 'package:flutter/material.dart';
5 import 'package:flutter/rendering.dart';
6 import 'package:flutter/services.dart';
7 import 'package:flutter_test/flutter_test.dart';
8 import 'package:lifemate/standalone/app.dart';
9 import 'package:lifemate/standalone/model.dart';
10 import 'package:lifemate/standalone/settings_ui.dart';
11 import 'package:lifemate/standalone/store.dart';
12 import 'package:sqflite_common_ffi/sqflite_ffi.dart';
13
14 void main() {
15 late Directory directory;
16 late String path;
17 late StandaloneStore store;
18
19 setUpAll(() async {
20 sqfliteFfiInit();
21 await (FontLoader('LifeGuidePersian')
22 ..addFont(rootBundle.load('assets/fonts/LifeGuidePersian.ttf')))
23 .load();
24 await (FontLoader('MaterialIcons')
25 ..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf')))
26 .load();
27 });
28 setUp(() async {
29 directory = await Directory.systemTemp.createTemp('lifeguide-ui-');
30 path = '${directory.path}/planner.sqlite';
31 // The same SQLite engine and schema as Android, without a background
32 // isolate so widget-test fake time does not stall a database message.
33 store = await StandaloneStore.open(
34 path: path, factory: databaseFactoryFfiNoIsolate);
35 });
36 tearDown(() async {
37 await store.close();
38 await directory.delete(recursive: true);
39 });
40
41 Future<void> idle(WidgetTester tester) async {
42 var idleFrames = 0;
43 for (var i = 0; i < 500; i++) {
44 await Future<void>.delayed(const Duration(milliseconds: 10));
45 await tester.pumpAndSettle();
46 final busy =
47 find.byType(CircularProgressIndicator).evaluate().isNotEmpty ||
48 find.text('در حال ذخیره…').evaluate().isNotEmpty;
49 idleFrames = busy ? 0 : idleFrames + 1;
50 if (idleFrames >= 3) return;
51 }
52 fail('SQLite-backed UI did not become idle.');
53 }
54
55 Future<void> open(WidgetTester tester,
56 {Future<void> Function(StandaloneStore)? before,
57 Future<void> Function(StandaloneStore)? after}) async {
58 await tester.pumpWidget(RepaintBoundary(
59 key: const Key('personal-test-surface'),
60 child: StandaloneApp(
61 openStore: () async => store,
62 onBeforePlansChange: before,
63 onPlansChanged: after)));
64 await idle(tester);
65 }
66
67 Future<void> tap(WidgetTester tester, Finder target) async {
68 FocusManager.instance.primaryFocus?.unfocus();
69 if (find.byType(SnackBar).evaluate().isNotEmpty) {
70 // Dismiss the prior transient result before the next independent action.
71 ScaffoldMessenger.of(tester.element(find.byType(SnackBar)))
72 .removeCurrentSnackBar();
73 }
74 await tester.pumpAndSettle();
75 if (target.evaluate().isEmpty) {
76 await tester.scrollUntilVisible(target, 200,
77 scrollable: find.byType(Scrollable).first, maxScrolls: 30);
78 }
79 await tester.ensureVisible(target);
80 await tester.pumpAndSettle();
81 await tester.tap(target);
82 await idle(tester);
83 }
84
85 Future<void> chooseRepeat(WidgetTester tester, String label) async {
86 await tap(tester, find.byKey(const Key('plan-recurrence')));
87 await tap(tester, find.text(label).last);
88 }
89
90 Future<void> chooseDateOption(WidgetTester tester, String label) async {
91 // The selected label also exists in the dialog behind the open menu.
92 final menu = find.byType(Scrollable).last;
93 final option = find.descendant(of: menu, matching: find.text(label));
94 await tester.scrollUntilVisible(option, -150, scrollable: menu);
95 expect(option, findsOneWidget);
96 await tap(tester, option);
97 }
98
99 Future<void> profile() => store.createProfile(
100 displayName: 'کاربر ساختگی',
101 category: StandaloneProfileCategory.girlMinor);
102
103 Future<void> seedDaily() async {
104 await profile();
105 await store.createPlan(StandalonePlanDraft(
106 title: 'برنامهٔ آزمایشی',
107 kind: StandalonePlanKind.task,
108 recurrence: StandaloneRecurrence.daily,
109 startDate: StandaloneDate.only(DateTime.now()),
110 startMinute: 540,
111 endMinute: 600));
112 }
113
114 testWidgets('onboarding and daily save commit before reminder reconciliation',
115 (tester) async {
116 await tester.runAsync(() async {
117 final events = <String>[];
118 await open(tester, before: (actual) async {
119 events.add('invalidate:${(await actual.listPlans()).length}');
120 }, after: (actual) async {
121 events.add('reconcile:${(await actual.listPlans()).length}');
122 });
123 expect(find.textContaining('بدون حساب و سرور'), findsOneWidget);
124 expect(await store.profile(), isNull);
125 await tester.enterText(find.byType(TextField), 'نام ساختگی');
126 await tap(tester,
127 find.byType(DropdownButtonFormField<StandaloneProfileCategory>));
128 await tap(tester, find.text('دختر').last);
129 await tap(tester, find.text('شروع برنامهٔ من'));
130 expect(find.text('سلام نام ساختگی'), findsOneWidget);
131 expect(await store.listPlans(), isEmpty);
132 await tap(tester, find.text('برنامهٔ تازه'));
133 await tester.enterText(
134 find.byKey(const Key('plan-title')), 'قدم روزانهٔ ساختگی');
135 await chooseRepeat(tester, 'هر روز');
136 await tap(tester, find.text('ذخیرهٔ برنامه'));
137 expect(events, ['invalidate:0', 'reconcile:1']);
138 expect((await store.listPlans()).single.recurrence,
139 StandaloneRecurrence.daily);
140 await tap(tester, find.byType(Checkbox));
141 final today = StandaloneDate.only(DateTime.now());
142 final occurrences = await store.occurrences(
143 from: today, through: StandaloneDate.addDays(today, 1));
144 expect(occurrences.first.completed, isTrue);
145 expect(occurrences.last.completed, isFalse);
146 await tester.pumpWidget(const SizedBox());
147 await store.close();
148 store = await StandaloneStore.open(
149 path: path, factory: databaseFactoryFfiNoIsolate);
150 await open(tester);
151 expect(find.text('سلام نام ساختگی'), findsOneWidget);
152 expect(find.textContaining('۱ از ۱'), findsOneWidget);
153 expect(tester.takeException(), isNull);
154 });
155 });
156
157 testWidgets('one occurrence edit and whole-plan archive preserve other dates',
158 (tester) async {
159 await tester.runAsync(() async {
160 await seedDaily();
161 await open(tester);
162 await tap(tester, find.text('شروع'));
163 await tap(tester, find.text('ویرایش همین نوبت'));
164 await tester.enterText(
165 find.byKey(const Key('occurrence-title')), 'عنوان مستقل');
166 await tap(tester, find.text('ثبت تغییر همین نوبت'));
167 final today = StandaloneDate.only(DateTime.now());
168 var items = await store.occurrences(
169 from: today, through: StandaloneDate.addDays(today, 1));
170 expect(items.first.title, 'عنوان مستقل');
171 expect(items.last.title, 'برنامهٔ آزمایشی');
172 await tap(tester, find.text('انجام شد'));
173 await tap(tester, find.text('بایگانی…'));
174 await tap(tester, find.text('کل برنامه و همهٔ نوبت‌های آینده'));
175 expect(await store.listPlans(), isEmpty);
176 items = await store.occurrences(
177 from: today,
178 through: StandaloneDate.addDays(today, 1),
179 includeArchived: true);
180 expect(items.first.completed, isTrue);
181 expect(items.last.completed, isFalse);
182 expect(
183 find.text('برای این روز هنوز برنامه‌ای ننوشته‌ای.'), findsOneWidget);
184 expect(tester.takeException(), isNull);
185 });
186 });
187
188 testWidgets(
189 'personal week shows Persian calendar without rewriting stored days',
190 (tester) async {
191 await tester.runAsync(() async {
192 await seedDaily();
193 final original = (await store.listPlans()).single;
194 await open(tester);
195 await tap(
196 tester,
197 find.descendant(
198 of: find.byType(NavigationBar), matching: find.text('هفته')));
199 expect(find.text('تاریخ‌ها شمسی‌اند.'), findsOneWidget);
200 expect(find.textContaining('میلادی'), findsNothing);
201 expect((await store.listPlans()).single.startDate, original.startDate);
202 expect(tester.takeException(), isNull);
203 });
204 });
205
206 testWidgets(
207 'Persian picker saves next-year date and keeps ISO SQLite after reopen',
208 (tester) async {
209 tester.view.physicalSize = const Size(390, 844);
210 tester.view.devicePixelRatio = 1;
211 addTearDown(() {
212 tester.view.resetPhysicalSize();
213 tester.view.resetDevicePixelRatio();
214 });
215 await tester.runAsync(() async {
216 await profile();
217 await open(tester);
218 await tap(tester, find.text('برنامهٔ تازه'));
219 await tester.enterText(
220 find.byKey(const Key('plan-title')), 'نوروز ساختگی');
221 await tap(tester, find.textContaining('تاریخ:'));
222 expect(find.text('انتخاب تاریخ شمسی'), findsOneWidget);
223 await tap(tester, find.byKey(const Key('personal-date-year')));
224 await tap(tester, find.text('۱۴۰۶').last);
225 await tap(tester, find.byKey(const Key('personal-date-month')));
226 await chooseDateOption(tester, 'فروردین');
227 await tap(tester, find.byKey(const Key('personal-date-day')));
228 await chooseDateOption(tester, '۱');
229 // Reopening day1 exercises duplicate labels regardless of today's date.
230 await tap(tester, find.byKey(const Key('personal-date-day')));
231 await chooseDateOption(tester, '۱');
232 final evidence = Platform.environment['LIFEGUIDE_UI_EVIDENCE_DIR'];
233 if (evidence != null) {
234 final boundary = tester.renderObject<RenderRepaintBoundary>(
235 find.byKey(const Key('personal-test-surface')));
236 final image = await boundary.toImage(pixelRatio: 2);
237 final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
238 await Directory(evidence).create(recursive: true);
239 await File('$evidence/personal-jalali-picker.png')
240 .writeAsBytes(bytes!.buffer.asUint8List());
241 image.dispose();
242 }
243 await tap(tester, find.text('انتخاب تاریخ'));
244 expect(find.text('تاریخ: ۱ فروردین ۱۴۰۶ شمسی'), findsOneWidget);
245 await tap(tester, find.text('ذخیرهٔ برنامه'));
246 final original = (await store.listPlans()).single;
247 await tester.pumpWidget(const SizedBox());
248 await store.close();
249 final independent = await databaseFactoryFfiNoIsolate.openDatabase(path,
250 options: OpenDatabaseOptions(readOnly: true, singleInstance: false));
251 expect((await independent.query('local_plans')).single['start_date'],
252 '2027-03-21');
253 await independent.close();
254 store = await StandaloneStore.open(
255 path: path, factory: databaseFactoryFfiNoIsolate);
256 await open(tester);
257 expect((await store.listPlans()).single.id, original.id);
258 expect((await store.listPlans()).single.startDate, DateTime(2027, 3, 21));
259 expect(tester.takeException(), isNull);
260 });
261 });
262
263 testWidgets('Persian picker confirms and cancels at320px and200percent text',
264 (tester) async {
265 tester.view.physicalSize = const Size(320, 900);
266 tester.view.devicePixelRatio = 1;
267 tester.platformDispatcher.textScaleFactorTestValue = 2;
268 addTearDown(() {
269 tester.view.resetPhysicalSize();
270 tester.view.resetDevicePixelRatio();
271 tester.platformDispatcher.clearTextScaleFactorTestValue();
272 });
273 await tester.runAsync(() async {
274 await profile();
275 await open(tester);
276 await tap(tester, find.text('برنامهٔ تازه'));
277 await tap(tester, find.textContaining('تاریخ:'));
278 expect(find.text('انتخاب تاریخ شمسی'), findsOneWidget);
279 await tap(tester, find.byKey(const Key('personal-date-year')));
280 await tap(tester, find.text('۱۴۰۶').last);
281 await tap(tester, find.byKey(const Key('personal-date-month')));
282 await chooseDateOption(tester, 'فروردین');
283 await tap(tester, find.byKey(const Key('personal-date-day')));
284 await chooseDateOption(tester, '۱');
285 await tap(tester, find.text('انتخاب تاریخ'));
286 expect(find.text('تاریخ: ۱ فروردین ۱۴۰۶ شمسی'), findsOneWidget);
287 final originalLabel =
288 tester.widget<Text>(find.textContaining('تاریخ:')).data;
289 await tap(tester, find.textContaining('تاریخ:'));
290 await tap(tester, find.byKey(const Key('personal-date-year')));
291 await tap(tester, find.text('۱۴۰۵').last);
292 await tap(tester, find.text('انصراف').last);
293 expect(find.text(originalLabel!), findsOneWidget);
294 expect(await store.listPlans(), isEmpty);
295 expect(tester.takeException(), isNull);
296 });
297 });
298
299 testWidgets('weekly editor persists different hours for selected weekdays',
300 (tester) async {
301 await tester.runAsync(() async {
302 await profile();
303 await open(tester);
304 await tap(tester, find.text('برنامهٔ تازه'));
305 await tester.enterText(
306 find.byKey(const Key('plan-title')), 'هفتهٔ ساختگی');
307 await chooseRepeat(tester, 'روزهای انتخابی هفته');
308 await tap(tester, find.byKey(const Key('plan-weekday-6')));
309 await tap(tester, find.byKey(const Key('plan-weekday-7')));
310 final saturdayHours = find.byKey(const Key('weekly-hours-6'));
311 await tap(
312 tester,
313 find
314 .descendant(
315 of: saturdayHours, matching: find.byType(OutlinedButton))
316 .last);
317 final fields = find.descendant(
318 of: find.byType(TimePickerDialog), matching: find.byType(TextField));
319 await tester.enterText(fields.at(0), '11');
320 await tester.enterText(fields.at(1), '30');
321 await tap(tester, find.widgetWithText(TextButton, 'تأیید'));
322 await tap(tester, find.text('ذخیرهٔ برنامه'));
323 final plan = (await store.listPlans()).single;
324 expect(plan.recurrence, StandaloneRecurrence.weekly);
325 expect(plan.weeklySlots.map((slot) => slot.weekday), [6, 7]);
326 expect(plan.weeklySlots.map((slot) => slot.endMinute), [690, 600]);
327 expect(tester.takeException(), isNull);
328 });
329 });
330
331 testWidgets(
332 'SQLite failure retains editor; committed reminder failure does not',
333 (tester) async {
334 await tester.runAsync(() async {
335 await profile();
336 final db = await databaseFactoryFfiNoIsolate.openDatabase(path);
337 await db.execute('''CREATE TRIGGER synthetic_write_failure
338 BEFORE INSERT ON local_plans BEGIN
339 SELECT RAISE(ABORT, 'synthetic disk-write failure'); END''');
340 await open(tester,
341 after: (_) async => throw StateError('synthetic alarm'));
342 await tap(tester, find.text('برنامهٔ تازه'));
343 await tester.enterText(find.byKey(const Key('plan-title')), 'حفظ فرم');
344 await chooseRepeat(tester, 'یک روز در میان');
345 await tap(tester, find.text('ذخیرهٔ برنامه'));
346 expect(await store.listPlans(), isEmpty);
347 await tester.scrollUntilVisible(find.byKey(const Key('plan-title')), -200,
348 scrollable: find.byType(Scrollable).first);
349 expect(
350 tester
351 .widget<TextField>(find.byKey(const Key('plan-title')))
352 .controller!
353 .text,
354 'حفظ فرم');
355 await tester.scrollUntilVisible(
356 find.text('برنامه ذخیره نشد. می‌توانی دوباره تلاش کنی.'), 200,
357 scrollable: find.byType(Scrollable).first);
358 expect(find.text('برنامه ذخیره نشد. می‌توانی دوباره تلاش کنی.'),
359 findsOneWidget);
360 await db.execute('DROP TRIGGER synthetic_write_failure');
361 await tap(tester, find.text('ذخیرهٔ برنامه'));
362 expect((await store.listPlans()).single.recurrence,
363 StandaloneRecurrence.everyTwoDays);
364 expect(find.byKey(const Key('plan-title')), findsNothing);
365 expect(
366 find.text(
367 'برنامه ذخیره شد؛ آماده‌سازی یادآوری را در تنظیمات بررسی کن.'),
368 findsOneWidget);
369 expect(tester.takeException(), isNull);
370 });
371 });
372
373 testWidgets('onboarding reload failure never recreates a committed profile',
374 (tester) async {
375 await tester.runAsync(() async {
376 var reloads = 0;
377 await tester.pumpWidget(MaterialApp(
378 home: StandaloneOnboarding(
379 store: store,
380 onSaved: () async {
381 reloads++;
382 if (reloads == 1) throw StateError('synthetic read failure');
383 })));
384 await tester.pumpAndSettle();
385 await tester.enterText(find.byType(TextField), 'نام محفوظ');
386 await tap(tester,
387 find.byType(DropdownButtonFormField<StandaloneProfileCategory>));
388 await tap(tester, find.text('بزرگسال').last);
389 await tap(tester, find.text('شروع برنامهٔ من'));
390 final id = (await store.profile())!.id;
391 expect(find.textContaining('نام روی این گوشی ذخیره شد'), findsOneWidget);
392 await tap(tester, find.text('باز کردن برنامهٔ من'));
393 expect((await store.profile())!.id, id);
394 expect(reloads, 2);
395 expect(tester.takeException(), isNull);
396 });
397 });
398
399 testWidgets(
400 '320 wide at 200 percent keeps onboarding, pages and settings usable',
401 (tester) async {
402 await tester.runAsync(() async {
403 tester.view.physicalSize = const Size(320, 740);
404 tester.view.devicePixelRatio = 1;
405 tester.platformDispatcher.textScaleFactorTestValue = 2;
406 addTearDown(tester.view.resetPhysicalSize);
407 addTearDown(tester.view.resetDevicePixelRatio);
408 addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
409 await open(tester);
410 await tester.scrollUntilVisible(find.byType(TextField), 180,
411 scrollable: find.byType(Scrollable).first);
412 await tester.enterText(find.byType(TextField), 'نام ساختگی');
413 await tap(tester,
414 find.byType(DropdownButtonFormField<StandaloneProfileCategory>));
415 await tap(tester, find.text('پسر').last);
416 await tap(tester, find.text('شروع برنامهٔ من'));
417 expect(tester.takeException(), isNull);
418 await tap(
419 tester,
420 find.descendant(
421 of: find.byType(NavigationBar), matching: find.text('هفته')));
422 expect(tester.takeException(), isNull);
423 await tap(
424 tester,
425 find.descendant(
426 of: find.byType(NavigationBar), matching: find.text('تنظیمات')));
427 await tap(tester, find.text('سبز نعنایی'));
428 await tap(tester, find.text('ذخیرهٔ تغییرها'));
429 expect((await store.profile())!.themeKey, 'mint');
430 await tap(tester, find.text('مرجانی گرم'));
431 await tap(tester, find.text('ذخیرهٔ تغییرها'));
432 expect((await store.profile())!.themeKey, 'coral');
433 expect(tester.takeException(), isNull);
434 await tap(
435 tester,
436 find.descendant(
437 of: find.byType(NavigationBar), matching: find.text('امروز')));
438 await tap(tester, find.text('برنامهٔ تازه'));
439 await chooseRepeat(tester, 'روزهای انتخابی هفته');
440 await tap(tester, find.byKey(const Key('plan-weekday-6')));
441 await tap(tester, find.text('ذخیرهٔ برنامه'));
442 expect(find.text('یک عنوان برای برنامه بنویس.'), findsOneWidget);
443 expect(tester.takeException(), isNull);
444 });
445 });
446 testWidgets('resume reads committed plans before reminder reconciliation',
447 (tester) async {
448 await tester.runAsync(() async {
449 await seedDaily();
450 var resumed = 0;
451 await tester.pumpWidget(StandaloneApp(
452 openStore: () async => store,
453 onResumed: (actual) async {
454 expect(await actual.listPlans(), hasLength(1));
455 resumed++;
456 }));
457 await idle(tester);
458 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
459 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
460 await idle(tester);
461 expect(resumed, 1);
462 expect(tester.takeException(), isNull);
463 });
464 });
465
466 testWidgets('failed profile write restores reminders from unchanged SQLite',
467 (tester) async {
468 await tester.runAsync(() async {
469 await profile();
470 final db = await databaseFactoryFfiNoIsolate.openDatabase(path);
471 await db.execute(
472 "CREATE TRIGGER reject_profile BEFORE UPDATE ON local_profiles BEGIN SELECT RAISE(ABORT, 'synthetic write failure'); END");
473 final events = <String>[];
474 await open(tester,
475 before: (_) async => events.add('suspend'),
476 after: (actual) async =>
477 events.add('restore:${(await actual.profile())!.displayName}'));
478 await tap(
479 tester,
480 find.descendant(
481 of: find.byType(NavigationBar), matching: find.text('تنظیمات')));
482 await tester.enterText(find.byType(TextField).first, 'نام ذخیره نشده');
483 await tap(tester, find.text('ذخیرهٔ تغییرها'));
484 expect(events, ['suspend', 'restore:کاربر ساختگی']);
485 expect((await store.profile())!.displayName, 'کاربر ساختگی');
486 expect(find.textContaining('تغییرها ذخیره نشد'), findsOneWidget);
487 expect(tester.takeException(), isNull);
488 });
489 });
490 }