LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 298 lines 10.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/session_store.dart';
9 import 'package:lifemate/study_coordinator.dart';
10 import 'package:lifemate/study_ui.dart';
11 import 'package:lifemate/dashboard_ui.dart';
12 import 'package:lifemate/phase3_ui.dart' show shortDate;
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 class _MemorySession extends SessionStore {
17 String? value;
18 @override
19 Future<String?> read() async => value;
20 @override
21 Future<void> write(String next) async {
22 value = next;
23 }
24
25 @override
26 Future<void> clear() async {
27 value = null;
28 }
29 }
30
31 HttpIdentityApi apiFor(Future<http.Response> Function(http.Request) handler) =>
32 HttpIdentityApi(
33 baseUrl: 'https://synthetic.example.test/service',
34 client: MockClient(handler),
35 sessionStore: _MemorySession())
36 ..accessToken = 'synthetic-token'
37 ..currentUserId = 'synthetic-child';
38 http.Response jsonResponse(Map<String, dynamic> json, [int status = 200]) =>
39 http.Response(jsonEncode(json), status,
40 headers: {'content-type': 'application/json'});
41 void main() {
42 TestWidgetsFlutterBinding.ensureInitialized();
43 setUp(() {
44 SharedPreferencesAsyncPlatform.instance =
45 InMemorySharedPreferencesAsync.withData({});
46 String? pending;
47 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
48 .setMockMethodCallHandler(
49 const MethodChannel('lifeguide/local_write_guard'), (call) async {
50 if (call.method == 'getBlocked') return pending != null;
51 if (call.method == 'beginWrite') return pending = 'study-test-token';
52 if (call.method == 'completeWrite' && call.arguments == pending) {
53 pending = null;
54 return true;
55 }
56 throw PlatformException(code: 'local_storage_restart_required');
57 });
58 });
59 test('study acknowledgement for another session retains exact queued event',
60 () async {
61 final api = apiFor((req) async {
62 final body = jsonDecode(req.body) as Map;
63 return jsonResponse({
64 'session': {'id': 'different-session', 'version': 1},
65 'acknowledgement': {
66 'mutationId': body['mutationId'],
67 'status': 'accepted',
68 'acceptedAt': '2026-10-08T10:00:00Z'
69 }
70 });
71 });
72 final sync = StudySync(api);
73 await expectLater(sync.start('owned-plan'), throwsA(isA<ApiException>()));
74 expect(await sync.store.readQueue(), hasLength(1));
75 api.close();
76 });
77 test('offline study start reopens and retries the same body once', () async {
78 bool offline = true;
79 final sent = <Map<String, dynamic>>[];
80 final api = apiFor((req) async {
81 final body = Map<String, dynamic>.from(jsonDecode(req.body) as Map);
82 sent.add(body);
83 if (offline) throw http.ClientException('synthetic transport failure');
84 return jsonResponse({
85 'session': {
86 'id': body['id'],
87 'planItemId': body['planItemId'],
88 'status': 'running',
89 'version': 1,
90 'recordedDurationSeconds': 0,
91 'intervals': []
92 },
93 'acknowledgement': {
94 'mutationId': body['mutationId'],
95 'status': 'accepted',
96 'acceptedAt': '2026-10-08T10:00:00Z'
97 }
98 });
99 });
100 final first = await StudySync(api).start('owned-plan');
101 expect(first.queued, isTrue);
102 final reopened = StudySync(api);
103 final retained = await reopened.store.readQueue();
104 expect(retained, hasLength(1));
105 offline = false;
106 await reopened.flush();
107 expect(sent[1], sent[0]);
108 expect(await reopened.store.readQueue(), isEmpty);
109 expect((await reopened.store.readList('study.sessions')).single['status'],
110 'running');
111 api.close();
112 });
113 testWidgets(
114 'timer restores a running server session and labels recorded time',
115 (tester) async {
116 final api = apiFor((req) async => jsonResponse({
117 'sessions': [
118 {
119 'id': 'server-session',
120 'planItemId': 'owned-plan',
121 'status': 'running',
122 'version': 3,
123 'recordedDurationSeconds': 120,
124 'intervals': [],
125 'isEvidenceOfStudy': false
126 }
127 ],
128 'asOf': '2026-10-08T10:00:00Z'
129 }));
130 await tester.pumpWidget(MaterialApp(
131 home: StudyTimerPage(
132 api: api, item: {'id': 'owned-plan', 'title': 'ریاضی'})));
133 await tester.pumpAndSettle();
134 expect(find.text('مکث'), findsOneWidget);
135 expect(find.text('پایان'), findsOneWidget);
136 expect(find.text('2:00'), findsOneWidget);
137 expect(find.textContaining('اثبات مطالعه نیست'), findsOneWidget);
138 await tester.pumpWidget(const SizedBox());
139 api.close();
140 });
141 testWidgets('parent polling failure labels previous report stale',
142 (tester) async {
143 var fail = false;
144 var calls = 0;
145 final api = apiFor((req) async {
146 calls++;
147 return fail
148 ? jsonResponse({'error': 'server_failed'}, 500)
149 : jsonResponse({
150 'metrics': {
151 'totalTasks': 1,
152 'completedTasks': 0,
153 'overdueTasks': 0,
154 'completionPercent': 0,
155 'plannedDurationSeconds': 1800,
156 'recordedDurationSeconds': 120
157 },
158 'items': [
159 {
160 'id': 'plan',
161 'title': 'ریاضی',
162 'kind': 'assignment',
163 'activityState': 'started',
164 'activitySource': 'timer'
165 }
166 ],
167 'daily': [],
168 'subjects': [],
169 'asOf': '2026-10-08T10:00:00Z',
170 'lastSyncAt': '2026-10-08T09:00:00Z'
171 });
172 });
173 await tester.pumpWidget(MaterialApp(
174 home: LearningReportPage(
175 api: api,
176 familyId: 'family',
177 childId: 'child',
178 childName: 'فرزند')));
179 await tester.pumpAndSettle();
180 expect(find.text('ریاضی'), findsOneWidget);
181 fail = true;
182 await tester.pump(const Duration(seconds: 15));
183 await tester.pumpAndSettle();
184 expect(find.textContaining('داده قبلی به‌روز نیست'), findsOneWidget);
185 expect(find.text('ریاضی'), findsOneWidget);
186 expect(calls, 2);
187 await tester.pumpWidget(const SizedBox());
188 await tester.pump(const Duration(seconds: 30));
189 expect(calls, 2);
190 api.close();
191 });
192 for (final denial in [401, 403, 0]) {
193 testWidgets(
194 'parent refresh failure $denial clears previously displayed child data',
195 (tester) async {
196 var fail = false;
197 final api = apiFor((req) async {
198 if (fail) {
199 if (denial == 0) {
200 throw http.ClientException('synthetic transport failure');
201 }
202 return jsonResponse({'error': 'forbidden'}, denial);
203 }
204 return jsonResponse({
205 'metrics': {},
206 'items': [
207 {
208 'id': 'plan',
209 'title': 'اطلاعات فرزند',
210 'kind': 'assignment',
211 'activityState': 'started',
212 'activitySource': 'timer'
213 }
214 ],
215 'daily': [],
216 'subjects': [],
217 'asOf': '2026-10-08T10:00:00Z'
218 });
219 });
220 await tester.pumpWidget(MaterialApp(
221 home: LearningReportPage(
222 api: api,
223 familyId: 'family',
224 childId: 'child',
225 childName: 'فرزند')));
226 await tester.pumpAndSettle();
227 expect(find.text('اطلاعات فرزند'), findsOneWidget);
228 fail = true;
229 await tester.pump(const Duration(seconds: 15));
230 await tester.pumpAndSettle();
231 expect(find.text('اطلاعات فرزند'), findsNothing);
232 expect(
233 find.textContaining(denial == 401
234 ? 'نشست ورود'
235 : denial == 403
236 ? 'دسترسی نداری'
237 : 'اتصال برقرار نیست'),
238 findsOneWidget);
239 await tester.pumpWidget(const SizedBox());
240 api.close();
241 });
242 }
243
244 testWidgets('weekly and monthly reports include the rest of today in Tehran',
245 (tester) async {
246 final now = DateTime.now().toUtc();
247 final tehran = now.add(const Duration(hours: 3, minutes: 30));
248 final dayEnd = DateTime.utc(tehran.year, tehran.month, tehran.day + 1)
249 .subtract(const Duration(hours: 3, minutes: 30));
250 final laterToday = now.add(dayEnd.difference(now) ~/ 2);
251 final windows = <Map<String, DateTime>>[];
252 final api = apiFor((request) async {
253 final from = DateTime.parse(request.url.queryParameters['from']!);
254 final to = DateTime.parse(request.url.queryParameters['to']!);
255 windows.add({'from': from, 'to': to});
256 final included = !laterToday.isBefore(from) && laterToday.isBefore(to);
257 return jsonResponse({
258 'metrics': {
259 'plannedDurationSeconds': 1800,
260 'plannedInRangeDurationSeconds': included ? 1800 : 0,
261 'recordedDurationSeconds': 1500
262 },
263 'items': [
264 {
265 'id': 'today-plan',
266 'title': 'ریاضی امروز',
267 'kind': 'assignment',
268 'dueAt': laterToday.toIso8601String(),
269 'plannedDurationSeconds': 1800,
270 }
271 ],
272 'daily': [],
273 'subjects': [],
274 'asOf': now.toIso8601String(),
275 });
276 });
277 await tester.pumpWidget(MaterialApp(
278 home: LearningReportPage(
279 api: api,
280 familyId: 'family',
281 childId: 'child',
282 childName: 'فرزند')));
283 await tester.pumpAndSettle();
284 expect(windows.single['to'], dayEnd);
285 expect(windows.single['from'], dayEnd.subtract(const Duration(days: 7)));
286 expect(find.text('زمان برنامه‌ریزی‌شده: 30 دقیقه'), findsOneWidget);
287 expect(find.text('زمان ثبت‌شده: 25 دقیقه'), findsOneWidget);
288 expect(
289 find.textContaining('دریافت سرور: ${shortDate(now)}'), findsOneWidget);
290 await tester.tap(find.text('ماهانه'));
291 await tester.pumpAndSettle();
292 expect(windows.last['to'], dayEnd);
293 expect(windows.last['from'], dayEnd.subtract(const Duration(days: 30)));
294 expect(find.text('زمان برنامه‌ریزی‌شده: 30 دقیقه'), findsOneWidget);
295 await tester.pumpWidget(const SizedBox());
296 api.close();
297 });
298 }