LifeMate — Personal, Family & Learning Companion

infra/lifeguide-cloudflare-qa
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 410 lines 15 KB
Raw
1 import 'dart:async';
2 import 'dart:convert';
3
4 import 'package:flutter/material.dart';
5 import 'package:flutter/services.dart';
6 import 'package:flutter_test/flutter_test.dart';
7 import 'package:http/http.dart' as http;
8 import 'package:http/testing.dart';
9 import 'package:lifemate/api.dart';
10 import 'package:lifemate/content_review_sync.dart';
11 import 'package:lifemate/content_review_ui.dart';
12 import 'package:lifemate/offline_store.dart';
13 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
14 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
15
16 const feedbackId = '81111111-1111-4111-8111-111111111111';
17 const mutationId = '91111111-1111-4111-8111-111111111111';
18 const created = '2026-10-11T10:00:00Z';
19 const briefId = 'a1111111-1111-4111-8111-111111111111';
20 Map<String, dynamic> validBrief() => {
21 'id': briefId,
22 'title': 'پیشنهاد بررسی و توسعه محتوای آموزشی',
23 'createdAt': created,
24 'sourceCount': 1,
25 'categories': [
26 {'category': 'topic_request', 'count': 1}
27 ],
28 'units': [],
29 'tasks': [
30 'نسخه رسمی کتاب و هدف یادگیری این درس را بررسی کنید.',
31 'محتوای پیشنهادی و سؤال‌های تمرینی را به‌طور کامل بازبینی کنید.',
32 'برای تغییر پیشنهادی معیار پذیرش، آزمون و PR مستقل تهیه کنید.',
33 'انتشار محتوا و استقرار فقط پس از بازبینی و مجوز جداگانه انجام شود.'
34 ],
35 'notice':
36 'این پیشنهاد ساختاری فاقد متن بازخورد و اطلاعات خصوصی است؛ تأیید محتوا یا دستور انتشار نیست.'
37 };
38 Map<String, dynamic> feedback({String status = 'received', int version = 1}) =>
39 {
40 'id': feedbackId,
41 'unitId': null,
42 'category': 'topic_request',
43 'summary': 'تمرین جمع به روش تصویری',
44 'status': status,
45 'version': version,
46 'createdAt': created,
47 'updatedAt': created,
48 };
49 http.Response jsonResponse(Object value, [int status = 200]) =>
50 http.Response(jsonEncode(value), status,
51 headers: {'content-type': 'application/json; charset=utf-8'});
52 HttpIdentityApi apiWith(Future<http.Response> Function(http.Request) handler,
53 {String actor = 'synthetic-reviewer'}) =>
54 HttpIdentityApi(
55 baseUrl: 'https://review.example.test/api', client: MockClient(handler))
56 ..accessToken = 'synthetic-token'
57 ..currentUserId = actor;
58
59 void main() {
60 TestWidgetsFlutterBinding.ensureInitialized();
61 setUp(() {
62 SharedPreferencesAsyncPlatform.instance =
63 InMemorySharedPreferencesAsync.withData({});
64 String? token;
65 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
66 .setMockMethodCallHandler(
67 const MethodChannel('lifeguide/local_write_guard'), (call) async {
68 if (call.method == 'getBlocked') return token != null;
69 if (call.method == 'beginWrite') return token = 'review-write';
70 if (call.method == 'completeWrite' && call.arguments == token) {
71 token = null;
72 return true;
73 }
74 throw PlatformException(code: 'local_storage_restart_required');
75 });
76 });
77
78 test(
79 'lost review acknowledgement keeps only metadata and retries exact body after reopen',
80 () async {
81 var lost = true;
82 final sent = <String>[];
83 final api = apiWith((request) async {
84 if (request.url.path.endsWith('/content-capabilities')) {
85 return jsonResponse({
86 'permissions': ['feedback.read', 'feedback.review']
87 });
88 }
89 sent.add(request.body);
90 if (lost) throw http.ClientException('synthetic lost receipt');
91 return jsonResponse({
92 'feedback': feedback(status: 'triaged', version: 2),
93 'acknowledgement': {
94 'mutationId': mutationId,
95 'feedbackId': feedbackId,
96 'status': 'already_applied'
97 }
98 });
99 });
100 final body = {
101 'mutationId': mutationId,
102 'expectedVersion': 1,
103 'status': 'triaged'
104 };
105 await expectLater(ContentReviewSync(api).review(feedbackId, body),
106 throwsA(predicate(isOfflineFailure)));
107 final durable = await OfflineStore.forApi(api).readQueue();
108 expect(durable.single['payload'], body);
109 expect(jsonEncode(durable), isNot(contains('تمرین جمع')));
110 expect(await OfflineStore.forApi(api).readList('content_review'), isEmpty);
111 lost = false;
112 await ContentReviewSync(api).retry(durable.single);
113 expect(sent.length, 2);
114 expect(sent[0], sent[1]);
115 expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
116 api.close();
117 });
118
119 test(
120 'wrong receipt leaves pending metadata and another account cannot retry it',
121 () async {
122 final api = apiWith((request) async => request.method == 'GET'
123 ? jsonResponse({
124 'permissions': ['feedback.read', 'feedback.review']
125 })
126 : jsonResponse({
127 'feedback': feedback(status: 'triaged', version: 2),
128 'acknowledgement': {
129 'mutationId': 'wrong',
130 'feedbackId': feedbackId,
131 'status': 'accepted'
132 }
133 }));
134 final sync = ContentReviewSync(api);
135 await expectLater(
136 sync.review(feedbackId, {
137 'mutationId': mutationId,
138 'expectedVersion': 1,
139 'status': 'triaged'
140 }),
141 throwsA(isA<ApiException>()));
142 final pending = (await sync.pending()).single;
143 api.currentUserId = 'other-account';
144 await expectLater(sync.retry(pending), throwsA(isA<ApiException>()));
145 expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
146 api.close();
147 });
148
149 test('offline capability check never creates a reviewer mutation', () async {
150 final api =
151 apiWith((request) async => throw http.ClientException('offline'));
152 await expectLater(
153 ContentReviewSync(api).review(feedbackId, {
154 'mutationId': mutationId,
155 'expectedVersion': 1,
156 'status': 'triaged'
157 }),
158 throwsA(predicate(isOfflineFailure)));
159 expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
160 api.close();
161 });
162
163 test(
164 'lost brief receipt retries immutable metadata and never exports a summary',
165 () async {
166 var lost = true;
167 final sent = <String>[];
168 final api = apiWith((request) async {
169 if (request.url.path.endsWith('/content-capabilities')) {
170 return jsonResponse({
171 'permissions': ['feedback.read', 'brief.prepare']
172 });
173 }
174 sent.add(request.body);
175 if (lost) throw http.ClientException('lost response');
176 return jsonResponse({
177 'brief': validBrief(),
178 'acknowledgement': {
179 'mutationId': mutationId,
180 'briefId': briefId,
181 'status': 'already_applied'
182 }
183 });
184 });
185 final body = <String, dynamic>{
186 'mutationId': mutationId,
187 'feedback': [
188 {'id': feedbackId, 'expectedVersion': 3}
189 ]
190 };
191 final result = ContentReviewSync(api).prepareBrief(body);
192 (body['feedback'] as List).single['expectedVersion'] = 999;
193 await expectLater(result, throwsA(predicate(isOfflineFailure)));
194 final saved = (await ContentReviewSync(api).pending()).single;
195 expect((saved['payload'] as Map)['feedback'], [
196 {'id': feedbackId, 'expectedVersion': 3}
197 ]);
198 expect(jsonEncode(saved), isNot(contains('summary')));
199 lost = false;
200 final accepted = await ContentReviewSync(api).retry(saved);
201 expect(sent[0], sent[1]);
202 expect(accepted['brief'], validBrief());
203 expect(await OfflineStore.forApi(api).readQueue(), isEmpty);
204 api.close();
205 });
206
207 test(
208 'current newer state can acknowledge an applied review but wrong accepted transition cannot',
209 () async {
210 var replay = false;
211 final api = apiWith((request) async {
212 if (request.method == 'GET') {
213 return jsonResponse({
214 'permissions': ['feedback.read', 'feedback.review']
215 });
216 }
217 return jsonResponse({
218 'feedback': feedback(status: 'planned', version: 3),
219 'acknowledgement': {
220 'mutationId': mutationId,
221 'feedbackId': feedbackId,
222 'status': replay ? 'already_applied' : 'accepted'
223 }
224 });
225 });
226 final sync = ContentReviewSync(api);
227 await expectLater(
228 sync.review(feedbackId, {
229 'mutationId': mutationId,
230 'expectedVersion': 1,
231 'status': 'triaged'
232 }),
233 throwsA(isA<ApiException>()));
234 expect(await sync.pending(), hasLength(1));
235 replay = true;
236 await sync.retry((await sync.pending()).single);
237 expect(await sync.pending(), isEmpty);
238 api.close();
239 });
240
241 test(
242 'inbox rejects injected private fields and preserves actual paging/filter query',
243 () async {
244 final api = apiWith((request) async {
245 expect(request.url.queryParameters,
246 {'limit': '20', 'cursor': feedbackId, 'status': 'planned'});
247 return jsonResponse({
248 'feedback': [
249 {
250 ...feedback(status: 'planned'),
251 'ownerEmail': 'synthetic@example.test'
252 }
253 ],
254 'nextCursor': null,
255 'total': 1
256 });
257 });
258 await expectLater(
259 ContentReviewSync(api).inbox(status: 'planned', cursor: feedbackId),
260 throwsA(isA<ApiException>()));
261 expect(await OfflineStore.forApi(api).readList('content_review'), isEmpty);
262 api.close();
263 });
264
265 test('revoked scope discards a delayed inbox response', () async {
266 final delayed = Completer<http.Response>();
267 final api = apiWith((request) => delayed.future);
268 final sync = ContentReviewSync(api);
269 final request = sync.inbox();
270 await Future<void>.delayed(Duration.zero);
271 await OfflineStore.invalidateNamespace(api.cacheNamespace!);
272 delayed.complete(jsonResponse({
273 'feedback': [feedback()],
274 'nextCursor': null,
275 'total': 1
276 }));
277 await expectLater(request, throwsA(isA<ApiException>()));
278 api.close();
279 });
280
281 testWidgets(
282 'read-only reviewer sees Persian status but no moderation buttons, and network failure clears summaries',
283 (tester) async {
284 var failing = false;
285 final api = apiWith((request) async {
286 if (failing) throw http.ClientException('synthetic offline');
287 if (request.url.path.endsWith('/content-capabilities')) {
288 return jsonResponse({
289 'permissions': ['feedback.read']
290 });
291 }
292 return jsonResponse({
293 'feedback': [feedback()],
294 'nextCursor': null,
295 'total': 1
296 });
297 });
298 await tester.pumpWidget(MaterialApp(home: ContentReviewPage(api: api)));
299 await tester.pumpAndSettle();
300 expect(find.text('تمرین جمع به روش تصویری'), findsOneWidget);
301 expect(find.textContaining('دریافت‌شده'), findsWidgets);
302 expect(find.byKey(const Key('review-status-$feedbackId')), findsNothing);
303 failing = true;
304 await tester.tap(find.byKey(const Key('content-refresh')));
305 await tester.pumpAndSettle();
306 expect(find.text('تمرین جمع به روش تصویری'), findsNothing);
307 expect(find.textContaining('اتصال'), findsWidgets);
308 await tester.pumpWidget(const SizedBox());
309 api.close();
310 });
311
312 testWidgets(
313 'late inbox response cannot expose summaries after newer permission revocation',
314 (tester) async {
315 final delayed = Completer<http.Response>();
316 var capabilityReads = 0;
317 final api = apiWith((request) async {
318 if (request.url.path.endsWith('/content-capabilities')) {
319 capabilityReads++;
320 return jsonResponse({
321 'permissions': capabilityReads == 1 ? ['feedback.read'] : []
322 });
323 }
324 return delayed.future;
325 });
326 await tester.pumpWidget(MaterialApp(home: ContentReviewPage(api: api)));
327 await tester.pump();
328 await tester.pump();
329 await tester.tap(find.byKey(const Key('content-refresh')));
330 await tester.pumpAndSettle();
331 delayed.complete(jsonResponse({
332 'feedback': [feedback()],
333 'nextCursor': null,
334 'total': 1
335 }));
336 await tester.pumpAndSettle();
337 expect(find.text('تمرین جمع به روش تصویری'), findsNothing);
338 expect(find.textContaining('مجوز'), findsWidgets);
339 await tester.pumpWidget(const SizedBox());
340 api.close();
341 });
342
343 testWidgets(
344 'withdrawn brief is revalidated before clipboard and never copied',
345 (tester) async {
346 tester.view.physicalSize = const Size(1000, 1600);
347 tester.view.devicePixelRatio = 1;
348 addTearDown(tester.view.resetPhysicalSize);
349 addTearDown(tester.view.resetDevicePixelRatio);
350 final clipboardWrites = <Object?>[];
351 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
352 .setMockMethodCallHandler(SystemChannels.platform, (call) async {
353 if (call.method == 'Clipboard.setData') {
354 clipboardWrites.add(call.arguments);
355 }
356 return null;
357 });
358 addTearDown(() => TestDefaultBinaryMessengerBinding
359 .instance.defaultBinaryMessenger
360 .setMockMethodCallHandler(SystemChannels.platform, null));
361 var revalidated = false;
362 final api = apiWith((request) async {
363 if (request.url.path.endsWith('/content-capabilities')) {
364 return jsonResponse({
365 'permissions': ['feedback.read', 'brief.prepare']
366 });
367 }
368 if (request.method == 'POST') {
369 final body = jsonDecode(request.body) as Map;
370 expect(body['feedback'], [
371 {'id': feedbackId, 'expectedVersion': 3}
372 ]);
373 return jsonResponse({
374 'brief': validBrief(),
375 'acknowledgement': {
376 'mutationId': body['mutationId'],
377 'briefId': briefId,
378 'status': 'accepted'
379 }
380 });
381 }
382 if (request.url.path.endsWith('/briefs/$briefId')) {
383 revalidated = true;
384 return jsonResponse({'error': 'brief_invalidated'}, 409);
385 }
386 return jsonResponse({
387 'feedback': [feedback(status: 'planned', version: 3)],
388 'nextCursor': null,
389 'total': 1
390 });
391 });
392 await tester.pumpWidget(MaterialApp(home: ContentReviewPage(api: api)));
393 await tester.pumpAndSettle();
394 await tester.tap(find.byType(Checkbox));
395 await tester.pumpAndSettle();
396 await tester.tap(find.text('تهیه پیشنهاد توسعه، بدون متن بازخورد'));
397 await tester.pumpAndSettle();
398 expect(find.byKey(const Key('copy-content-brief')), findsOneWidget);
399 await tester.ensureVisible(find.byKey(const Key('copy-content-brief')));
400 await tester.tap(find.byKey(const Key('copy-content-brief')));
401 await tester.pumpAndSettle();
402 expect(revalidated, true);
403 expect(clipboardWrites, isEmpty);
404 expect(find.byKey(const Key('copy-content-brief')), findsNothing);
405 expect(find.text('تمرین جمع به روش تصویری'), findsNothing);
406 expect(find.textContaining('نسخه یا رضایت'), findsOneWidget);
407 await tester.pumpWidget(const SizedBox());
408 api.close();
409 });
410 }