LifeMate — Personal, Family & Learning Companion

fix/study-duration-display
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 355 lines 13.5 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/learning_reviews_ui.dart';
11 import 'package:lifemate/offline_store.dart';
12 import 'package:lifemate/session_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 // HTTP/widget fixtures only; not real teaching, device or API/SQL acceptance.
17 const _unit = '00000000-0000-4000-8000-000000000101';
18 const _laterUnit = '00000000-0000-4000-8000-000000000102';
19 const _course = '00000000-0000-4000-8000-000000000103';
20 const _attemptId = '00000000-0000-4000-8000-000000000104';
21 const _mutationId = '00000000-0000-4000-8000-000000000105';
22 const _assessment = '00000000-0000-4000-8000-000000000106';
23 const _fetchedAt = '2026-10-11T05:00:00Z';
24
25 class _Session implements SessionStore {
26 @override
27 Future<String?> read() async => null;
28 @override
29 Future<void> write(String value) async {}
30 @override
31 Future<void> clear() async {}
32 }
33
34 Map<String, dynamic> _attempt() => {
35 'mutationId': _mutationId,
36 'attemptId': _attemptId,
37 'unitId': _unit,
38 'assessmentId': _assessment,
39 'assessmentVersion': 2,
40 'correctCount': 1,
41 'total': 2,
42 'feedback': [
43 {
44 'questionId': 'q1',
45 'objectiveId': 'o1',
46 'correct': true,
47 'explanationFa': 'توضیح درست صرفاً آزمایشی',
48 'remediationFa': 'مرور اول صرفاً آزمایشی',
49 },
50 {
51 'questionId': 'q2',
52 'objectiveId': 'o2',
53 'correct': false,
54 'explanationFa': 'توضیح دوم صرفاً آزمایشی',
55 'remediationFa': 'راهنمای تمرین صرفاً آزمایشی',
56 },
57 ],
58 'resultLabel': 'needs_practice',
59 'nextReviewAt': '2026-10-12T10:00:00Z',
60 'schedulePolicy': 'pilot-1-or-3-days',
61 'source': 'quiz_answers',
62 'acceptedAt': '2026-10-10T10:00:00Z',
63 'confidence': 'unsure',
64 };
65
66 class _Fixture {
67 _Fixture() {
68 api = HttpIdentityApi(
69 baseUrl: 'https://reviews.example.test/api',
70 client: MockClient(handle),
71 sessionStore: _Session())
72 ..accessToken = 'synthetic-token'
73 ..currentUserId = 'synthetic-review-learner-${next++}';
74 store = OfflineStore.forNamespace(api.cacheNamespace!,
75 session: OfflineSession());
76 }
77 static int next = 0;
78 late final HttpIdentityApi api;
79 late final OfflineStore store;
80 final requests = <http.Request>[];
81 bool offline = false;
82 int? forbidden, locatorFailure;
83 Completer<void>? delay;
84 List<Map<String, dynamic>> reviews = [
85 {
86 'unitId': _unit,
87 'nextReviewAt': '2025-01-01T10:00:00Z',
88 'schedulePolicy': 'pilot-1-or-3-days',
89 },
90 {
91 'unitId': _laterUnit,
92 'nextReviewAt': '2050-01-01T10:00:00Z',
93 'schedulePolicy': 'pilot-1-or-3-days',
94 },
95 ];
96 List<Map<String, dynamic>> attempts = [_attempt()];
97 String fetchedAt = _fetchedAt;
98
99 http.Response response(Object value, [int status = 200]) =>
100 http.Response(jsonEncode(value), status,
101 headers: {'content-type': 'application/json; charset=utf-8'});
102
103 Future<http.Response> handle(http.Request request) async {
104 requests.add(request);
105 if (delay != null) await delay!.future;
106 if (offline) throw http.ClientException('synthetic offline');
107 if (forbidden != null) {
108 return response({'error': 'synthetic-session-refused'}, forbidden!);
109 }
110 if (request.url.path.endsWith('/me/learning-reviews')) {
111 return response({'reviews': reviews, 'fetchedAt': fetchedAt});
112 }
113 if (request.url.path.endsWith('/me/learning-attempts')) {
114 return response({'attempts': attempts, 'fetchedAt': fetchedAt});
115 }
116 if (request.url.path.contains('/education/units/')) {
117 if (locatorFailure != null) {
118 return response({'error': 'unit_not_found'}, locatorFailure!);
119 }
120 final id = request.url.path.split('/').last;
121 return response({
122 'unit': {
123 'id': id,
124 'titleFa': id == _unit ? 'جمع آزمایشی' : 'درس آینده آزمایشی',
125 'courseId': _course,
126 },
127 'fetchedAt': _fetchedAt,
128 });
129 }
130 throw StateError('Unexpected synthetic request ${request.url.path}');
131 }
132 }
133
134 Widget _screen(_Fixture fixture,
135 {Future<void> Function(BuildContext, String)? open}) =>
136 MaterialApp(
137 home: LearningReviewsPage(
138 api: fixture.api, onOpenLesson: open ?? (_, __) async {}));
139
140 void main() {
141 TestWidgetsFlutterBinding.ensureInitialized();
142 setUp(() {
143 SharedPreferencesAsyncPlatform.instance =
144 InMemorySharedPreferencesAsync.withData({});
145 String? write;
146 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
147 .setMockMethodCallHandler(
148 const MethodChannel('lifeguide/local_write_guard'), (call) async {
149 if (call.method == 'getBlocked') return write != null;
150 if (call.method == 'beginWrite') return write = 'synthetic-review-write';
151 if (call.method == 'completeWrite' && call.arguments == write) {
152 write = null;
153 return true;
154 }
155 throw PlatformException(code: 'local_storage_restart_required');
156 });
157 });
158
159 testWidgets(
160 'owner sees due reviews and server-only history with lesson names',
161 (tester) async {
162 final f = _Fixture();
163 String? opened;
164 await tester.pumpWidget(_screen(f, open: (_, id) async => opened = id));
165 await tester.pumpAndSettle();
166 expect(find.text('مرور و تاریخچه یادگیری'), findsOneWidget);
167 expect(find.text('موعد رسیده'), findsOneWidget);
168 expect(find.text('مرور آینده'), findsOneWidget);
169 expect(find.text('جمع آزمایشی'), findsWidgets);
170 expect(find.textContaining('به‌تنهایی اثبات تسلط نیست'), findsOneWidget);
171 expect(f.requests.where((r) => r.url.path.contains('/education/units/')),
172 hasLength(2),
173 reason: 'Locator titles must be deduplicated');
174 expect(f.requests.every((r) => r.method == 'GET'), true);
175 expect(
176 f.requests.every(
177 (r) => r.headers['authorization'] == 'Bearer synthetic-token'),
178 true);
179 expect(f.requests.every((r) => r.url.query.isEmpty), true,
180 reason: 'No child/owner override in private history requests');
181 await tester.scrollUntilVisible(
182 find.byKey(const Key('attempt-$_attemptId')), 250);
183 expect(find.text('۱ پاسخ درست از ۲'), findsOneWidget);
184 expect(find.textContaining('نیاز به تمرین'), findsOneWidget);
185 expect(find.textContaining(_unit), findsNothing);
186 await tester.scrollUntilVisible(
187 find.byKey(const Key('review-$_unit')), -250);
188 await tester.ensureVisible(find.byKey(const Key('open-review-$_unit')));
189 await tester.tap(find.byKey(const Key('open-review-$_unit')));
190 await tester.pumpAndSettle();
191 expect(opened, _unit);
192 await tester.pumpWidget(const SizedBox());
193 f.api.close();
194 });
195
196 testWidgets(
197 'pausing during lesson open does not leave resumed history locked',
198 (tester) async {
199 final f = _Fixture();
200 final opening = Completer<void>();
201 await tester.pumpWidget(_screen(f, open: (_, __) => opening.future));
202 await tester.pumpAndSettle();
203 await tester.ensureVisible(find.byKey(const Key('open-review-$_unit')));
204 await tester.tap(find.byKey(const Key('open-review-$_unit')));
205 await tester.pump();
206 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused);
207 await tester.pump();
208 opening.complete();
209 await tester.pump();
210 final beforeResume = f.requests.length;
211 tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
212 await tester.pumpAndSettle();
213 expect(f.requests.length, greaterThan(beforeResume),
214 reason:
215 'A discarded open callback must not block a fresh resumed read');
216 expect(find.text('جمع آزمایشی'), findsWidgets);
217 await tester.pumpWidget(const SizedBox());
218 f.api.close();
219 });
220
221 testWidgets('same API object switching account discards prior receipts',
222 (tester) async {
223 final f = _Fixture();
224 await tester.pumpWidget(_screen(f));
225 await tester.pumpAndSettle();
226 expect(find.text('جمع آزمایشی'), findsWidgets);
227 f.api.currentUserId = 'another-synthetic-review-learner';
228 f.reviews = [];
229 f.attempts = [];
230 await tester.pumpWidget(_screen(f));
231 await tester.pumpAndSettle();
232 expect(find.text('جمع آزمایشی'), findsNothing);
233 expect(find.text('مروری ثبت نشده است.'), findsOneWidget);
234 await tester.pumpWidget(const SizedBox());
235 f.api.close();
236 });
237
238 for (final failure in [0, 401, 403, 500]) {
239 testWidgets(
240 'history clears private receipts after refresh failure $failure',
241 (tester) async {
242 final f = _Fixture();
243 await tester.pumpWidget(_screen(f));
244 await tester.pumpAndSettle();
245 expect(find.text('جمع آزمایشی'), findsWidgets);
246 if (failure == 0) {
247 f.offline = true;
248 } else {
249 f.forbidden = failure;
250 }
251 await tester.pump(const Duration(seconds: 30));
252 await tester.pumpAndSettle();
253 expect(find.text('جمع آزمایشی'), findsNothing);
254 expect(find.textContaining('تأیید تازه دریافت نشده'), findsOneWidget);
255 expect(find.byKey(const Key('attempt-$_attemptId')), findsNothing);
256 await tester.pumpWidget(const SizedBox());
257 f.api.close();
258 });
259 }
260
261 testWidgets('pending answers survive reopen without appearing as graded work',
262 (tester) async {
263 final f = _Fixture();
264 f.attempts = [];
265 f.reviews = [];
266 await f.store.enqueue({
267 'id': _mutationId,
268 'entityId': _assessment,
269 'entityType': 'learning_attempt',
270 'payload': {
271 'answers': ['PRIVATE-UNSENT-ANSWER'],
272 'unitId': _unit
273 },
274 });
275 final before = jsonEncode(await f.store.readQueue());
276 await tester.pumpWidget(_screen(f));
277 await tester.pumpAndSettle();
278 expect(find.textContaining('روی این دستگاه: ۱'), findsOneWidget);
279 expect(
280 find.text('هنوز نتیجه پذیرفته‌شده‌ای ثبت نشده است.'), findsOneWidget);
281 expect(find.textContaining('PRIVATE-UNSENT-ANSWER'), findsNothing);
282 expect(f.requests.every((r) => r.method == 'GET'), true);
283 await tester.pumpWidget(const SizedBox());
284 await tester.pumpWidget(_screen(f));
285 await tester.pumpAndSettle();
286 expect(find.textContaining('روی این دستگاه: ۱'), findsOneWidget);
287 expect(jsonEncode(await f.store.readQueue()), before,
288 reason: 'History never grades or acknowledges queued answers');
289 await tester.pumpWidget(const SizedBox());
290 f.api.close();
291 });
292
293 testWidgets('late old-account history cannot resurrect after API replacement',
294 (tester) async {
295 final first = _Fixture()..delay = Completer<void>();
296 final second = _Fixture()
297 ..reviews = []
298 ..attempts = [];
299 await tester.pumpWidget(_screen(first));
300 await tester.pump();
301 await tester.pumpWidget(_screen(second));
302 await tester.pumpAndSettle();
303 expect(find.text('مروری ثبت نشده است.'), findsOneWidget);
304 first.delay!.complete();
305 await tester.pumpAndSettle();
306 expect(find.text('جمع آزمایشی'), findsNothing);
307 expect(find.byKey(const Key('attempt-$_attemptId')), findsNothing);
308 await tester.pumpWidget(const SizedBox());
309 first.api.close();
310 second.api.close();
311 });
312
313 for (final corruption in ['wrong-total', 'duplicate-id', 'bad-time']) {
314 testWidgets('malformed history $corruption never displays a graded receipt',
315 (tester) async {
316 final f = _Fixture();
317 if (corruption == 'wrong-total') {
318 f.attempts.single['total'] = 3;
319 } else if (corruption == 'duplicate-id') {
320 f.attempts.add(_attempt());
321 } else {
322 f.fetchedAt = 'not-a-server-timestamp';
323 }
324 await tester.pumpWidget(_screen(f));
325 await tester.pumpAndSettle();
326 expect(find.text('۱ پاسخ درست از ۲'), findsNothing);
327 expect(find.textContaining('پاسخ معتبر دریافت نشد'), findsOneWidget);
328 await tester.pumpWidget(const SizedBox());
329 f.api.close();
330 });
331 }
332
333 testWidgets(
334 'removed lesson keeps acknowledged receipt and reports unavailable',
335 (tester) async {
336 final f = _Fixture()..locatorFailure = 404;
337 var opened = false;
338 await tester.pumpWidget(_screen(f, open: (_, __) async => opened = true));
339 await tester.pumpAndSettle();
340 expect(find.text('درس از دسترس خارج شده'), findsWidgets);
341 await tester.ensureVisible(find.byKey(const Key('open-review-$_unit')));
342 await tester.tap(find.byKey(const Key('open-review-$_unit')));
343 await tester.pumpAndSettle();
344 expect(opened, false);
345 await tester.scrollUntilVisible(
346 find.textContaining('فعلاً در کتابخانه فعال در دسترس نیست'), -200);
347 expect(find.textContaining('فعلاً در کتابخانه فعال در دسترس نیست'),
348 findsOneWidget);
349 await tester.scrollUntilVisible(
350 find.byKey(const Key('attempt-$_attemptId')), 200);
351 expect(find.text('۱ پاسخ درست از ۲'), findsOneWidget);
352 await tester.pumpWidget(const SizedBox());
353 f.api.close();
354 });
355 }