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 256 lines 9.15 KB
Raw
1 import 'dart:convert';
2 import 'package:flutter/services.dart';
3 import 'package:flutter_test/flutter_test.dart';
4 import 'package:http/http.dart' as http;
5 import 'package:http/testing.dart';
6 import 'package:lifemate/api.dart';
7 import 'package:lifemate/offline_store.dart';
8 import 'package:lifemate/school_management_ui.dart';
9 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
10 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
11
12 const owner = '10000000-0000-4000-8000-000000000001';
13 const secondOwner = '10000000-0000-4000-8000-000000000002';
14 const stamp = '2026-10-11T12:00:00Z';
15 const contextId = '20000000-0000-4000-8000-000000000001';
16 http.Response response(Object body, [int status = 200]) =>
17 http.Response(jsonEncode(body), status,
18 headers: {'content-type': 'application/json; charset=utf-8'});
19 Map<String, dynamic> entity(String id,
20 {int version = 1, String title = 'مدرسه', bool active = true}) =>
21 {
22 'id': id,
23 'title': title,
24 'kind': 'student',
25 'user_id': owner,
26 'active': active,
27 'version': version,
28 'created_at': stamp,
29 'updated_at': stamp
30 };
31
32 class Fixture {
33 Fixture({String endpoint = 'https://school.test/api', String user = owner}) {
34 api = HttpIdentityApi(baseUrl: endpoint, client: MockClient(handle))
35 ..accessToken = 'synthetic'
36 ..currentUserId = user;
37 store = OfflineStore.forApi(api);
38 sync = SchoolLifecycleSync(api, store: store);
39 }
40 late final HttpIdentityApi api;
41 late final OfflineStore store;
42 late final SchoolLifecycleSync sync;
43 final rows = <String, Map<String, dynamic>>{};
44 final receipts = <String, Map<String, dynamic>>{};
45 final posts = <String>[];
46 bool offline = false,
47 loseAck = false,
48 malformedAck = false,
49 conflict = false,
50 forged = false;
51 Future<http.Response> handle(http.Request request) async {
52 if (offline) throw http.ClientException('synthetic offline');
53 if (request.method == 'GET') {
54 return response({
55 'contexts': rows.values.toList(),
56 'years': [],
57 'terms': [],
58 'fetchedAt': stamp
59 });
60 }
61 posts.add(request.body);
62 final body = jsonDecode(request.body) as Map<String, dynamic>;
63 if (conflict) return response({'error': 'school_version_conflict'}, 409);
64 final type = request.url.path.split('/').reversed.skip(1).first;
65 if (!receipts.containsKey(body['mutationId'])) {
66 final old = rows[body['entityId']];
67 final data = body['data'] as Map;
68 final row = entity(body['entityId'],
69 version: body['expectedVersion'] + 1,
70 title: data['title'] ?? old?['title'] ?? 'مدرسه',
71 active: body['operation'] != 'archive');
72 rows[row['id']] = row;
73 receipts[body['mutationId']] = {
74 'mutationId': body['mutationId'],
75 'entityId': body['entityId'],
76 'entityType': type,
77 'operation': body['operation'],
78 'status': 'accepted',
79 'appliedVersion': row['version'],
80 'acceptedAt': stamp
81 };
82 }
83 if (loseAck) {
84 loseAck = false;
85 throw http.ClientException('ACK lost after synthetic commit');
86 }
87 final ack = {
88 ...receipts[body['mutationId']]!,
89 'status': posts
90 .where(
91 (p) => jsonDecode(p)['mutationId'] == body['mutationId'])
92 .length >
93 1
94 ? 'already_applied'
95 : 'accepted'
96 };
97 if (malformedAck) ack['entityId'] = contextId;
98 final row = {...rows[body['entityId']]!};
99 if (forged) row['user_id'] = secondOwner;
100 return response({'entity': row, 'acknowledgement': ack});
101 }
102 }
103
104 void main() {
105 TestWidgetsFlutterBinding.ensureInitialized();
106 setUp(() {
107 SharedPreferencesAsyncPlatform.instance =
108 InMemorySharedPreferencesAsync.withData({});
109 String? guard;
110 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
111 .setMockMethodCallHandler(
112 const MethodChannel('lifeguide/local_write_guard'), (call) async {
113 if (call.method == 'getBlocked') return guard != null;
114 if (call.method == 'beginWrite') return guard = 'school-sync';
115 if (call.method == 'completeWrite' && call.arguments == guard) {
116 guard = null;
117 return true;
118 }
119 throw PlatformException(code: 'local_storage_restart_required');
120 });
121 });
122 test(
123 'lost ACK is durably retained and reopened helper sends exact bytes once without a duplicate',
124 () async {
125 final f = Fixture()..loseAck = true;
126 final result = await f.sync
127 .mutate('contexts', 'create', {'title': ' مدرسه ', 'kind': 'student'});
128 expect(result['queued'], true);
129 expect(f.rows.length, 1);
130 expect((await f.store.readQueue()).length, 1);
131 final reopened =
132 SchoolLifecycleSync(f.api, store: OfflineStore.forApi(f.api));
133 await reopened.flush();
134 expect(f.posts.length, 2);
135 expect(f.posts[1], f.posts[0]);
136 expect(f.rows.length, 1);
137 expect(await f.store.readQueue(), isEmpty);
138 expect((await reopened.read())['contexts'], hasLength(1));
139 f.api.close();
140 });
141 test(
142 'malformed or foreign-owner ACK does not erase pending intent or acknowledge a create',
143 () async {
144 for (final forged in [false, true]) {
145 final f = Fixture(
146 endpoint: 'https://${forged ? 'forged' : 'malformed'}.test/api')
147 ..malformedAck = !forged
148 ..forged = forged;
149 await expectLater(
150 f.sync.mutate(
151 'contexts', 'create', {'title': 'مدرسه', 'kind': 'student'}),
152 throwsA(
153 isA<ApiException>().having((e) => e.statusCode, 'status', 502)));
154 expect((await f.store.readQueue()).length, 1);
155 expect(await f.store.readLastAck(), isNull);
156 final id = (await f.store.readQueue()).single['entityId'] as String;
157 await expectLater(
158 f.sync.mutate(
159 'contexts', 'create', {'title': 'مدرسه', 'kind': 'student'},
160 entityId: id),
161 throwsA(
162 isA<ApiException>().having((e) => e.statusCode, 'status', 409)));
163 expect(f.posts.length, 1);
164 f.api.close();
165 }
166 });
167 test(
168 'conflict remains until explicit server choice journals the local intent',
169 () async {
170 final f = Fixture()..conflict = true;
171 f.rows[contextId] = entity(contextId, version: 2, title: 'نسخه سرور');
172 await expectLater(
173 f.sync.mutate('contexts', 'update', {'title': 'نسخه محلی'},
174 entityId: contextId, expectedVersion: 1),
175 throwsA(
176 isA<ApiException>().having((e) => e.statusCode, 'status', 409)));
177 expect((await f.store.readQueue()).single['queueStatus'], 'conflict');
178 await expectLater(f.sync.flush(), throwsA(isA<ApiException>()));
179 expect(f.posts.length, 1);
180 f.conflict = false;
181 await f.sync.useServer('contexts', contextId);
182 expect(await f.store.readQueue(), isEmpty);
183 expect(
184 (await f.store.readDiscardedChanges()).single['payload']['data']
185 ['title'],
186 'نسخه محلی');
187 expect((await f.sync.read())['contexts'].single['title'], 'نسخه سرور');
188 f.api.close();
189 });
190 test(
191 'account and endpoint changes cannot replay previous school intent or cache',
192 () async {
193 final f = Fixture()..offline = true;
194 await f.sync
195 .mutate('contexts', 'create', {'title': 'خصوصی', 'kind': 'student'});
196 final other = Fixture(user: secondOwner);
197 expect(await other.sync.pending(), isEmpty);
198 final endpoint = Fixture(endpoint: 'https://other-school.test/api');
199 expect(await endpoint.sync.pending(), isEmpty);
200 f.api.currentUserId = secondOwner;
201 await expectLater(
202 f.sync.flush(),
203 throwsA(
204 isA<ApiException>().having((e) => e.statusCode, 'status', 401)));
205 expect(f.posts, isEmpty);
206 f.api.close();
207 other.api.close();
208 endpoint.api.close();
209 });
210 test(
211 'offline school cache preserves server freshness and never declares cached data live',
212 () async {
213 final f = Fixture();
214 f.rows[contextId] = entity(contextId);
215 final online = await f.sync.read();
216 expect(online['offline'], false);
217 f.offline = true;
218 final stale = await f.sync.read();
219 expect(stale['offline'], true);
220 expect(stale['fetchedAt'], stamp);
221 expect(stale['contexts'], hasLength(1));
222 f.api.close();
223 });
224 test(
225 'invalid dates and owner-controlled fields never enter queue or reach API',
226 () async {
227 final f = Fixture();
228 for (final data in [
229 {
230 'title': 'year',
231 'startsOn': '2026-02-30',
232 'endsOn': '2027-01-01',
233 'lifeContextId': contextId
234 },
235 {
236 'title': 'year',
237 'startsOn': '2027-01-01',
238 'endsOn': '2026-01-01',
239 'lifeContextId': contextId
240 },
241 {
242 'title': 'year',
243 'startsOn': '2026-09-01',
244 'endsOn': '2027-01-01',
245 'lifeContextId': contextId,
246 'active': false
247 }
248 ]) {
249 expect(() => f.sync.mutate('years', 'create', data),
250 throwsA(isA<ApiException>()));
251 }
252 expect(await f.store.readQueue(), isEmpty);
253 expect(f.posts, isEmpty);
254 f.api.close();
255 });
256 }