LifeMate — Personal, Family & Learning Companion

feat/weekly-planner-android
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 382 lines 16.6 KB
Raw
1 import 'dart:convert';
2 import 'package:flutter/material.dart';
3 import 'package:flutter/services.dart';
4 import 'package:flutter_test/flutter_test.dart';
5 import 'package:http/http.dart' as http;
6 import 'package:http/testing.dart';
7 import 'package:lifemate/api.dart';
8 import 'package:lifemate/phase4_ui.dart';
9 import 'package:lifemate/learning_goals_ui.dart';
10 import 'learning_goal_sync_test.dart' as support;
11 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
12 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
13
14 void main() {
15 TestWidgetsFlutterBinding.ensureInitialized();
16 setUp(() {
17 SharedPreferencesAsyncPlatform.instance =
18 InMemorySharedPreferencesAsync.withData({});
19 String? token;
20 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
21 .setMockMethodCallHandler(
22 const MethodChannel('lifeguide/local_write_guard'), (call) async {
23 if (call.method == 'getBlocked') return token != null;
24 if (call.method == 'beginWrite') return token = 'goal-widget-test';
25 if (call.method == 'completeWrite' && call.arguments == token) {
26 token = null;
27 return true;
28 }
29 throw PlatformException(code: 'local_storage_restart_required');
30 });
31 });
32 testWidgets(
33 'HTTP hub opens private goal CRUD screen with truthful server freshness',
34 (tester) async {
35 final api = HttpIdentityApi(
36 baseUrl: 'https://goals.example.test/api',
37 client: MockClient((request) async => http.Response(
38 jsonEncode({'items': [], 'fetchedAt': '2026-10-11T10:00:00Z'}), 200,
39 headers: {'content-type': 'application/json; charset=utf-8'})))
40 ..accessToken = 'synthetic'
41 ..currentUserId = '10000000-0000-4000-8000-000000000001';
42 await tester.pumpWidget(MaterialApp(
43 home: Directionality(
44 textDirection: TextDirection.rtl,
45 child: Scaffold(body: Phase4Hub(api: api)))));
46 await tester.pumpAndSettle();
47 await tester.scrollUntilVisible(find.text('مدیریت هدف‌های یادگیری'), 200,
48 scrollable: find.byType(Scrollable).first);
49 await tester.tap(find.text('مدیریت هدف‌های یادگیری'));
50 await tester.pumpAndSettle();
51 expect(find.text('هدف‌های یادگیری'), findsOneWidget);
52 expect(find.text('هدف جدید'), findsOneWidget);
53 expect(find.textContaining('خصوصی'), findsOneWidget);
54 expect(find.textContaining('آخرین دریافت سرور:'), findsOneWidget);
55 expect(tester.takeException(), isNull);
56 await tester.pumpWidget(const SizedBox());
57 api.close();
58 });
59 Future<void> showPage(WidgetTester tester, HttpIdentityApi api) async {
60 await tester.pumpWidget(MaterialApp(
61 home: Directionality(
62 textDirection: TextDirection.rtl,
63 child: LearningGoalsPage(api: api))));
64 await tester.pumpAndSettle();
65 }
66
67 testWidgets(
68 'goal creation, edit, completion and confirmed archive use versioned API operations',
69 (tester) async {
70 final f = support.GoalFixture();
71 await showPage(tester, f.api);
72 await tester.tap(find.text('هدف جدید'));
73 await tester.pumpAndSettle();
74 await tester.enterText(find.byType(TextField).at(0), 'هدف ریاضی');
75 await tester.enterText(find.byType(TextField).at(1), 'جمع با درک مفهوم');
76 await tester.tap(find.text('ذخیره'));
77 await tester.pumpAndSettle();
78 expect(find.text('هدف ریاضی'), findsOneWidget);
79 expect(find.text('تغییر ارسال‌نشده: 0'), findsOneWidget);
80 await tester.tap(find.text('ویرایش'));
81 await tester.pumpAndSettle();
82 await tester.enterText(find.byType(TextField).at(0), 'تمرین جمع');
83 await tester.tap(find.text('ذخیره'));
84 await tester.pumpAndSettle();
85 expect(find.text('هدف ریاضی'), findsNothing);
86 expect(find.text('تمرین جمع'), findsOneWidget);
87 await tester.tap(find.widgetWithText(TextButton, 'تکمیل طبق گزارش من'));
88 await tester.pumpAndSettle();
89 expect(find.text('فعال‌کردن دوباره'), findsOneWidget);
90 await tester.tap(find.widgetWithText(TextButton, 'بایگانی'));
91 await tester.pumpAndSettle();
92 expect(find.text('بایگانی هدف؟'), findsOneWidget);
93 await tester.tap(find.widgetWithText(TextButton, 'انصراف'));
94 await tester.pumpAndSettle();
95 expect(f.goals.values.single['status'], 'completed');
96 await tester.tap(find.widgetWithText(TextButton, 'بایگانی'));
97 await tester.pumpAndSettle();
98 await tester.tap(find.widgetWithText(FilledButton, 'بایگانی'));
99 await tester.pumpAndSettle();
100 expect(find.text('تمرین جمع'), findsNothing);
101 expect(f.goals.values.single['status'], 'archived');
102 expect(f.goals.values.single['version'], 4);
103 expect(f.receipts, hasLength(4));
104 await tester.pumpWidget(const SizedBox());
105 f.api.close();
106 });
107
108 testWidgets(
109 'offline goal intent remains pending after page reopen and becomes live only after acknowledgement',
110 (tester) async {
111 final f = support.GoalFixture()..offline = true;
112 await showPage(tester, f.api);
113 await tester.tap(find.text('هدف جدید'));
114 await tester.pumpAndSettle();
115 await tester.enterText(find.byType(TextField).first, 'هدف بدون اینترنت');
116 await tester.tap(find.text('ذخیره'));
117 await tester.pumpAndSettle();
118 expect(find.text('تغییر در انتظار تأیید سرور'), findsOneWidget);
119 expect(find.text('تغییر ارسال‌نشده: 1'), findsOneWidget);
120 expect(find.textContaining('آخرین ثبت سرور:'), findsNothing);
121 await tester.pumpWidget(const SizedBox());
122 await showPage(tester, f.api);
123 expect(find.text('هدف بدون اینترنت'), findsOneWidget);
124 expect(find.text('تغییر ارسال‌نشده: 1'), findsOneWidget);
125 f.offline = false;
126 await tester.tap(find.text('همگام‌سازی و تازه‌سازی'));
127 await tester.pumpAndSettle();
128 expect(find.text('تغییر ارسال‌نشده: 0'), findsOneWidget);
129 expect(find.textContaining('آخرین ثبت سرور:'), findsOneWidget);
130 expect(f.goals, hasLength(1));
131 await tester.pumpWidget(const SizedBox());
132 f.api.close();
133 });
134
135 testWidgets('denied refresh removes private goal text and actions',
136 (tester) async {
137 final f = support.GoalFixture();
138 f.goals[support.goalId] = support.goal();
139 await showPage(tester, f.api);
140 expect(find.text('هدف خصوصی آزمایشی'), findsOneWidget);
141 f.errorCode = 403;
142 await tester.tap(find.text('همگام‌سازی و تازه‌سازی'));
143 await tester.pumpAndSettle();
144 expect(find.text('هدف خصوصی آزمایشی'), findsNothing);
145 expect(find.text('ویرایش'), findsNothing);
146 expect(find.textContaining('دسترسی'), findsOneWidget);
147 await tester.pumpWidget(const SizedBox());
148 f.api.close();
149 });
150
151 testWidgets(
152 'failed response labels retained goals as stale instead of a live snapshot',
153 (tester) async {
154 final f = support.GoalFixture();
155 f.goals[support.goalId] = support.goal();
156 await showPage(tester, f.api);
157 f.errorCode = 502;
158 await tester.tap(find.text('همگام‌سازی و تازه‌سازی'));
159 await tester.pumpAndSettle();
160 expect(find.text('هدف خصوصی آزمایشی'), findsOneWidget);
161 expect(find.text('تازه‌سازی ناموفق؛ این داده ممکن است قدیمی باشد.'),
162 findsOneWidget);
163 await tester.pumpWidget(const SizedBox());
164 f.api.close();
165 });
166
167 testWidgets(
168 'backgrounding clears private goal view and resume revalidates before display',
169 (tester) async {
170 final f = support.GoalFixture();
171 f.goals[support.goalId] = support.goal();
172 await showPage(tester, f.api);
173 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
174 await tester.pump();
175 expect(find.text('هدف خصوصی آزمایشی'), findsNothing);
176 f.errorCode = 403;
177 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
178 await tester.pumpAndSettle();
179 expect(find.text('هدف خصوصی آزمایشی'), findsNothing);
180 expect(find.textContaining('دسترسی'), findsOneWidget);
181 await tester.pumpWidget(const SizedBox());
182 f.api.close();
183 });
184
185 testWidgets(
186 'denied edit closes private text dialog and never restores cached goals',
187 (tester) async {
188 final f = support.GoalFixture();
189 f.goals[support.goalId] = support.goal();
190 await showPage(tester, f.api);
191 await tester.tap(find.text('ویرایش'));
192 await tester.pumpAndSettle();
193 f.errorCode = 403;
194 await tester.tap(find.text('ذخیره'));
195 await tester.pumpAndSettle();
196 expect(find.byType(TextField), findsNothing);
197 expect(find.text('هدف خصوصی آزمایشی'), findsNothing);
198 expect(find.textContaining('دسترسی'), findsOneWidget);
199 await tester.pumpWidget(const SizedBox());
200 f.api.close();
201 });
202 testWidgets(
203 'goal-linked private reflection history supports create, edit and safe archive',
204 (tester) async {
205 final f = _HistoryFixture();
206 await tester.pumpWidget(MaterialApp(
207 home: LearningGoalHistoryPage(api: f.api, goalId: support.goalId)));
208 await tester.pumpAndSettle();
209 expect(find.text('ثبت بازتاب'), findsOneWidget);
210 await tester.tap(find.text('ثبت بازتاب'));
211 await tester.pumpAndSettle();
212 await tester.enterText(find.byType(TextField), 'جمع را بهتر فهمیدم');
213 await tester.tap(find.text('ذخیره'));
214 await tester.pumpAndSettle();
215 expect(find.text('جمع را بهتر فهمیدم'), findsOneWidget);
216 expect(find.textContaining('اثبات یادگیری'), findsWidgets);
217 await tester.tap(find.widgetWithText(TextButton, 'ویرایش بازتاب'));
218 await tester.pumpAndSettle();
219 await tester.enterText(find.byType(TextField), 'نیاز به تمرین بیشتر دارم');
220 await tester.tap(find.text('ذخیره'));
221 await tester.pumpAndSettle();
222 expect(find.text('جمع را بهتر فهمیدم'), findsNothing);
223 expect(find.text('نیاز به تمرین بیشتر دارم'), findsOneWidget);
224 await tester.tap(find.widgetWithText(TextButton, 'بایگانی بازتاب'));
225 await tester.pumpAndSettle();
226 await tester.tap(find.text('تأیید بایگانی'));
227 await tester.pumpAndSettle();
228 expect(find.text('نیاز به تمرین بیشتر دارم'), findsNothing);
229 expect(f.posts, 1);
230 expect(f.patches, 1);
231 expect(f.archives, 1);
232 expect(f.rows.single['archived_at'], support.at);
233 await tester.pumpWidget(const SizedBox());
234 f.api.close();
235 });
236
237 testWidgets(
238 'reflection receipt loss refreshes history without automatically repeating non-idempotent creation',
239 (tester) async {
240 final f = _HistoryFixture()..loseReceipt = true;
241 await tester.pumpWidget(MaterialApp(
242 home: LearningGoalHistoryPage(api: f.api, goalId: support.goalId)));
243 await tester.pumpAndSettle();
244 await tester.tap(find.text('ثبت بازتاب'));
245 await tester.pumpAndSettle();
246 await tester.enterText(find.byType(TextField), 'بازتاب نامشخص آزمایشی');
247 await tester.tap(find.text('ذخیره'));
248 await tester.pumpAndSettle();
249 expect(f.posts, 1);
250 expect(find.text('بازتاب نامشخص آزمایشی'), findsOneWidget);
251 expect(find.textContaining('نتیجه ثبت قبلی ممکن است نامشخص باشد'),
252 findsOneWidget);
253 await tester.tap(find.text('تازه‌سازی سابقه'));
254 await tester.pumpAndSettle();
255 expect(f.posts, 1);
256 expect(f.rows, hasLength(1));
257 await tester.pumpWidget(const SizedBox());
258 f.api.close();
259 });
260
261 testWidgets('denied reflection reads clear note text and mutation controls',
262 (tester) async {
263 final f = _HistoryFixture()
264 ..rows.add(_HistoryFixture.row('یادداشت خصوصی آزمایشی'));
265 await tester.pumpWidget(MaterialApp(
266 home: LearningGoalHistoryPage(api: f.api, goalId: support.goalId)));
267 await tester.pumpAndSettle();
268 expect(find.text('یادداشت خصوصی آزمایشی'), findsOneWidget);
269 f.denied = true;
270 await tester.tap(find.text('تازه‌سازی سابقه'));
271 await tester.pumpAndSettle();
272 expect(find.text('یادداشت خصوصی آزمایشی'), findsNothing);
273 expect(find.text('ویرایش بازتاب'), findsNothing);
274 expect(find.textContaining('دسترسی'), findsOneWidget);
275 await tester.pumpWidget(const SizedBox());
276 f.api.close();
277 });
278
279 testWidgets(
280 'failed online-only reflection fetch never claims an unsent local record exists',
281 (tester) async {
282 final f = _HistoryFixture();
283 await tester.pumpWidget(MaterialApp(
284 home: LearningGoalHistoryPage(api: f.api, goalId: support.goalId)));
285 await tester.pumpAndSettle();
286 f.offlineRead = true;
287 await tester.tap(find.text('تازه‌سازی سابقه'));
288 await tester.pumpAndSettle();
289 expect(find.textContaining('تغییر ذخیره‌شده'), findsNothing);
290 expect(find.text('اتصال برقرار نیست؛ دریافت بازتاب‌ها به سرور نیاز دارد.'),
291 findsOneWidget);
292 expect(f.posts, 0);
293 expect(find.textContaining('آخرین دریافت سابقه:'), findsNothing);
294 await tester.pumpWidget(const SizedBox());
295 f.api.close();
296 });
297
298 testWidgets(
299 'denied reflection edit clears private text and closes the editor safely',
300 (tester) async {
301 final f = _HistoryFixture()
302 ..rows.add(_HistoryFixture.row('یادداشت پیشین خصوصی'));
303 await tester.pumpWidget(MaterialApp(
304 home: LearningGoalHistoryPage(api: f.api, goalId: support.goalId)));
305 await tester.pumpAndSettle();
306 await tester.tap(find.text('ویرایش بازتاب'));
307 await tester.pumpAndSettle();
308 await tester.enterText(find.byType(TextField), 'متن ویرایش‌شده خصوصی');
309 f.denied = true;
310 await tester.tap(find.text('ذخیره'));
311 await tester.pumpAndSettle();
312 expect(find.byType(TextField), findsNothing);
313 expect(find.text('یادداشت پیشین خصوصی'), findsNothing);
314 expect(find.text('متن ویرایش‌شده خصوصی'), findsNothing);
315 expect(find.textContaining('دسترسی'), findsOneWidget);
316 expect(tester.takeException(), isNull);
317 await tester.pumpWidget(const SizedBox());
318 f.api.close();
319 });
320 }
321
322 class _HistoryFixture {
323 _HistoryFixture() {
324 api = HttpIdentityApi(
325 baseUrl: 'https://history.example.test/api', client: MockClient(handle))
326 ..accessToken = 'synthetic-token'
327 ..currentUserId = support.userId;
328 }
329 late final HttpIdentityApi api;
330 final rows = <Map<String, dynamic>>[];
331 int posts = 0, patches = 0, archives = 0;
332 bool loseReceipt = false, denied = false, offlineRead = false;
333 static Map<String, dynamic> row(String note) => {
334 'id': '30000000-0000-4000-8000-000000000001',
335 'owner_user_id': support.userId,
336 'learning_goal_id': support.goalId,
337 'confidence': 3,
338 'difficulty': 3,
339 'note': note,
340 'source': 'self_reported',
341 'isEvidenceOfStudy': false,
342 'occurred_at': support.at,
343 'created_at': support.at,
344 'updated_at': support.at,
345 'archived_at': null,
346 };
347 Future<http.Response> handle(http.Request request) async {
348 if (denied) return support.response({'error': 'forbidden'}, 403);
349 if (request.method == 'GET') {
350 if (offlineRead) throw http.ClientException('synthetic offline read');
351 return request.url.path.contains('/goals/')
352 ? support.response(support.goal())
353 : support.response(
354 {'items': rows.where((r) => r['archived_at'] == null).toList()});
355 }
356 if (request.method == 'DELETE') {
357 archives++;
358 rows.single['archived_at'] = support.at;
359 return http.Response('', 204);
360 }
361 final body = jsonDecode(request.body) as Map<String, dynamic>;
362 if (request.method == 'POST') {
363 posts++;
364 rows.add({
365 ...row(body['note'] as String),
366 'confidence': body['confidence'],
367 'difficulty': body['difficulty']
368 });
369 if (loseReceipt) {
370 throw http.ClientException('synthetic receipt lost after commit');
371 }
372 return support.response(rows.last, 201);
373 }
374 patches++;
375 rows.single.addAll({
376 'confidence': body['confidence'],
377 'difficulty': body['difficulty'],
378 'note': body['note']
379 });
380 return support.response(rows.single);
381 }
382 }