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
| 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_quiz_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 | // SYNTHETIC reviewed-bank substitutes only. No real questions are published. |
| 17 | const _unit = '00000000-0000-4000-8000-000000000101'; |
| 18 | const _assessment = '00000000-0000-4000-8000-000000000102'; |
| 19 | const _mutation = '00000000-0000-4000-8000-000000000103'; |
| 20 | const _attempt = '00000000-0000-4000-8000-000000000104'; |
| 21 | |
| 22 | Map<String, dynamic> _body() => { |
| 23 | 'mutationId': _mutation, |
| 24 | 'assessmentId': _assessment, |
| 25 | 'assessmentVersion': 2, |
| 26 | 'answers': [ |
| 27 | {'questionId': 'q1', 'choiceId': 'a'} |
| 28 | ], |
| 29 | 'confidence': 'unsure', |
| 30 | }; |
| 31 | |
| 32 | Map<String, dynamic> _bank() => { |
| 33 | 'id': _assessment, |
| 34 | 'unitId': _unit, |
| 35 | 'version': 2, |
| 36 | 'questions': [ |
| 37 | { |
| 38 | 'id': 'q1', |
| 39 | 'objectiveId': 'objective-1', |
| 40 | 'promptFa': 'پرسش صرفاً آزمایشی', |
| 41 | 'choices': [ |
| 42 | {'id': 'a', 'textFa': 'گزینه آزمایشی الف'}, |
| 43 | {'id': 'b', 'textFa': 'گزینه آزمایشی ب'}, |
| 44 | ], |
| 45 | } |
| 46 | ], |
| 47 | }; |
| 48 | |
| 49 | class _Session implements SessionStore { |
| 50 | @override |
| 51 | Future<String?> read() async => null; |
| 52 | @override |
| 53 | Future<void> write(String value) async {} |
| 54 | @override |
| 55 | Future<void> clear() async {} |
| 56 | } |
| 57 | |
| 58 | class _Fixture { |
| 59 | _Fixture() { |
| 60 | api = HttpIdentityApi( |
| 61 | baseUrl: 'https://quiz.test', |
| 62 | client: MockClient(handle), |
| 63 | sessionStore: _Session(), |
| 64 | ) |
| 65 | ..accessToken = 'synthetic-token' |
| 66 | ..currentUserId = 'synthetic-learner-${next++}'; |
| 67 | store = OfflineStore.forNamespace(api.cacheNamespace!, |
| 68 | session: OfflineSession()); |
| 69 | sync = LearningQuizSync(api, store: store); |
| 70 | } |
| 71 | static int next = 0; |
| 72 | late final HttpIdentityApi api; |
| 73 | late final OfflineStore store; |
| 74 | late final LearningQuizSync sync; |
| 75 | bool offline = false, loseAcknowledgement = false, reviewed = true; |
| 76 | int? failure; |
| 77 | Future<void>? delay; |
| 78 | final posts = <Map<String, dynamic>>[]; |
| 79 | final applied = <String, Map<String, dynamic>>{}; |
| 80 | Map<String, dynamic> Function(Map<String, dynamic>)? alterAck; |
| 81 | |
| 82 | Future<http.Response> handle(http.Request request) async { |
| 83 | if (request.method == 'GET') { |
| 84 | return http.Response( |
| 85 | jsonEncode({ |
| 86 | 'assessment': reviewed ? _bank() : null, |
| 87 | if (!reviewed) 'reason': 'review_pending' |
| 88 | }), |
| 89 | 200, |
| 90 | headers: {'content-type': 'application/json; charset=utf-8'}); |
| 91 | } |
| 92 | expect(request.method, 'POST'); |
| 93 | expect(request.url.path, '/v1/me/learning-attempts'); |
| 94 | final body = Map<String, dynamic>.from(jsonDecode(request.body) as Map); |
| 95 | posts.add(body); |
| 96 | if (delay != null) await delay; |
| 97 | if (offline) throw http.ClientException('synthetic offline transport'); |
| 98 | if (failure != null) { |
| 99 | return http.Response( |
| 100 | jsonEncode({'error': 'synthetic_rejection'}), failure!); |
| 101 | } |
| 102 | final id = body['mutationId'] as String; |
| 103 | applied.putIfAbsent( |
| 104 | id, |
| 105 | () => { |
| 106 | 'mutationId': id, |
| 107 | 'attemptId': _attempt, |
| 108 | 'unitId': _unit, |
| 109 | 'assessmentId': _assessment, |
| 110 | 'assessmentVersion': 2, |
| 111 | 'correctCount': 1, |
| 112 | 'total': 1, |
| 113 | 'feedback': [ |
| 114 | { |
| 115 | 'questionId': 'q1', |
| 116 | 'objectiveId': 'objective-1', |
| 117 | 'correct': true, |
| 118 | 'explanationFa': 'توضیح صرفاً آزمایشی', |
| 119 | 'remediationFa': 'مرور صرفاً آزمایشی', |
| 120 | } |
| 121 | ], |
| 122 | 'resultLabel': 'answered_correctly', |
| 123 | 'nextReviewAt': '2026-10-12T10:00:00Z', |
| 124 | 'schedulePolicy': 'pilot-1-or-3-days', |
| 125 | 'source': 'quiz_answers', |
| 126 | 'acceptedAt': '2026-10-09T10:00:00Z', |
| 127 | }); |
| 128 | if (loseAcknowledgement) { |
| 129 | loseAcknowledgement = false; |
| 130 | throw http.ClientException('synthetic response lost after commit'); |
| 131 | } |
| 132 | final ack = Map<String, dynamic>.from(applied[id]!); |
| 133 | return http.Response(jsonEncode(alterAck?.call(ack) ?? ack), 201, |
| 134 | headers: {'content-type': 'application/json; charset=utf-8'}); |
| 135 | } |
| 136 | |
| 137 | LearningQuizSync reopen() => LearningQuizSync(api, |
| 138 | store: OfflineStore.forNamespace(store.scope, session: OfflineSession())); |
| 139 | } |
| 140 | |
| 141 | Matcher _error(String code) => |
| 142 | throwsA(isA<ApiException>().having((e) => e.code, 'code', code)); |
| 143 | |
| 144 | void main() { |
| 145 | TestWidgetsFlutterBinding.ensureInitialized(); |
| 146 | var blocked = false; |
| 147 | setUp(() { |
| 148 | blocked = false; |
| 149 | SharedPreferencesAsyncPlatform.instance = |
| 150 | InMemorySharedPreferencesAsync.withData({}); |
| 151 | String? token; |
| 152 | TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger |
| 153 | .setMockMethodCallHandler( |
| 154 | const MethodChannel('lifeguide/local_write_guard'), (call) async { |
| 155 | if (call.method == 'getBlocked') return blocked || token != null; |
| 156 | if (call.method == 'beginWrite') return token = 'synthetic-quiz-write'; |
| 157 | if (call.method == 'completeWrite' && call.arguments == token) { |
| 158 | token = null; |
| 159 | return true; |
| 160 | } |
| 161 | throw PlatformException(code: 'local_storage_restart_required'); |
| 162 | }); |
| 163 | }); |
| 164 | |
| 165 | test( |
| 166 | 'durable before POST, lost acknowledgement replays exact attempt after reopen', |
| 167 | () async { |
| 168 | final blockedFixture = _Fixture(); |
| 169 | blocked = true; |
| 170 | await expectLater( |
| 171 | blockedFixture.sync.submit(_body(), _unit), throwsA(anything)); |
| 172 | expect(blockedFixture.posts, isEmpty); |
| 173 | blocked = false; |
| 174 | final f = _Fixture(); |
| 175 | f.loseAcknowledgement = true; |
| 176 | expect((await f.sync.submit(_body(), _unit))['queued'], true); |
| 177 | final pending = (await f.store.readQueue()).single; |
| 178 | expect(pending['unitId'], _unit); |
| 179 | expect(pending['payload'], _body()); |
| 180 | expect(f.posts.single.containsKey('unitId'), false); |
| 181 | await f.reopen().flush(); |
| 182 | expect(f.posts, [_body(), _body()]); |
| 183 | expect(f.applied.length, 1); |
| 184 | expect(await f.store.readQueue(), isEmpty); |
| 185 | expect( |
| 186 | (await f.store.readList('learning_attempts')).single['id'], _attempt); |
| 187 | expect(await f.store.readList('learning_progress'), isEmpty); |
| 188 | expect(await f.store.readPlanner(), isEmpty); |
| 189 | }); |
| 190 | |
| 191 | test( |
| 192 | 'wrong acknowledgements retain answers; permanent rejection is recoverable', |
| 193 | () async { |
| 194 | for (final alter in <Map<String, dynamic> Function(Map<String, dynamic>)>[ |
| 195 | (ack) => ack..['assessmentVersion'] = 3, |
| 196 | (ack) => ack..['unitId'] = _assessment, |
| 197 | (ack) => ack..['source'] = 'timer', |
| 198 | (ack) => ack..['correctCount'] = 0, |
| 199 | (ack) => ack..['nextReviewAt'] = '2026-10-10T10:00:00Z', |
| 200 | (ack) => ack..['feedback'] = [], |
| 201 | ]) { |
| 202 | final f = _Fixture()..alterAck = alter; |
| 203 | await expectLater(f.sync.submit(_body(), _unit), |
| 204 | _error('invalid_sync_acknowledgement')); |
| 205 | expect((await f.store.readQueue()).single['payload'], _body()); |
| 206 | expect(await f.store.readList('learning_attempts'), isEmpty); |
| 207 | } |
| 208 | for (final status in [409, 400]) { |
| 209 | final f = _Fixture()..failure = status; |
| 210 | await expectLater( |
| 211 | f.sync.submit(_body(), _unit), _error('synthetic_rejection')); |
| 212 | expect((await f.store.readQueue()).single['queueStatus'], |
| 213 | status == 409 ? 'conflict' : 'rejected'); |
| 214 | await f.sync.cancelPending(_mutation); |
| 215 | expect(await f.store.readQueue(), isEmpty); |
| 216 | expect((await f.store.readDiscardedChanges()).single['payload'], _body()); |
| 217 | } |
| 218 | }); |
| 219 | |
| 220 | test('late response after account switch cannot acknowledge the old queue', |
| 221 | () async { |
| 222 | final f = _Fixture(); |
| 223 | final release = Completer<void>(); |
| 224 | f.delay = release.future; |
| 225 | final request = f.sync.submit(_body(), _unit); |
| 226 | final failed = expectLater(request, throwsA(isA<ApiException>())); |
| 227 | while (f.posts.isEmpty) { |
| 228 | await Future<void>.delayed(Duration.zero); |
| 229 | } |
| 230 | f.api.currentUserId = 'another-synthetic-account'; |
| 231 | release.complete(); |
| 232 | await failed; |
| 233 | expect((await f.store.readQueue()).single['payload'], _body()); |
| 234 | expect(await f.store.readList('learning_attempts'), isEmpty); |
| 235 | final other = OfflineStore.forNamespace(f.api.cacheNamespace!); |
| 236 | expect(await other.readQueue(), isEmpty); |
| 237 | await expectLater(f.reopen().flush(), _error('cache_scope_closed')); |
| 238 | expect(f.posts.length, 1); |
| 239 | }); |
| 240 | |
| 241 | testWidgets('no reviewed bank means no placeholder questions or submission', |
| 242 | (tester) async { |
| 243 | final f = _Fixture()..reviewed = false; |
| 244 | await tester.pumpWidget( |
| 245 | MaterialApp(home: LearningQuizPage(api: f.api, unitId: _unit))); |
| 246 | await tester.pumpAndSettle(); |
| 247 | expect(find.textContaining('در انتظار بازبینی'), findsOneWidget); |
| 248 | expect(find.byKey(const Key('quiz-submit')), findsNothing); |
| 249 | expect(find.text('پرسش صرفاً آزمایشی'), findsNothing); |
| 250 | expect(f.posts, isEmpty); |
| 251 | }); |
| 252 | |
| 253 | testWidgets( |
| 254 | 'explicit answers and confidence; reopen locks pending answers and retries', |
| 255 | (tester) async { |
| 256 | final f = _Fixture()..offline = true; |
| 257 | await tester.pumpWidget( |
| 258 | MaterialApp(home: LearningQuizPage(api: f.api, unitId: _unit))); |
| 259 | await tester.pumpAndSettle(); |
| 260 | FilledButton submit() => |
| 261 | tester.widget(find.byKey(const Key('quiz-submit'))); |
| 262 | expect(submit().onPressed, isNull); |
| 263 | await tester.tap(find.byKey(const Key('quiz-choice-q1-a'))); |
| 264 | await tester.pump(); |
| 265 | expect(submit().onPressed, isNull); |
| 266 | await tester.tap(find.byKey(const Key('quiz-confidence-unsure'))); |
| 267 | await tester.pump(); |
| 268 | expect(submit().onPressed, isNotNull); |
| 269 | await tester.ensureVisible(find.byKey(const Key('quiz-submit'))); |
| 270 | await tester.tap(find.byKey(const Key('quiz-submit'))); |
| 271 | await tester.pumpAndSettle(); |
| 272 | final sent = f.posts.single; |
| 273 | expect(sent.containsKey('unitId'), false); |
| 274 | expect(find.textContaining('روی این دستگاه'), findsOneWidget); |
| 275 | expect(find.textContaining('پاسخ درست'), findsNothing); |
| 276 | await tester.pumpWidget(const MaterialApp(home: SizedBox())); |
| 277 | await tester.pumpWidget( |
| 278 | MaterialApp(home: LearningQuizPage(api: f.api, unitId: _unit))); |
| 279 | await tester.pumpAndSettle(); |
| 280 | final choice = |
| 281 | tester.widget<ChoiceChip>(find.byKey(const Key('quiz-choice-q1-a'))); |
| 282 | expect(choice.selected, true); |
| 283 | expect(choice.onSelected, isNull); |
| 284 | f.offline = false; |
| 285 | await tester.ensureVisible(find.byKey(const Key('quiz-retry'))); |
| 286 | await tester.tap(find.byKey(const Key('quiz-retry'))); |
| 287 | await tester.pumpAndSettle(); |
| 288 | expect(f.posts, [sent, sent]); |
| 289 | expect(find.text('توضیح صرفاً آزمایشی'), findsOneWidget); |
| 290 | expect(find.text('مرور صرفاً آزمایشی'), findsOneWidget); |
| 291 | expect(find.textContaining('پیشنهاد آزمایشی'), findsOneWidget); |
| 292 | expect(await f.store.readQueue(), isEmpty); |
| 293 | expect(f.posts.every((p) => p.keys.length == 5), true); |
| 294 | }); |
| 295 | } |