LifeMate — Personal, Family & Learning Companion

test/personal-recovery-acceptance
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 201 lines 7.65 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/planner_series.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 seriesId = '20000000-0000-4000-8000-000000000001';
14 const payload = <String, dynamic>{
15 'title': 'برنامه ساختگی مدرسه',
16 'kind': 'event',
17 'timezone': 'Asia/Tehran',
18 'startsOn': '2026-10-18',
19 'frequency': 'weekly',
20 'intervalDays': 1,
21 'slots': [
22 {'weekday': 6, 'start': '08:00', 'end': '12:00'}
23 ],
24 'reminderMinutes': [5]
25 };
26
27 class Fixture {
28 Fixture() {
29 api = HttpIdentityApi(
30 baseUrl: 'https://weekly.test/api', client: MockClient(handle))
31 ..accessToken = 'synthetic-token'
32 ..currentUserId = owner;
33 store = OfflineStore.forNamespace(api.cacheNamespace!,
34 session: OfflineSession());
35 }
36 late final HttpIdentityApi api;
37 late final OfflineStore store;
38 bool offline = false, loseReceipt = false, badOwner = false;
39 int? status;
40 int commits = 0;
41 final requests = <String>[];
42 final rows = <String, Map<String, dynamic>>{};
43 PlannerSeriesSync reopen() => PlannerSeriesSync(api,
44 store: OfflineStore.forNamespace(store.scope, session: OfflineSession()));
45 Future<http.Response> handle(http.Request request) async {
46 requests.add(request.body);
47 if (offline) throw http.ClientException('synthetic offline');
48 if (status != null) {
49 return http.Response('{"error":"synthetic_rejection"}', status!);
50 }
51 final body = jsonDecode(request.body) as Map<String, dynamic>;
52 expect((await store.readQueue()).single['payload'], body);
53 final id = body['id'] as String;
54 rows.putIfAbsent(id, () {
55 commits++;
56 return {
57 'id': id,
58 'owner_user_id': owner,
59 'version': 1,
60 'title': body['title'],
61 };
62 });
63 if (loseReceipt) {
64 loseReceipt = false;
65 throw http.ClientException('synthetic lost receipt');
66 }
67 return http.Response(
68 jsonEncode({
69 'series': {
70 ...rows[id]!,
71 if (badOwner) 'owner_user_id': 'other-owner'
72 },
73 'items': [
74 {
75 'id': '30000000-0000-4000-8000-000000000001',
76 'series_id': id,
77 'owner_user_id': owner,
78 'title': body['title'],
79 'version': 1,
80 'status': 'planned'
81 }
82 ]
83 }),
84 200,
85 headers: {'content-type': 'application/json; charset=utf-8'});
86 }
87 }
88
89 void main() {
90 TestWidgetsFlutterBinding.ensureInitialized();
91 setUp(() {
92 SharedPreferencesAsyncPlatform.instance =
93 InMemorySharedPreferencesAsync.withData({});
94 String? token;
95 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
96 .setMockMethodCallHandler(
97 const MethodChannel('lifeguide/local_write_guard'), (call) async {
98 if (call.method == 'getBlocked') return token != null;
99 if (call.method == 'beginWrite') return token = 'synthetic-series-write';
100 if (call.method == 'completeWrite' && call.arguments == token) {
101 token = null;
102 return true;
103 }
104 throw PlatformException(code: 'local_storage_restart_required');
105 });
106 });
107 test('offline durable draft reopens and synchronizes exact ID once',
108 () async {
109 final f = Fixture()..offline = true;
110 expect((await f.reopen().create(payload, id: seriesId)).queued, true);
111 expect((await f.store.readQueue()).single['entityId'], seriesId);
112 expect(await f.store.readPlanner(), isEmpty);
113 f.offline = false;
114 await f.reopen().flush();
115 expect(f.commits, 1);
116 expect(await f.store.readQueue(), isEmpty);
117 expect((await f.store.readPlanner()).single['series_id'], seriesId);
118 expect((await f.store.readList('planner_series')).single['id'], seriesId);
119 expect(f.requests.first, f.requests.last);
120 });
121 test('response lost after commit retries same UUID without duplicate',
122 () async {
123 final f = Fixture()..loseReceipt = true;
124 expect((await f.reopen().create(payload, id: seriesId)).queued, true);
125 expect((await f.reopen().create(payload, id: seriesId)).queued, false);
126 expect(f.commits, 1);
127 expect(f.requests.toSet().length, 1);
128 });
129 test('terminal 400 is retained and retry never reports queued success',
130 () async {
131 final f = Fixture()..status = 400;
132 await expectLater(
133 f.reopen().create(payload, id: seriesId), throwsA(isA<ApiException>()));
134 expect((await f.store.readQueue()).single['queueStatus'], 'rejected');
135 f.status = null;
136 await expectLater(
137 f.reopen().create(payload, id: seriesId),
138 throwsA(
139 isA<ApiException>().having((e) => e.statusCode, 'status', 422)));
140 expect(f.requests.length, 1);
141 });
142 test('ambiguous server error keeps exact frozen request for retry', () async {
143 final f = Fixture()..status = 500;
144 await expectLater(
145 f.reopen().create(payload, id: seriesId), throwsA(isA<ApiException>()));
146 expect((await f.store.readQueue()).single['queueStatus'], 'queued');
147 await expectLater(
148 f.reopen().create({...payload, 'title': 'changed'}, id: seriesId),
149 throwsA(isA<ApiException>()
150 .having((e) => e.code, 'code', 'mutation_id_reused')));
151 f.status = null;
152 expect((await f.reopen().create(payload, id: seriesId)).queued, false);
153 expect(f.requests.toSet().length, 1);
154 });
155 test('foreign owner acknowledgement cannot remove private draft', () async {
156 final f = Fixture()..badOwner = true;
157 await expectLater(
158 f.reopen().create(payload, id: seriesId),
159 throwsA(isA<ApiException>()
160 .having((e) => e.code, 'code', 'invalid_series_acknowledgement')));
161 expect((await f.store.readQueue()).length, 1);
162 expect(await f.store.readPlanner(), isEmpty);
163 });
164 test('old service cannot send after identity changes', () async {
165 final f = Fixture();
166 final sync = f.reopen();
167 f.api.currentUserId = 'other-synthetic-user';
168 await expectLater(
169 sync.create(payload, id: seriesId), throwsA(isA<ApiException>()));
170 expect(f.requests, isEmpty);
171 });
172 test('rejected draft does not block other sync and keeps recoverable journal',
173 () async {
174 final f = Fixture()..status = 400;
175 await expectLater(
176 f.reopen().create(payload, id: seriesId), throwsA(isA<ApiException>()));
177 f.status = null;
178 await f.reopen().flush();
179 expect(f.requests.length, 1);
180 await f.store.discardEntityChanges(seriesId,
181 entityType: 'planner_series', cacheKey: 'planner_series');
182 expect(await f.store.readQueue(), isEmpty);
183 expect((await f.store.readDiscardedChanges()).single['entityType'],
184 'planner_series');
185 });
186 test('acknowledged UUID cannot silently accept edited payload', () async {
187 final f = Fixture();
188 await f.reopen().create(payload, id: seriesId);
189 await expectLater(
190 f.reopen().create({...payload, 'title': 'changed'}, id: seriesId),
191 throwsA(isA<ApiException>()
192 .having((e) => e.code, 'code', 'mutation_id_reused')));
193 expect(f.requests.length, 1);
194 });
195 test('Saturday week and dates retain selected calendar day', () {
196 final days = plannerWeekDays(DateTime(2026, 10, 18));
197 expect(days.first.weekday, DateTime.saturday);
198 expect(plannerDate(days.first), '2026-10-17');
199 expect(days.last.weekday, DateTime.friday);
200 });
201 }