LifeMate — Personal, Family & Learning Companion

fix/local-task-persistence
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 287 lines 11.4 KB
Raw
1 import 'package:flutter_test/flutter_test.dart';
2 import 'dart:convert';
3 import 'local_test_preferences.dart';
4 import 'package:lifemate/local_only_api.dart';
5 import 'package:lifemate/api.dart';
6 import 'package:lifemate/local_data_store.dart';
7 import 'package:shared_preferences/shared_preferences.dart';
8 import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.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 final class FailedWrites extends InMemorySharedPreferencesAsync {
13 FailedWrites(super.data) : super.withData();
14 @override
15 Future<bool> setString(
16 String key, String value, SharedPreferencesOptions options) async {
17 await super.setString(key, value, options);
18 throw StateError('Synthetic native cache publication then rename failure');
19 }
20 }
21
22 final class NativeWriteDuringRead extends InMemorySharedPreferencesAsync {
23 NativeWriteDuringRead(super.data, this.guard) : super.withData();
24 final MockNativeLocalWriteGuard guard;
25
26 @override
27 Future<String?> getString(
28 String key, SharedPreferencesOptions options) async {
29 final raw = await super.getString(key, options);
30 guard.beginWrite();
31 return raw;
32 }
33 }
34
35 class FailedNativeCommit extends InMemorySharedPreferencesStore {
36 FailedNativeCommit(super.data) : super.withData();
37 @override
38 Future<bool> setValue(String type, String key, Object value) async {
39 await super.setValue(type, key, value);
40 return false; // Android legacy commit can publish memory before disk fails.
41 }
42 }
43
44 void main() {
45 late LocalDataSession session;
46 setUp(() {
47 resetLocalPreferences();
48 session = LocalDataSession();
49 });
50
51 LocalOnlyApi open() => LocalOnlyApi(
52 displayName: 'آرام',
53 category: 'girl_minor',
54 store: LocalDataStore(
55 category: 'girl_minor', displayName: 'آرام', session: session));
56
57 test('assignment survives recreation, update and safe archive', () async {
58 final created = await open().createPlanItem({
59 'kind': 'assignment',
60 'title': 'تمرین ریاضی',
61 'dueAt': DateTime.now().toUtc().toIso8601String(),
62 'visibility': 'private',
63 });
64 final reopened = open();
65 final records = await reopened.listPlanItems();
66 expect(records, hasLength(1));
67 expect(records.single['id'], created['id']);
68 expect(records.single['title'], 'تمرین ریاضی');
69 await reopened
70 .updatePlanItem(created['id'].toString(), {'title': 'تمرین علوم'});
71 expect((await open().listPlanItems()).single['title'], 'تمرین علوم');
72 await open()
73 .updatePlanItem(created['id'].toString(), {'status': 'cancelled'});
74 expect(await open().listPlanItems(), isEmpty);
75 });
76
77 test('edited profile is restored by a new API', () async {
78 await open()
79 .updateProfile(displayName: 'سارا', themePreference: 'boy_blue');
80 final restored = await open().getProfile();
81 expect(restored['display_name'], 'سارا');
82 expect(restored['theme_preference'], 'boy_blue');
83 });
84
85 test('concurrent writers retain every item with unique identifiers',
86 () async {
87 final records = await Future.wait(List.generate(
88 20,
89 (i) => open().createPlanItem({
90 'kind': 'task',
91 'title': 'کار $i',
92 })));
93 expect(records.map((item) => item['id']).toSet(), hasLength(20));
94 expect(await open().listPlanItems(), hasLength(20));
95 });
96
97 test('invalid changes do not replace persisted records', () async {
98 final item =
99 await open().createPlanItem({'kind': 'assignment', 'title': 'علوم'});
100 for (final change in <Map<String, dynamic>>[
101 {'title': ' '},
102 {'status': 'wrong'},
103 {'visibility': 'family'},
104 {'dueAt': 'not-a-date'},
105 {'id': 'spoofed'},
106 ]) {
107 await expectLater(open().updatePlanItem(item['id'] as String, change),
108 throwsA(isA<ApiException>()));
109 }
110 expect((await open().listPlanItems()).single['title'], 'علوم');
111 await expectLater(open().updatePlanItem('missing', {'title': 'x'}),
112 throwsA(isA<ApiException>()));
113 await expectLater(
114 open().updateProfile(displayName: ' '), throwsA(isA<ApiException>()));
115 });
116
117 test('date window includes due boundary and excludes upper boundary',
118 () async {
119 final from = DateTime.utc(2026, 10, 8);
120 final to = from.add(const Duration(days: 1));
121 await open().createPlanItem({
122 'kind': 'assignment',
123 'title': 'داخل',
124 'dueAt': from.toIso8601String()
125 });
126 await open().createPlanItem(
127 {'kind': 'task', 'title': 'بعد', 'dueAt': to.toIso8601String()});
128 final result = await open().getToday(from: from, to: to);
129 expect(result.map((item) => item['title']), ['داخل']);
130 await open()
131 .updatePlanItem(result.single['id'] as String, {'status': 'completed'});
132 expect(await open().getToday(from: from, to: to), isEmpty);
133 });
134
135 test('today uses start time when a deadline is on another day', () async {
136 final from = DateTime.utc(2026, 10, 8);
137 await open().createPlanItem({
138 'kind': 'assignment',
139 'title': 'امروز',
140 'startsAt': from.add(const Duration(hours: 10)).toIso8601String(),
141 'dueAt': from.add(const Duration(days: 1)).toIso8601String(),
142 });
143 expect(
144 await open()
145 .getToday(from: from, to: from.add(const Duration(days: 1))),
146 hasLength(1));
147 });
148
149 test('numeric dates are rejected instead of coerced into strings', () async {
150 await expectLater(
151 open().createPlanItem({
152 'kind': 'task',
153 'title': 'زمان نامعتبر',
154 'dueAt': 20261008,
155 }),
156 throwsA(isA<ApiException>()));
157 });
158
159 test('valid JSON with corrupt fields cannot be read or overwritten',
160 () async {
161 await open().createPlanItem({'kind': 'task', 'title': 'اول'});
162 final original = await open().store.read();
163 for (final corrupt in <Map<String, dynamic>>[
164 {'notes': <String, dynamic>{}},
165 {'priority': 'wrong'},
166 {'due_at': 20261008},
167 {'starts_at': '2026-10-09T10:00:00Z', 'due_at': '2026-10-08T10:00:00Z'},
168 ]) {
169 final data = jsonDecode(jsonEncode(original)) as Map<String, dynamic>;
170 (data['items'] as List).first.addAll(corrupt);
171 final raw = jsonEncode(data);
172 resetLocalPreferences({LocalDataStore.key: raw});
173 await expectLater(
174 open().listPlanItems(),
175 throwsA(isA<ApiException>()
176 .having((e) => e.code, 'code', 'local_data_corrupt')));
177 await expectLater(open().updateProfile(displayName: 'دوم'),
178 throwsA(isA<ApiException>()));
179 expect(await SharedPreferencesAsync().getString(LocalDataStore.key), raw);
180 }
181 });
182
183 test('corrupt data raises error and is never overwritten', () async {
184 const bad = '{invalid';
185 resetLocalPreferences({LocalDataStore.key: bad});
186 await expectLater(
187 open().listPlanItems(),
188 throwsA(isA<ApiException>()
189 .having((e) => e.code, 'code', 'local_data_corrupt')));
190 await expectLater(open().createPlanItem({'kind': 'task', 'title': 'new'}),
191 throwsA(isA<ApiException>()));
192 expect(await SharedPreferencesAsync().getString(LocalDataStore.key), bad);
193 });
194
195 test('failed native write requires restart and blocks further operations',
196 () async {
197 final item = await open().createPlanItem({'kind': 'task', 'title': 'اول'});
198 final raw = (await SharedPreferencesAsync().getString(LocalDataStore.key))!;
199 SharedPreferencesAsyncPlatform.instance =
200 FailedWrites({LocalDataStore.key: raw});
201 await expectLater(
202 open().updatePlanItem(item['id'] as String, {'title': 'دوم'}),
203 throwsA(isA<ApiException>()
204 .having((e) => e.code, 'code', 'local_storage_restart_required')));
205 await expectLater(
206 open().listPlanItems(),
207 throwsA(isA<ApiException>()
208 .having((e) => e.code, 'code', 'local_storage_restart_required')));
209 final uncertain = jsonDecode(
210 (await SharedPreferencesAsync().getString(LocalDataStore.key))!) as Map;
211 expect((uncertain['items'] as List).first['title'], 'دوم');
212 // Flutter engine recreation replaces Dart state, but retains native caches.
213 session = LocalDataSession();
214 await expectLater(
215 open().listPlanItems(),
216 throwsA(isA<ApiException>()
217 .having((e) => e.code, 'code', 'local_storage_restart_required')));
218 await expectLater(
219 open().updatePlanItem(item['id'] as String, {'title': 'سوم'}),
220 throwsA(isA<ApiException>()
221 .having((e) => e.code, 'code', 'local_storage_restart_required')));
222 resetLocalPreferences({
223 LocalDataStore.key: raw
224 }); // simulate native process restart + disk read
225 await expectLater(open().listPlanItems(), throwsA(isA<ApiException>()));
226 session = LocalDataSession();
227 expect((await open().listPlanItems()).single['title'], 'اول');
228 });
229
230 test('reads never trust legacy memory published by a failed commit',
231 () async {
232 await open().createPlanItem({'kind': 'task', 'title': 'اول'});
233 final original = await open().store.read();
234 final raw = jsonEncode(original);
235 SharedPreferencesAsyncPlatform.instance =
236 InMemorySharedPreferencesAsync.withData({LocalDataStore.key: raw});
237 SharedPreferencesStorePlatform.instance =
238 FailedNativeCommit({'flutter.${LocalDataStore.key}': raw});
239 (original['items'] as List).first['title'] = 'ذخیره ناموفق';
240 final prefs = await SharedPreferences.getInstance();
241 expect(await prefs.setString(LocalDataStore.key, jsonEncode(original)),
242 isFalse);
243 expect((await open().listPlanItems()).single['title'], 'اول');
244 });
245
246 test('a native write beginning during a read blocks the returned snapshot',
247 () async {
248 await open().createPlanItem({'kind': 'task', 'title': 'ثبت‌شده'});
249 final raw = (await SharedPreferencesAsync().getString(LocalDataStore.key))!;
250 final guard = resetNativeLocalWriteGuard();
251 SharedPreferencesAsyncPlatform.instance =
252 NativeWriteDuringRead({LocalDataStore.key: raw}, guard);
253 await expectLater(
254 open().listPlanItems(),
255 throwsA(isA<ApiException>()
256 .having((e) => e.code, 'code', 'local_storage_restart_required')));
257 });
258
259 test('oversized mutation does not start a native write or replace saved data',
260 () async {
261 final item = await open().createPlanItem({'kind': 'task', 'title': 'اول'});
262 final guard = resetNativeLocalWriteGuard();
263 await expectLater(
264 open().store.mutate((data) {
265 data['items'] = List.generate(
266 200,
267 (index) => {
268 ...item,
269 'id': 'synthetic-capacity-item-$index',
270 'notes': 'x' * 6000,
271 });
272 }),
273 throwsA(isA<ApiException>()
274 .having((e) => e.code, 'code', 'local_storage_failed')));
275 expect(guard.blocked, isFalse);
276 expect((await open().listPlanItems()).single['title'], 'اول');
277 });
278
279 test('unimplemented server features cannot fabricate success', () async {
280 expect(open().accessToken, isNull);
281 expect(
282 () => open().createAiSession('study'),
283 throwsA(isA<ApiException>()
284 .having((e) => e.code, 'code', 'local_feature_unavailable')));
285 expect(() => open().createFamily('خانواده'), throwsA(isA<ApiException>()));
286 });
287 }