LifeMate — Personal, Family & Learning Companion
test: exercise native Android reminders in an isolated emulator
Quinn White committed
Oct 19, 2026 at 02:59 UTC
7fb737d044d61b61b6b3d7bba3eba47859710ba5
7 files changed
+1237
.github/workflows/android-reminder-acceptance.yml
new
+63
@@ -0,0 +1,63 @@
1
+name: LifeGuide Android reminder acceptance (synthetic emulator only)
2
+on:
3
+ pull_request:
4
+ paths:
5
+ - '.github/workflows/android-reminder-acceptance.yml'
6
+ - 'apps/lifemate/tool/*native_reminder*'
7
+ - 'apps/lifemate/test/native_reminder_fixture_test.dart'
8
+ - 'apps/lifemate/lib/local_reminders.dart'
9
+ - 'apps/lifemate/android/**'
10
+ workflow_dispatch:
11
+permissions:
12
+ contents: read
13
+concurrency:
14
+ group: lifeguide-native-reminders-${{ github.ref }}
15
+ cancel-in-progress: true
16
+jobs:
17
+ synthetic-emulator:
18
+ runs-on: ubuntu-latest
19
+ timeout-minutes: 30
20
+ defaults:
21
+ run:
22
+ working-directory: apps/lifemate
23
+ steps:
24
+ - uses: actions/checkout@v4
25
+ - uses: actions/setup-java@v4
26
+ with: {distribution: temurin, java-version: '17'}
27
+ - uses: subosito/flutter-action@v2
28
+ with: {flutter-version: '3.47.6', channel: stable, cache: true}
29
+ - run: flutter pub get
30
+ - name: Check test-tool safety boundaries
31
+ run: |
32
+ python3 -m unittest discover -s tool -p 'test_native_reminders_android_test.py' -v
33
+ dart format --output=none --set-exit-if-changed tool/native_reminder_fixture.dart test/native_reminder_fixture_test.dart
34
+ flutter test test/native_reminder_fixture_test.dart
35
+ - name: Build isolated emulator fixture (never distributed)
36
+ run: flutter build apk --debug --target=tool/native_reminder_fixture.dart --dart-define=LG_NATIVE_REMINDER_FIXTURE=true
37
+ - name: Enable KVM for disposable emulator
38
+ run: |
39
+ test -c /dev/kvm
40
+ echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
41
+ sudo udevadm control --reload-rules
42
+ sudo udevadm trigger --name-match=kvm
43
+ - name: Exercise actual AlarmManager and NotificationManager
44
+ # Pinned v2 commit; no app/server credentials or external test data.
45
+ uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d
46
+ with:
47
+ api-level: 35
48
+ target: google_apis
49
+ arch: x86_64
50
+ profile: pixel_6
51
+ emulator-port: 5554
52
+ avd-name: lifeguide-synthetic-reminders
53
+ force-avd-creation: true
54
+ emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -wipe-data -noaudio -no-boot-anim -camera-back none
55
+ working-directory: apps/lifemate
56
+ script: python3 tool/test_native_reminders_android.py --serial emulator-5554 --apk build/app/outputs/flutter-apk/app-debug.apk --allow-synthetic-emulator-reset --output exports/native-reminders-android.json
57
+ - name: Upload sanitized receipt only (no fixture APK or raw device dumps)
58
+ if: always()
59
+ uses: actions/upload-artifact@v4
60
+ with:
61
+ name: LifeGuide-synthetic-emulator-reminder-receipt
62
+ path: apps/lifemate/exports/native-reminders-android.json
63
+ if-no-files-found: warn
apps/lifemate/test/native_reminder_fixture_test.dart
new
+113
@@ -0,0 +1,113 @@
1
+import 'package:flutter/foundation.dart';
2
+import 'package:flutter/services.dart';
3
+import 'package:flutter_test/flutter_test.dart';
4
+import '../tool/native_reminder_fixture.dart' as fixture;
5
+
6
+void main() {
7
+ TestWidgetsFlutterBinding.ensureInitialized();
8
+ const channel = MethodChannel('lifeguide/local_reminders');
9
+ final calls = <MethodCall>[];
10
+ final now = DateTime.utc(2026, 10, 19, 8);
11
+ setUp(() {
12
+ debugDefaultTargetPlatformOverride = TargetPlatform.android;
13
+ calls.clear();
14
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
15
+ .setMockMethodCallHandler(channel, (call) async {
16
+ calls.add(call);
17
+ if (call.method == 'status') {
18
+ return {
19
+ 'supported': true,
20
+ 'permissionGranted': true,
21
+ 'active': true,
22
+ 'activeScope': fixture.scope,
23
+ 'scheduledCount': 1,
24
+ 'timing': 'exact',
25
+ 'canScheduleExactAlarms': true
26
+ };
27
+ }
28
+ return true;
29
+ });
30
+ });
31
+ tearDown(() {
32
+ debugDefaultTargetPlatformOverride = null;
33
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
34
+ .setMockMethodCallHandler(channel, null);
35
+ });
36
+ test('disabled and non-Android fixtures never reach native storage',
37
+ () async {
38
+ for (final flags in [
39
+ (false, true, true),
40
+ (true, false, true),
41
+ (true, true, false)
42
+ ]) {
43
+ await expectLater(
44
+ fixture.runFixture('/schedule?nonce=0123456789abcdef&delay=45',
45
+ enabled: flags.$1,
46
+ debug: flags.$2,
47
+ android: flags.$3,
48
+ now: () => now),
49
+ throwsStateError);
50
+ expect(calls, isEmpty);
51
+ }
52
+ });
53
+ test('unknown commands and malformed metadata fail before channel access',
54
+ () async {
55
+ for (final route in [
56
+ '/',
57
+ '/other?nonce=01234567',
58
+ '/schedule?nonce=bad&delay=45',
59
+ '/schedule?nonce=01234567&delay=0',
60
+ '/schedule?nonce=01234567&delay=999',
61
+ '/inspect?nonce=01234567&owner=private',
62
+ '/inspect?nonce=01234567&nonce=abcdef01',
63
+ 'https://example.invalid/inspect?nonce=01234567'
64
+ ]) {
65
+ await expectLater(
66
+ fixture.runFixture(route,
67
+ enabled: true, debug: true, android: true, now: () => now),
68
+ throwsArgumentError);
69
+ expect(calls, isEmpty);
70
+ }
71
+ });
72
+ test('schedule uses production port with only synthetic opaque metadata',
73
+ () async {
74
+ final result = await fixture.runFixture(
75
+ '/schedule?nonce=0123456789abcdef&delay=45',
76
+ enabled: true,
77
+ debug: true,
78
+ android: true,
79
+ now: () => now);
80
+ expect(calls.map((c) => c.method),
81
+ ['status', 'deactivate', 'activate', 'replace', 'status']);
82
+ final payload =
83
+ calls.singleWhere((c) => c.method == 'replace').arguments as Map;
84
+ expect(payload['scope'], fixture.scope);
85
+ expect(payload['reminders'], [
86
+ {
87
+ 'id': fixture.reminder,
88
+ 'planItemId': fixture.plan,
89
+ 'scheduledAtEpochMs':
90
+ now.add(const Duration(seconds: 45)).millisecondsSinceEpoch,
91
+ 'companionName': fixture.companion
92
+ }
93
+ ]);
94
+ expect(result['simulatedServerAcknowledgement'], isTrue);
95
+ expect(result['mode'], 'schedule');
96
+ expect(result.toString(), isNot(contains('SYNTHETIC_PRIVATE_TASK_CANARY')));
97
+ });
98
+ test('inspect after restart reads without resetting persisted generation',
99
+ () async {
100
+ await fixture.runFixture('/inspect?nonce=0123456789abcdef',
101
+ enabled: true, debug: true, android: true, now: () => now);
102
+ expect(calls.map((c) => c.method), ['status']);
103
+ });
104
+ test('suppression and off do not reactivate a previous fixture', () async {
105
+ await fixture.runFixture('/suppress?nonce=0123456789abcdef',
106
+ enabled: true, debug: true, android: true, now: () => now);
107
+ expect(calls.map((c) => c.method), ['suppressPlanItems', 'status']);
108
+ calls.clear();
109
+ await fixture.runFixture('/off?nonce=0123456789abcdef',
110
+ enabled: true, debug: true, android: true, now: () => now);
111
+ expect(calls.map((c) => c.method), ['deactivate', 'status']);
112
+ });
113
+}
apps/lifemate/tool/native_reminder_fixture.dart
new
+117
@@ -0,0 +1,117 @@
1
+// Emulator-only test entry point. Never import from lib/ or distribute its APK.
2
+// No API, credentials, identity or real server acknowledgement is involved.
3
+import 'dart:convert';
4
+import 'package:flutter/foundation.dart';
5
+import 'package:flutter/material.dart';
6
+import 'package:lifemate/local_reminders.dart';
7
+
8
+const owner = '11111111-1111-4111-8111-111111111111';
9
+const plan = '22222222-2222-4222-8222-222222222222';
10
+const reminder = '33333333-3333-4333-8333-333333333333';
11
+const scope = 'emulator-fixture-v1|$owner';
12
+const companion = 'LifeGuide EMULATOR FIXTURE';
13
+
14
+/// The host additionally refuses physical devices and preinstalled packages.
15
+/// Flags are injectable only to test this tool's fail-closed boundary.
16
+Future<Map<String, Object?>> runFixture(String route,
17
+ {required bool enabled,
18
+ required bool debug,
19
+ required bool android,
20
+ DateTime Function()? now}) async {
21
+ if (!enabled || !debug || !android) {
22
+ throw StateError('fixture_disabled');
23
+ }
24
+ final uri = Uri.tryParse(route);
25
+ const modes = {'/schedule', '/inspect', '/suppress', '/off'};
26
+ if (uri == null ||
27
+ uri.hasScheme ||
28
+ uri.hasAuthority ||
29
+ uri.hasFragment ||
30
+ !modes.contains(uri.path) ||
31
+ uri.queryParametersAll.entries.any((e) =>
32
+ e.value.length != 1 ||
33
+ !(e.key == 'nonce' ||
34
+ (uri.path == '/schedule' && e.key == 'delay')))) {
35
+ throw ArgumentError('invalid_fixture_route');
36
+ }
37
+ final nonce = uri.queryParameters['nonce'] ?? '';
38
+ final delay = int.tryParse(uri.queryParameters['delay'] ?? '45');
39
+ if (!RegExp(r'^[0-9a-f]{8,32}$').hasMatch(nonce) ||
40
+ delay == null ||
41
+ delay < 30 ||
42
+ delay > 90) {
43
+ throw ArgumentError('invalid_fixture_metadata');
44
+ }
45
+ final clock = now ?? DateTime.now;
46
+ final port = AndroidLocalReminderPort(now: clock);
47
+ DateTime? at;
48
+ switch (uri.path) {
49
+ case '/schedule':
50
+ final before = await port.status();
51
+ if (!before.supported || !before.permissionGranted) {
52
+ throw StateError('fixture_permission_not_granted');
53
+ }
54
+ await port.deactivate();
55
+ final utc = clock().toUtc();
56
+ at = utc.add(Duration(seconds: delay));
57
+ await port.activate(scope,
58
+ validUntil: utc.add(const Duration(minutes: 10)));
59
+ await port.replace(
60
+ scope,
61
+ [
62
+ LocalReminder(
63
+ id: reminder,
64
+ planItemId: plan,
65
+ scheduledAt: at,
66
+ companionName: companion,
67
+ ownerUserId: owner,
68
+ serverAcknowledged: true)
69
+ ],
70
+ currentUserId: owner);
71
+ case '/suppress':
72
+ await port.suppressPlanItems(scope, {plan});
73
+ case '/off':
74
+ await port.deactivate();
75
+ case '/inspect':
76
+ break; // Intentionally no activate: preserve the stored generation.
77
+ }
78
+ final status = await port.status();
79
+ return {
80
+ 'nonce': nonce,
81
+ 'mode': uri.path.substring(1),
82
+ 'simulatedServerAcknowledgement': true,
83
+ if (at != null) 'scheduledAtEpochMs': at.millisecondsSinceEpoch,
84
+ 'status': {
85
+ 'supported': status.supported,
86
+ 'permissionGranted': status.permissionGranted,
87
+ 'active': status.active,
88
+ 'activeScope': status.activeScope,
89
+ 'scheduledCount': status.scheduledCount,
90
+ 'timing': status.timing,
91
+ 'canScheduleExactAlarms': status.canScheduleExactAlarms
92
+ }
93
+ };
94
+}
95
+
96
+Future<void> main() async {
97
+ final binding = WidgetsFlutterBinding.ensureInitialized();
98
+ final route = binding.platformDispatcher.defaultRouteName;
99
+ const enabled = bool.fromEnvironment('LG_NATIVE_REMINDER_FIXTURE');
100
+ final android = !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
101
+ const label = 'EMULATOR ONLY — SYNTHETIC DATA — NOT THE APPLICATION';
102
+ runApp(const MaterialApp(
103
+ initialRoute: '/',
104
+ home: Scaffold(
105
+ body: SafeArea(
106
+ child: Padding(
107
+ padding: EdgeInsets.all(24),
108
+ child: Text('$label\nSYNTHETIC_PRIVATE_TASK_CANARY'))))));
109
+ try {
110
+ final result = await runFixture(route,
111
+ enabled: enabled, debug: kDebugMode, android: android);
112
+ debugPrint('LG_NATIVE_REMINDER_FIXTURE ${jsonEncode(result)}');
113
+ } catch (_) {
114
+ // Never dump native exceptions, routes or arbitrary storage into logs.
115
+ debugPrint('LG_NATIVE_REMINDER_FIXTURE_ERROR fixture_failed_closed');
116
+ }
117
+}
apps/lifemate/tool/test_native_reminders_android.py
new
+458
@@ -0,0 +1,458 @@
1
+#!/usr/bin/env python3
2
+"""Run synthetic native reminder acceptance on a fresh API 35 Android emulator.
3
+
4
+Build only the debug tool/native_reminder_fixture.dart entry point with
5
+--dart-define=LG_NATIVE_REMINDER_FIXTURE=true. Never distribute that APK.
6
+This runner never selects a device implicitly or removes an existing install.
7
+Only sanitized assertions are written; adb output stays in memory.
8
+"""
9
+import argparse
10
+import json
11
+import re
12
+import secrets
13
+import shlex
14
+import subprocess
15
+import time
16
+import uuid
17
+import xml.etree.ElementTree as ET
18
+from pathlib import Path
19
+
20
+import check_apk_manifest
21
+
22
+PACKAGE = "ir.lifeguide.app"
23
+SCOPE = "emulator-fixture-v1|11111111-1111-4111-8111-111111111111"
24
+PLAN = "22222222-2222-4222-8222-222222222222"
25
+REMINDER = "33333333-3333-4333-8333-333333333333"
26
+COMPANION = "LifeGuide EMULATOR FIXTURE"
27
+GENERIC_BODY = "برای دیدن برنامهٔ شخصی، لایفگاید را باز کنید."
28
+CHANNEL = "lifeguide_personal_plan_v1"
29
+MARKER = "LG_NATIVE_REMINDER_FIXTURE "
30
+CANARY = "SYNTHETIC_PRIVATE_TASK_CANARY"
31
+PREFERENCES = "shared_prefs/lifeguide_local_reminders_v1.xml"
32
+# A missing process makes pidof exit 1. Preserve transport/remote failures, and
33
+# require the explicit ABSENT token rather than interpreting empty output.
34
+PID_QUERY = ("pids=$(pidof " + PACKAGE + "); code=$?; "
35
+ "if [ \"$code\" -eq 0 ] && [ -n \"$pids\" ]; then printf PRESENT; "
36
+ "elif [ \"$code\" -eq 1 ] && [ -z \"$pids\" ]; then printf ABSENT; "
37
+ "else exit 2; fi")
38
+MODES = {"schedule", "inspect", "suppress", "off"}
39
+LIMITATIONS = {
40
+ name: "UNVERIFIED" for name in (
41
+ "physicalDevice", "reboot", "Doze", "soundOrVibration",
42
+ "permissionConsentUI", "realServerAcknowledgement", "signedRelease",
43
+ )
44
+}
45
+
46
+
47
+class AcceptanceError(Exception):
48
+ """An intentionally sanitized error code; never wrap raw device output."""
49
+
50
+
51
+def require(condition, code):
52
+ if not condition:
53
+ raise AcceptanceError(code)
54
+
55
+
56
+def validate_serial(serial):
57
+ require(isinstance(serial, str) and
58
+ re.fullmatch(r"emulator-[0-9]{4,5}", serial) is not None,
59
+ "explicit_emulator_serial_required")
60
+ port = int(serial.split("-")[1])
61
+ require(1024 <= port <= 65534 and port % 2 == 0,
62
+ "invalid_emulator_console_port")
63
+
64
+
65
+class Adb:
66
+ def __init__(self, serial):
67
+ validate_serial(serial)
68
+ self.serial = serial
69
+
70
+ def command(self, *parts, allow_failure=False):
71
+ try:
72
+ result = subprocess.run(
73
+ ["adb", "-s", self.serial, *parts], capture_output=True,
74
+ text=True, encoding="utf-8", errors="replace", timeout=30,
75
+ check=False)
76
+ except (OSError, subprocess.SubprocessError):
77
+ raise AcceptanceError("adb_command_unavailable") from None
78
+ require(allow_failure or result.returncode == 0, "adb_command_failed")
79
+ return result.stdout
80
+
81
+ def shell(self, *parts, allow_failure=False):
82
+ # adb shell uses a remote shell even when the host subprocess does not.
83
+ return self.command("shell", " ".join(shlex.quote(str(p)) for p in parts),
84
+ allow_failure=allow_failure)
85
+
86
+
87
+def active_fixture_keys(output):
88
+ """Parse only `cmd notification list` active keys, never dumpsys history."""
89
+ found = []
90
+ for line in output.splitlines():
91
+ key = line.strip()
92
+ pieces = key.split("|")
93
+ if len(pieces) < 2 or pieces[1] != PACKAGE:
94
+ continue
95
+ require(len(pieces) == 5 and pieces[0] == "0" and pieces[2] == "1" and
96
+ pieces[3] == "lifeguide-plan:" + REMINDER and
97
+ re.fullmatch(r"[0-9]+", pieces[4]) is not None,
98
+ "unexpected_fixture_notification")
99
+ require(key not in found, "duplicate_fixture_notification")
100
+ found.append(key)
101
+ require(len(found) <= 1, "unexpected_fixture_notification")
102
+ return found
103
+
104
+
105
+def _notification_record(dump, key):
106
+ require(active_fixture_keys(key) == [key], "invalid_fixture_notification_key")
107
+ records = re.split(r"(?m)(?=^[ \t]*NotificationRecord\()", dump)
108
+ matching = [record for record in records
109
+ if re.search(r"\bkey=" + re.escape(key) + r"(?=[\s):])", record)
110
+ and re.search(r"\bpkg=" + re.escape(PACKAGE) + r"(?=[\s)])", record)]
111
+ require(len(matching) == 1, "fixture_notification_record_missing_or_ambiguous")
112
+ return matching[0]
113
+
114
+
115
+def check_notification_record(dump, key, *, require_channel=False):
116
+ record = _notification_record(dump, key)
117
+ titles = re.findall(r"android\.title=String \(([^\n]*)\)", record)
118
+ bodies = re.findall(r"android\.text=String \(([^\n]*)\)", record)
119
+ require(bool(titles) and titles[0] == COMPANION,
120
+ "fixture_notification_title_mismatch")
121
+ require(bool(bodies) and all(body == GENERIC_BODY for body in bodies),
122
+ "fixture_notification_body_mismatch")
123
+ require(CANARY not in record, "fixture_notification_contains_private_canary")
124
+ if require_channel:
125
+ require(re.search(r"(?:channel=|mId=['\"]?)" + re.escape(CHANNEL) +
126
+ r"(?=['\"\s,)])", record) is not None,
127
+ "fixture_notification_channel_mismatch")
128
+ return {"titleMatches": True, "genericBodyMatches": True,
129
+ "privateCanaryAbsent": True}
130
+
131
+
132
+def _integer(value):
133
+ return type(value) is int and value > 0
134
+
135
+
136
+def fixture_marker(line, nonce, mode):
137
+ require(re.fullmatch(r"[0-9a-f]{8,32}", nonce) is not None and mode in MODES,
138
+ "invalid_fixture_request")
139
+ if MARKER not in line:
140
+ return None
141
+ raw = line.split(MARKER, 1)[1]
142
+ try:
143
+ marker = json.loads(raw)
144
+ except (ValueError, TypeError):
145
+ if nonce in raw:
146
+ raise AcceptanceError("invalid_fixture_marker") from None
147
+ return None
148
+ if not isinstance(marker, dict) or marker.get("nonce") != nonce:
149
+ return None
150
+ require(marker.get("mode") == mode, "unexpected_fixture_mode")
151
+ require(marker.get("simulatedServerAcknowledgement") is True,
152
+ "fixture_simulation_label_missing")
153
+ status = marker.get("status")
154
+ required_status = {"supported", "permissionGranted", "active", "activeScope",
155
+ "scheduledCount", "timing", "canScheduleExactAlarms"}
156
+ require(isinstance(status, dict) and required_status <= set(status),
157
+ "invalid_fixture_status")
158
+ require(status.get("supported") is True and
159
+ all(type(status.get(name)) is bool for name in
160
+ ("permissionGranted", "active", "canScheduleExactAlarms")) and
161
+ type(status.get("scheduledCount")) is int and
162
+ status["scheduledCount"] in (0, 1) and
163
+ status.get("timing") in ("exact", "approximate"),
164
+ "invalid_fixture_status")
165
+ require(status["canScheduleExactAlarms"] == (status["timing"] == "exact"),
166
+ "invalid_fixture_status")
167
+ require(status.get("activeScope") == (SCOPE if status["active"] else None),
168
+ "unexpected_fixture_scope")
169
+ require(status["active"] or status["scheduledCount"] == 0,
170
+ "invalid_fixture_status")
171
+ clean = {"nonce": nonce, "mode": mode,
172
+ "simulatedServerAcknowledgement": True,
173
+ "status": {name: status[name] for name in (
174
+ "supported", "permissionGranted", "active", "activeScope",
175
+ "scheduledCount", "timing", "canScheduleExactAlarms")}}
176
+ if "scheduledAtEpochMs" in marker:
177
+ require(mode == "schedule" and _integer(marker["scheduledAtEpochMs"]),
178
+ "invalid_fixture_deadline")
179
+ clean["scheduledAtEpochMs"] = marker["scheduledAtEpochMs"]
180
+ return clean
181
+
182
+
183
+def parse_preferences(xml):
184
+ """Accept only the known synthetic native state; do not return private data."""
185
+ try:
186
+ require(len(xml) <= 32768 and "<!" not in xml,
187
+ "unexpected_fixture_preferences")
188
+ root = ET.fromstring(xml)
189
+ require(root.tag == "map" and not root.attrib,
190
+ "unexpected_fixture_preferences")
191
+ if len(root) == 0:
192
+ return None
193
+ require(len(root) == 1 and root[0].tag == "string" and
194
+ root[0].attrib == {"name": "active"} and len(root[0]) == 0,
195
+ "unexpected_fixture_preferences")
196
+ state = json.loads(root[0].text or "")
197
+ require(isinstance(state, dict) and set(state) <= {
198
+ "scope", "generation", "issuedAtEpochMs", "validUntilEpochMs",
199
+ "reminders", "deliveryExpired"}, "unexpected_fixture_preferences")
200
+ require(state.get("scope") == SCOPE and
201
+ str(uuid.UUID(state["generation"], version=4)) == state["generation"] and
202
+ _integer(state.get("issuedAtEpochMs")) and
203
+ _integer(state.get("validUntilEpochMs")) and
204
+ 0 < state["validUntilEpochMs"] - state["issuedAtEpochMs"] <= 600000 and
205
+ isinstance(state.get("reminders"), list) and len(state["reminders"]) <= 1,
206
+ "unexpected_fixture_preferences")
207
+ if "deliveryExpired" in state:
208
+ require(type(state["deliveryExpired"]) is bool,
209
+ "unexpected_fixture_preferences")
210
+ for row in state["reminders"]:
211
+ require(isinstance(row, dict) and set(row) <= {
212
+ "id", "planItemId", "scheduledAtEpochMs", "companionName", "delivered"} and
213
+ row.get("id") == REMINDER and row.get("planItemId") == PLAN and
214
+ row.get("companionName") == COMPANION and
215
+ _integer(row.get("scheduledAtEpochMs")) and
216
+ state["issuedAtEpochMs"] < row["scheduledAtEpochMs"] <= state["validUntilEpochMs"] and
217
+ type(row.get("delivered", False)) is bool,
218
+ "unexpected_fixture_preferences")
219
+ return state
220
+ except (ET.ParseError, ValueError, TypeError, KeyError, AttributeError):
221
+ raise AcceptanceError("unexpected_fixture_preferences") from None
222
+
223
+
224
+class Harness:
225
+ def __init__(self, *, serial, apk, allow_reset, adb=None,
226
+ manifest_check=check_apk_manifest.check,
227
+ clock=time.monotonic, sleep=time.sleep):
228
+ self.serial, self.apk, self.allow_reset = serial, Path(apk), allow_reset
229
+ self.adb = adb
230
+ self.manifest_check = manifest_check
231
+ self.clock, self.sleep = clock, sleep
232
+ self.installed = False
233
+ self.receipt = {"schemaVersion": 1, "result": "FAIL",
234
+ "scope": "synthetic API 35 emulator only",
235
+ "simulatedServerAcknowledgement": True,
236
+ "limitations": LIMITATIONS.copy(), "checks": {}}
237
+
238
+ def install_fixture(self):
239
+ validate_serial(self.serial)
240
+ require(self.allow_reset is True, "synthetic_emulator_reset_flag_required")
241
+ require(self.apk.is_file(), "apk_file_required")
242
+ try:
243
+ manifest = self.manifest_check(self.apk, "debug")
244
+ require(isinstance(manifest, dict) and manifest.get("result") == "PASS" and
245
+ manifest.get("mode") == "debug" and manifest.get("package") == PACKAGE and
246
+ manifest.get("debuggable") is True and
247
+ type(manifest.get("targetSdkVersion")) is int and
248
+ manifest["targetSdkVersion"] == 36 and
249
+ re.fullmatch(r"[0-9a-f]{64}", manifest.get("sha256", "")) is not None,
250
+ "apk_manifest_rejected")
251
+ except Exception:
252
+ raise AcceptanceError("apk_manifest_rejected") from None
253
+ if self.adb is None:
254
+ self.adb = Adb(self.serial)
255
+ require(self.adb.command("get-state").strip() == "device", "emulator_not_ready")
256
+ kernel = self.adb.shell("getprop", "ro.kernel.qemu").strip()
257
+ boot = self.adb.shell("getprop", "ro.boot.qemu").strip()
258
+ require("1" in (kernel, boot), "qemu_emulator_required")
259
+ require(self.adb.shell("getprop", "ro.hardware").strip() in ("ranchu", "goldfish"),
260
+ "android_emulator_hardware_required")
261
+ product = self.adb.shell("getprop", "ro.product.name").strip()
262
+ require(re.fullmatch(r"sdk_(?:gphone|phone)[A-Za-z0-9_]*", product) is not None,
263
+ "synthetic_sdk_product_required")
264
+ require(self.adb.shell("getprop", "ro.build.version.sdk").strip() == "35",
265
+ "api_35_required")
266
+ require(not self.adb.shell("pm", "list", "packages", PACKAGE).strip(),
267
+ "fresh_emulator_required_package_already_present")
268
+ installed = self.adb.command("install", str(self.apk))
269
+ require("Failure" not in installed and "Error" not in installed,
270
+ "fixture_install_failed")
271
+ self.installed = True
272
+ self.adb.shell("pm", "grant", PACKAGE, "android.permission.POST_NOTIFICATIONS")
273
+ self.adb.shell("cmd", "appops", "set", PACKAGE, "SCHEDULE_EXACT_ALARM", "allow")
274
+ self.receipt["apk"] = {name: manifest[name] for name in
275
+ ("sha256", "package", "debuggable", "targetSdkVersion")}
276
+ self.receipt["checks"]["emulatorAndFreshInstallGates"] = "PASS"
277
+
278
+ def _ready(self):
279
+ require(self.installed, "fixture_not_installed_by_this_runner")
280
+
281
+ def process_dead(self):
282
+ self._ready()
283
+ self.adb.shell("input", "keyevent", "KEYCODE_HOME")
284
+ self.adb.shell("am", "kill", PACKAGE)
285
+ until = self.clock() + 10
286
+ while True:
287
+ state = self.adb.shell("sh", "-c", PID_QUERY).strip()
288
+ require(state in ("PRESENT", "ABSENT"), "fixture_process_query_failed")
289
+ if state == "ABSENT":
290
+ return True
291
+ require(self.clock() < until, "fixture_process_did_not_exit")
292
+ self.sleep(0.25)
293
+
294
+ def launch(self, mode):
295
+ self._ready()
296
+ require(mode in MODES, "invalid_fixture_request")
297
+ self.process_dead()
298
+ nonce = secrets.token_hex(8)
299
+ route = "/" + mode + "?nonce=" + nonce
300
+ if mode == "schedule":
301
+ route += "&delay=45"
302
+ output = self.adb.shell("am", "start", "-W", "-n", PACKAGE + "/.MainActivity",
303
+ "--es", "route", route)
304
+ require("Error" not in output and "Exception" not in output,
305
+ "fixture_activity_launch_failed")
306
+ until = self.clock() + 30
307
+ while True:
308
+ logs = self.adb.command("logcat", "-d", "-v", "brief", "-s", "flutter:I")
309
+ for line in logs.splitlines():
310
+ marker = fixture_marker(line, nonce, mode)
311
+ if marker is not None:
312
+ return marker
313
+ require(self.clock() < until, "fixture_marker_timeout")
314
+ self.sleep(0.5)
315
+
316
+ def preferences(self):
317
+ self._ready()
318
+ script = ("if [ -f " + PREFERENCES + " ]; then cat " + PREFERENCES +
319
+ "; else printf '<map/>'; fi")
320
+ return parse_preferences(self.adb.shell("run-as", PACKAGE, "sh", "-c", script))
321
+
322
+ def active_keys(self):
323
+ self._ready()
324
+ return active_fixture_keys(self.adb.shell("cmd", "notification", "list"))
325
+
326
+ def device_epoch_ms(self):
327
+ output = self.adb.shell("date", "+%s").strip()
328
+ require(re.fullmatch(r"[0-9]{10,}", output) is not None, "emulator_clock_unavailable")
329
+ return int(output) * 1000
330
+
331
+ def assert_status(self, marker, *, active, count, exact):
332
+ status = marker["status"]
333
+ require(status["permissionGranted"] is True and status["active"] is active and
334
+ status["scheduledCount"] == count and
335
+ status["canScheduleExactAlarms"] is exact and
336
+ status["timing"] == ("exact" if exact else "approximate"),
337
+ "fixture_status_assertion_failed")
338
+
339
+ def scheduled(self, *, exact):
340
+ marker = self.launch("schedule")
341
+ self.assert_status(marker, active=True, count=1, exact=exact)
342
+ at = marker.get("scheduledAtEpochMs")
343
+ require(_integer(at) and 15000 < at - self.device_epoch_ms() <= 47000,
344
+ "fixture_schedule_not_future_45_seconds")
345
+ state = self.preferences()
346
+ require(state is not None and len(state["reminders"]) == 1 and
347
+ state["reminders"][0]["scheduledAtEpochMs"] == at and
348
+ state["reminders"][0].get("delivered", False) is False,
349
+ "fixture_schedule_not_persisted")
350
+ require(self.active_keys() == [], "unexpected_fixture_notification_before_deadline")
351
+ return at, state
352
+
353
+ def wait_for_post(self, at):
354
+ until = self.clock() + max(0, (at - self.device_epoch_ms()) / 1000) + 30
355
+ while True:
356
+ keys = self.active_keys()
357
+ if keys:
358
+ require(self.device_epoch_ms() + 1000 >= at,
359
+ "fixture_notification_posted_before_deadline")
360
+ return keys[0]
361
+ require(self.clock() < until, "fixture_notification_not_posted")
362
+ self.sleep(1)
363
+
364
+ def assert_no_post_through(self, at):
365
+ # Check throughout the interval, not only a final snapshot.
366
+ remaining = max(0, (at - self.device_epoch_ms()) / 1000) + 5
367
+ until = self.clock() + remaining
368
+ while True:
369
+ require(self.active_keys() == [], "canceled_fixture_notification_posted")
370
+ if self.clock() >= until:
371
+ return
372
+ self.sleep(min(1, until - self.clock()))
373
+
374
+ def run(self):
375
+ self.install_fixture()
376
+ checks = self.receipt["checks"]
377
+ initial = self.launch("inspect")
378
+ self.assert_status(initial, active=False, count=0, exact=True)
379
+ require(self.preferences() is None and not self.active_keys(),
380
+ "fresh_inspect_created_native_state")
381
+ checks["inspectDoesNotActivate"] = "PASS"
382
+
383
+ at, scheduled = self.scheduled(exact=True)
384
+ self.process_dead()
385
+ checks["processAbsentBeforeAlarm"] = "PASS"
386
+ key = self.wait_for_post(at)
387
+ delivered = self.preferences()
388
+ require(delivered is not None and delivered["generation"] == scheduled["generation"] and
389
+ len(delivered["reminders"]) == 1 and
390
+ delivered["reminders"][0].get("delivered") is True,
391
+ "native_delivered_marker_missing")
392
+ checks["notificationAfterProcessDeath"] = "PASS"
393
+ checks["notificationContent"] = check_notification_record(
394
+ self.adb.shell("dumpsys", "notification", "--noredact"), key,
395
+ require_channel=True)
396
+ checks["notificationChannel"] = CHANNEL
397
+
398
+ inspected = self.launch("inspect")
399
+ self.assert_status(inspected, active=True, count=0, exact=True)
400
+ require(self.preferences() == delivered and self.active_keys() == [key],
401
+ "inspect_changed_delivered_state_or_post")
402
+ checks["relaunchPreservesDeliveredStateAndPost"] = "PASS"
403
+
404
+ suppressed = self.launch("suppress")
405
+ self.assert_status(suppressed, active=True, count=0, exact=True)
406
+ state = self.preferences()
407
+ require(state is not None and state["reminders"] == [] and not self.active_keys(),
408
+ "suppress_did_not_clear_delivered_post")
409
+ checks["suppressClearsDeliveredPost"] = "PASS"
410
+
411
+ canceled_at, _ = self.scheduled(exact=True)
412
+ suppressed = self.launch("suppress")
413
+ self.assert_status(suppressed, active=True, count=0, exact=True)
414
+ require(self.device_epoch_ms() < canceled_at, "fixture_cancellation_missed_deadline")
415
+ state = self.preferences()
416
+ require(state is not None and state["reminders"] == [],
417
+ "fixture_cancellation_not_persisted")
418
+ self.process_dead()
419
+ self.assert_no_post_through(canceled_at)
420
+ checks["cancelBeforeDeadlineHasNoOSPost"] = "PASS"
421
+
422
+ self.adb.shell("cmd", "appops", "set", PACKAGE, "SCHEDULE_EXACT_ALARM", "deny")
423
+ self.scheduled(exact=False)
424
+ checks["deniedExactAccessReportsApproximate"] = "PASS"
425
+ checks["approximateAlarmDeliveryTiming"] = "UNVERIFIED"
426
+ off = self.launch("off")
427
+ self.assert_status(off, active=False, count=0, exact=False)
428
+ require(self.preferences() is None and not self.active_keys(),
429
+ "off_did_not_clear_native_state_and_posts")
430
+ checks["offClearsNativeStateAndPosts"] = "PASS"
431
+ self.receipt["result"] = "PASS"
432
+ return self.receipt
433
+
434
+
435
+def main(argv=None):
436
+ parser = argparse.ArgumentParser(description=__doc__)
437
+ parser.add_argument("--serial", required=True)
438
+ parser.add_argument("--apk", type=Path, required=True)
439
+ parser.add_argument("--allow-synthetic-emulator-reset", action="store_true")
440
+ parser.add_argument("--output", type=Path)
441
+ options = parser.parse_args(argv)
442
+ harness = Harness(serial=options.serial, apk=options.apk,
443
+ allow_reset=options.allow_synthetic_emulator_reset)
444
+ try:
445
+ receipt = harness.run()
446
+ except AcceptanceError as error:
447
+ receipt = harness.receipt
448
+ receipt["error"] = str(error)
449
+ serialized = json.dumps(receipt, ensure_ascii=False, indent=2) + "\n"
450
+ if options.output:
451
+ options.output.parent.mkdir(parents=True, exist_ok=True)
452
+ options.output.write_text(serialized, encoding="utf-8")
453
+ print(serialized, end="")
454
+ return 0 if receipt["result"] == "PASS" else 1
455
+
456
+
457
+if __name__ == "__main__":
458
+ raise SystemExit(main())
apps/lifemate/tool/test_native_reminders_android_test.py
new
+405
@@ -0,0 +1,405 @@
1
+"""Host-side tests only: no adb, emulator, account, network, or APK build."""
2
+import json
3
+import contextlib
4
+import io
5
+import tempfile
6
+import unittest
7
+from pathlib import Path
8
+from unittest.mock import patch
9
+from urllib.parse import parse_qs, urlparse
10
+from xml.sax.saxutils import escape
11
+
12
+import test_native_reminders_android as subject
13
+
14
+
15
+class FakeAdb:
16
+ def __init__(self, overrides=None):
17
+ self.calls = []
18
+ self.responses = {
19
+ ("get-state",): "device\n",
20
+ ("shell", "getprop", "ro.kernel.qemu"): "1\n",
21
+ ("shell", "getprop", "ro.boot.qemu"): "1\n",
22
+ ("shell", "getprop", "ro.hardware"): "ranchu\n",
23
+ ("shell", "getprop", "ro.product.name"): "sdk_gphone64_x86_64\n",
24
+ ("shell", "getprop", "ro.build.version.sdk"): "35\n",
25
+ ("shell", "pm", "list", "packages", subject.PACKAGE): "",
26
+ }
27
+ self.responses.update(overrides or {})
28
+
29
+ def command(self, *parts, allow_failure=False):
30
+ self.calls.append(parts)
31
+ return self.responses.get(parts, "")
32
+
33
+ def shell(self, *parts, allow_failure=False):
34
+ return self.command("shell", *parts, allow_failure=allow_failure)
35
+
36
+
37
+class SyntheticEmulator(FakeAdb):
38
+ """A model of adb responses, not evidence of Android device behavior."""
39
+ def __init__(self):
40
+ super().__init__()
41
+ self.elapsed = 0
42
+ self.state = None
43
+ self.posted = False
44
+ self.alive = False
45
+ self.exact = True
46
+ self.markers = []
47
+ self.generation = 0
48
+ self.modes = []
49
+ self.private_body = False
50
+ self.refuse_kill = False
51
+ self.pid_query_failure = False
52
+
53
+ def clock(self):
54
+ return self.elapsed
55
+
56
+ def epoch(self):
57
+ return 1800000000000 + int(self.elapsed * 1000)
58
+
59
+ def sleep(self, seconds):
60
+ self.elapsed += seconds
61
+ if self.state and self.exact:
62
+ for row in self.state["reminders"]:
63
+ if not row.get("delivered") and row["scheduledAtEpochMs"] <= self.epoch():
64
+ row["delivered"] = True
65
+ self.posted = True
66
+ self.alive = True # The native receiver may start its process.
67
+
68
+ def status(self):
69
+ return {"supported": True, "permissionGranted": True,
70
+ "active": self.state is not None,
71
+ "activeScope": subject.SCOPE if self.state else None,
72
+ "scheduledCount": sum(row["scheduledAtEpochMs"] > self.epoch()
73
+ for row in self.state["reminders"]) if self.state else 0,
74
+ "timing": "exact" if self.exact else "approximate",
75
+ "canScheduleExactAlarms": self.exact}
76
+
77
+ def key(self):
78
+ return f"0|{subject.PACKAGE}|1|lifeguide-plan:{subject.REMINDER}|10123"
79
+
80
+ def command(self, *parts, allow_failure=False):
81
+ self.calls.append(parts)
82
+ if parts[0] == "logcat":
83
+ return "\n".join(self.markers)
84
+ if parts[:4] == ("shell", "cmd", "appops", "set"):
85
+ self.exact = parts[-1] == "allow"
86
+ if parts == ("shell", "input", "keyevent", "KEYCODE_HOME"):
87
+ return ""
88
+ if parts == ("shell", "am", "kill", subject.PACKAGE):
89
+ self.alive = self.refuse_kill
90
+ return ""
91
+ if parts == ("shell", "pidof", subject.PACKAGE):
92
+ if self.pid_query_failure:
93
+ return ""
94
+ return "123\n" if self.alive else ""
95
+ if parts[:3] == ("shell", "sh", "-c"):
96
+ if self.pid_query_failure:
97
+ return ""
98
+ return "PRESENT" if self.alive else "ABSENT"
99
+ if parts == ("shell", "date", "+%s"):
100
+ return str(self.epoch() // 1000)
101
+ if parts[:3] == ("shell", "run-as", subject.PACKAGE):
102
+ if self.state is None:
103
+ return "<map/>"
104
+ return '<map><string name="active">' + escape(json.dumps(self.state)) + '</string></map>'
105
+ if parts == ("shell", "cmd", "notification", "list"):
106
+ return self.key() + "\n" if self.posted else ""
107
+ if parts[:3] == ("shell", "dumpsys", "notification"):
108
+ body = subject.CANARY if self.private_body else subject.GENERIC_BODY
109
+ return (f"NotificationRecord(pkg={subject.PACKAGE} key={self.key()})\n"
110
+ f" channel={subject.CHANNEL}\n"
111
+ f" android.title=String ({subject.COMPANION})\n"
112
+ f" android.text=String ({body})\n")
113
+ if parts[:3] == ("shell", "am", "start"):
114
+ self.alive = True
115
+ route = urlparse(parts[-1])
116
+ mode = route.path.removeprefix("/")
117
+ query = parse_qs(route.query)
118
+ self.modes.append(mode)
119
+ if mode == "schedule":
120
+ self.generation += 1
121
+ self.state = {
122
+ "scope": subject.SCOPE,
123
+ "generation": f"{self.generation:08x}-4444-4444-8444-444444444444",
124
+ "issuedAtEpochMs": self.epoch(),
125
+ "validUntilEpochMs": self.epoch() + 600000,
126
+ "reminders": [{"id": subject.REMINDER, "planItemId": subject.PLAN,
127
+ "companionName": subject.COMPANION,
128
+ "scheduledAtEpochMs": self.epoch() + 45000}],
129
+ }
130
+ self.posted = False
131
+ elif mode == "suppress" and self.state:
132
+ self.state["reminders"] = []
133
+ self.posted = False
134
+ elif mode == "off":
135
+ self.state = None
136
+ self.posted = False
137
+ marker = {"nonce": query["nonce"][0], "mode": mode,
138
+ "status": self.status(), "simulatedServerAcknowledgement": True}
139
+ if mode == "schedule":
140
+ marker["scheduledAtEpochMs"] = self.state["reminders"][0]["scheduledAtEpochMs"]
141
+ self.markers.append(subject.MARKER + json.dumps(marker))
142
+ return "Success"
143
+ return self.responses.get(parts, "")
144
+
145
+
146
+class PreflightTest(unittest.TestCase):
147
+ def setUp(self):
148
+ self.directory = tempfile.TemporaryDirectory()
149
+ self.addCleanup(self.directory.cleanup)
150
+ self.apk = Path(self.directory.name) / "fixture.apk"
151
+ self.apk.write_bytes(b"synthetic APK placeholder; manifest check is mocked")
152
+ self.manifest = {
153
+ "result": "PASS", "mode": "debug", "package": subject.PACKAGE,
154
+ "debuggable": True, "targetSdkVersion": 36, "sha256": "a" * 64,
155
+ }
156
+
157
+ def harness(self, adb, **overrides):
158
+ values = dict(serial="emulator-5554", apk=self.apk, allow_reset=True,
159
+ adb=adb, manifest_check=lambda path, mode: self.manifest)
160
+ values.update(overrides)
161
+ return subject.Harness(**values)
162
+
163
+ def assert_read_only(self, adb):
164
+ for parts in adb.calls:
165
+ self.assertNotEqual(parts[0], "install")
166
+ if parts[0] == "shell":
167
+ self.assertIn(parts[1:3], [("getprop", "ro.kernel.qemu"),
168
+ ("getprop", "ro.boot.qemu"), ("getprop", "ro.hardware"),
169
+ ("getprop", "ro.product.name"), ("getprop", "ro.build.version.sdk"),
170
+ ("pm", "list")])
171
+
172
+ def test_physical_serial_refused_before_any_adb_call(self):
173
+ for serial in ("R58REALDEVICE", "", "emulator-5554;echo bad", "emulator-5554\n"):
174
+ with self.subTest(serial=serial):
175
+ adb = FakeAdb()
176
+ with self.assertRaises(subject.AcceptanceError):
177
+ self.harness(adb, serial=serial).install_fixture()
178
+ self.assertEqual(adb.calls, [])
179
+
180
+ def test_reset_confirmation_required_before_any_adb_call(self):
181
+ adb = FakeAdb()
182
+ with self.assertRaises(subject.AcceptanceError):
183
+ self.harness(adb, allow_reset=False).install_fixture()
184
+ self.assertEqual(adb.calls, [])
185
+
186
+ def test_missing_apk_refused_before_any_adb_call(self):
187
+ adb = FakeAdb()
188
+ with self.assertRaises(subject.AcceptanceError):
189
+ self.harness(adb, apk=self.apk.with_name("missing.apk")).install_fixture()
190
+ self.assertEqual(adb.calls, [])
191
+
192
+ def test_bad_manifest_refused_before_any_adb_call(self):
193
+ adb = FakeAdb()
194
+ def reject(path, mode):
195
+ raise ValueError("do not expose arbitrary checker output")
196
+ with self.assertRaisesRegex(subject.AcceptanceError, "apk_manifest_rejected"):
197
+ self.harness(adb, manifest_check=reject).install_fixture()
198
+ self.assertEqual(adb.calls, [])
199
+
200
+ def test_non_debug_or_wrong_target_manifest_is_rejected(self):
201
+ for changes in ({"debuggable": False}, {"targetSdkVersion": 35}, {"package": "other.app"}):
202
+ adb = FakeAdb()
203
+ with self.subTest(changes=changes):
204
+ with self.assertRaises(subject.AcceptanceError):
205
+ self.harness(adb, manifest_check=lambda path, mode: self.manifest | changes).install_fixture()
206
+ self.assertEqual(adb.calls, [])
207
+
208
+ def test_each_emulator_gate_prevents_mutation(self):
209
+ cases = [
210
+ {("get-state",): "offline\n"},
211
+ {("shell", "getprop", "ro.kernel.qemu"): "", ("shell", "getprop", "ro.boot.qemu"): "0"},
212
+ {("shell", "getprop", "ro.hardware"): "real-phone-chip"},
213
+ {("shell", "getprop", "ro.product.name"): "owners_phone"},
214
+ {("shell", "getprop", "ro.build.version.sdk"): "34"},
215
+ {("shell", "pm", "list", "packages", subject.PACKAGE): "package:ir.lifeguide.app\n"},
216
+ ]
217
+ for responses in cases:
218
+ with self.subTest(responses=responses):
219
+ adb = FakeAdb(responses)
220
+ with self.assertRaises(subject.AcceptanceError):
221
+ self.harness(adb).install_fixture()
222
+ self.assert_read_only(adb)
223
+
224
+ def test_install_follows_all_gates_and_no_other_package_is_touched(self):
225
+ adb = FakeAdb()
226
+ self.harness(adb).install_fixture()
227
+ install_index = next(i for i, parts in enumerate(adb.calls) if parts[0] == "install")
228
+ self.assertIn(("shell", "pm", "list", "packages", subject.PACKAGE), adb.calls[:install_index])
229
+ self.assertIn(("shell", "pm", "grant", subject.PACKAGE, "android.permission.POST_NOTIFICATIONS"), adb.calls)
230
+ self.assertIn(("shell", "cmd", "appops", "set", subject.PACKAGE, "SCHEDULE_EXACT_ALARM", "allow"), adb.calls)
231
+ flattened = " ".join(" ".join(parts) for parts in adb.calls)
232
+ for forbidden in ("force-stop", "kill-server", "uninstall", "logcat -c"):
233
+ self.assertNotIn(forbidden, flattened)
234
+
235
+
236
+class ParsingTest(unittest.TestCase):
237
+ def key(self, reminder=subject.REMINDER):
238
+ return f"0|{subject.PACKAGE}|1|lifeguide-plan:{reminder}|10123"
239
+
240
+ def test_active_keys_only_recognize_exact_package_id_and_tag(self):
241
+ own = self.key()
242
+ output = "\n".join((own, "0|other.app|1|lifeguide-plan:private|10124",
243
+ f"0|{subject.PACKAGE}.fake|1|lifeguide-plan:{subject.REMINDER}|10125"))
244
+ self.assertEqual(subject.active_fixture_keys(output), [own])
245
+ self.assertEqual(subject.active_fixture_keys("no active keys\n"), [])
246
+
247
+ def test_unknown_own_notification_is_refused_without_echoing_it(self):
248
+ with self.assertRaisesRegex(subject.AcceptanceError, "unexpected_fixture_notification") as caught:
249
+ subject.active_fixture_keys(f"0|{subject.PACKAGE}|9|private-user-title|10123")
250
+ self.assertNotIn("private-user-title", str(caught.exception))
251
+
252
+ def test_notification_check_uses_matching_record_only(self):
253
+ key = self.key()
254
+ dump = ("Notification List:\n NotificationRecord(pkg=other.app key=other)\n"
255
+ " android.text=String (SYNTHETIC_PRIVATE_TASK_CANARY)\n"
256
+ f" NotificationRecord(pkg={subject.PACKAGE} key={key})\n"
257
+ f" android.title=String ({subject.COMPANION})\n"
258
+ f" android.text=String ({subject.GENERIC_BODY})\n")
259
+ result = subject.check_notification_record(dump, key)
260
+ self.assertEqual(result, {"titleMatches": True, "genericBodyMatches": True,
261
+ "privateCanaryAbsent": True})
262
+ self.assertNotIn("other.app", json.dumps(result))
263
+
264
+ def test_notification_canary_or_wrong_body_fails(self):
265
+ for body in ("wrong body", subject.GENERIC_BODY + " SYNTHETIC_PRIVATE_TASK_CANARY"):
266
+ dump = (f"NotificationRecord(pkg={subject.PACKAGE} key={self.key()})\n"
267
+ f"android.title=String ({subject.COMPANION})\nandroid.text=String ({body})")
268
+ with self.assertRaises(subject.AcceptanceError):
269
+ subject.check_notification_record(dump, self.key())
270
+
271
+ def test_android_record_key_terminator_and_channel_are_recognized(self):
272
+ dump = (f" NotificationRecord(abc: pkg={subject.PACKAGE} user=UserHandle{{0}} "
273
+ f"id=1 key={self.key()}: Notification(channel={subject.CHANNEL} vis=PRIVATE))\n"
274
+ f" android.title=String ({subject.COMPANION})\n"
275
+ f" android.text=String ({subject.GENERIC_BODY})\n")
276
+ result = subject.check_notification_record(dump, self.key(), require_channel=True)
277
+ self.assertTrue(result["genericBodyMatches"])
278
+
279
+ def test_marker_requires_nonce_mode_fixture_scope_and_simulation_label(self):
280
+ marker = {"nonce": "0123456789abcdef", "mode": "inspect", "simulatedServerAcknowledgement": True,
281
+ "status": {"supported": True, "permissionGranted": True, "active": True,
282
+ "activeScope": subject.SCOPE, "scheduledCount": 0, "timing": "exact",
283
+ "canScheduleExactAlarms": True}}
284
+ line = "I/flutter (123): LG_NATIVE_REMINDER_FIXTURE " + json.dumps(marker)
285
+ self.assertEqual(subject.fixture_marker(line, marker["nonce"], "inspect")["status"]["scheduledCount"], 0)
286
+ self.assertIsNone(subject.fixture_marker(line, "a" * 16, "inspect"))
287
+ for change in ({"simulatedServerAcknowledgement": False},
288
+ {"status": marker["status"] | {"activeScope": "real-user-scope"}}):
289
+ with self.assertRaises(subject.AcceptanceError):
290
+ subject.fixture_marker("LG_NATIVE_REMINDER_FIXTURE " + json.dumps(marker | change), marker["nonce"], "inspect")
291
+
292
+ def test_incomplete_or_inconsistent_status_is_a_sanitized_failure(self):
293
+ status = {"supported": True, "permissionGranted": True, "active": False,
294
+ "activeScope": None, "scheduledCount": 0, "timing": "exact",
295
+ "canScheduleExactAlarms": True}
296
+ for broken in ({key: value for key, value in status.items() if key != "activeScope"},
297
+ status | {"canScheduleExactAlarms": False}):
298
+ marker = {"nonce": "0123456789abcdef", "mode": "inspect", "status": broken,
299
+ "simulatedServerAcknowledgement": True}
300
+ with self.subTest(status=broken):
301
+ with self.assertRaises(subject.AcceptanceError):
302
+ subject.fixture_marker(subject.MARKER + json.dumps(marker), marker["nonce"], "inspect")
303
+
304
+ def test_native_preferences_only_accept_known_synthetic_payload(self):
305
+ state = {"scope": subject.SCOPE, "generation": "44444444-4444-4444-8444-444444444444",
306
+ "issuedAtEpochMs": 1800000000000, "validUntilEpochMs": 1800000600000,
307
+ "reminders": [{"id": subject.REMINDER, "planItemId": subject.PLAN,
308
+ "scheduledAtEpochMs": 1800000045000,
309
+ "companionName": subject.COMPANION, "delivered": True}]}
310
+ from xml.sax.saxutils import escape
311
+ xml = '<map><string name="active">' + escape(json.dumps(state)) + '</string></map>'
312
+ parsed = subject.parse_preferences(xml)
313
+ self.assertTrue(parsed["reminders"][0]["delivered"])
314
+ self.assertIsNone(subject.parse_preferences('<map/>'))
315
+ state["reminders"][0]["companionName"] = "real private task text"
316
+ with self.assertRaisesRegex(subject.AcceptanceError, "unexpected_fixture_preferences") as caught:
317
+ subject.parse_preferences('<map><string name="active">' + escape(json.dumps(state)) + '</string></map>')
318
+ self.assertNotIn("real private task text", str(caught.exception))
319
+
320
+ def test_adb_shell_quoting_keeps_initial_route_a_single_argument(self):
321
+ completed = type("Completed", (), {"returncode": 0, "stdout": "", "stderr": ""})()
322
+ with patch.object(subject.subprocess, "run", return_value=completed) as run:
323
+ subject.Adb("emulator-5554").shell("am", "start", "--es", "route", "/schedule?nonce=abc12345&delay=45")
324
+ arguments = run.call_args.args[0]
325
+ self.assertEqual(arguments[:4], ["adb", "-s", "emulator-5554", "shell"])
326
+ self.assertIn("'/schedule?nonce=abc12345&delay=45'", arguments[4])
327
+
328
+
329
+class LifecycleTest(unittest.TestCase):
330
+ def harness(self, adb):
331
+ directory = tempfile.TemporaryDirectory()
332
+ self.addCleanup(directory.cleanup)
333
+ apk = Path(directory.name) / "fixture.apk"
334
+ apk.write_bytes(b"synthetic only")
335
+ manifest = {"result": "PASS", "mode": "debug", "package": subject.PACKAGE,
336
+ "debuggable": True, "targetSdkVersion": 36, "sha256": "a" * 64}
337
+ return subject.Harness(serial="emulator-5554", apk=apk, allow_reset=True, adb=adb,
338
+ manifest_check=lambda path, mode: manifest,
339
+ clock=adb.clock, sleep=adb.sleep)
340
+
341
+ def test_full_sequence_with_virtual_time_finishes_off_and_labels_limits(self):
342
+ adb = SyntheticEmulator()
343
+ receipt = self.harness(adb).run()
344
+ self.assertEqual(receipt["result"], "PASS")
345
+ self.assertEqual(adb.modes, ["inspect", "schedule", "inspect", "suppress",
346
+ "schedule", "suppress", "schedule", "off"])
347
+ self.assertGreaterEqual(adb.elapsed, 95)
348
+ self.assertIsNone(adb.state)
349
+ self.assertFalse(adb.posted)
350
+ self.assertFalse(adb.exact)
351
+ self.assertTrue(all(value == "UNVERIFIED" for value in receipt["limitations"].values()))
352
+ self.assertEqual(receipt["checks"]["approximateAlarmDeliveryTiming"], "UNVERIFIED")
353
+ self.assertEqual(receipt["checks"]["notificationContent"]["privateCanaryAbsent"], True)
354
+ serialized = json.dumps(receipt)
355
+ self.assertNotIn(subject.CANARY, serialized)
356
+ self.assertNotIn("NotificationRecord", serialized)
357
+ self.assertNotIn("<map", serialized)
358
+ for index, parts in enumerate(adb.calls):
359
+ if parts[:3] == ("shell", "am", "start"):
360
+ self.assertEqual(adb.calls[index - 3:index], [
361
+ ("shell", "input", "keyevent", "KEYCODE_HOME"),
362
+ ("shell", "am", "kill", subject.PACKAGE),
363
+ ("shell", "sh", "-c", subject.PID_QUERY)])
364
+ commands = " ".join(" ".join(parts) for parts in adb.calls)
365
+ for forbidden in ("force-stop", "kill-server", "uninstall", "logcat -c"):
366
+ self.assertNotIn(forbidden, commands)
367
+
368
+ def test_process_claim_fails_when_pid_remains(self):
369
+ adb = SyntheticEmulator()
370
+ adb.refuse_kill = True
371
+ with self.assertRaisesRegex(subject.AcceptanceError, "fixture_process_did_not_exit"):
372
+ self.harness(adb).run()
373
+ self.assertEqual(adb.modes, [])
374
+
375
+ def test_empty_failed_pid_query_cannot_claim_process_absence(self):
376
+ adb = SyntheticEmulator()
377
+ adb.pid_query_failure = True
378
+ with self.assertRaisesRegex(subject.AcceptanceError, "fixture_process_query_failed"):
379
+ self.harness(adb).run()
380
+ self.assertEqual(adb.modes, [])
381
+
382
+ def test_os_post_with_private_body_fails_without_echoing_body(self):
383
+ adb = SyntheticEmulator()
384
+ adb.private_body = True
385
+ with self.assertRaises(subject.AcceptanceError) as caught:
386
+ self.harness(adb).run()
387
+ self.assertNotIn(subject.CANARY, str(caught.exception))
388
+
389
+ def test_cli_refusal_writes_only_sanitized_receipt_without_adb(self):
390
+ directory = tempfile.TemporaryDirectory()
391
+ self.addCleanup(directory.cleanup)
392
+ output = Path(directory.name) / "receipt.json"
393
+ with patch.object(subject, "Adb") as adb, contextlib.redirect_stdout(io.StringIO()):
394
+ exit_code = subject.main(["--serial", "REAL_PHONE", "--apk", "/nonexistent.apk",
395
+ "--allow-synthetic-emulator-reset", "--output", str(output)])
396
+ self.assertEqual(exit_code, 1)
397
+ adb.assert_not_called()
398
+ receipt = json.loads(output.read_text())
399
+ self.assertEqual(receipt["result"], "FAIL")
400
+ self.assertEqual(receipt["error"], "explicit_emulator_serial_required")
401
+ self.assertNotIn("REAL_PHONE", output.read_text())
402
+
403
+
404
+if __name__ == "__main__":
405
+ unittest.main()
docs/audits/evidence/android-reminder-tooling-2026-10-19.json
new
+47
@@ -0,0 +1,47 @@
1
+{
2
+ "date": "2026-10-19",
3
+ "scope": "Emulator acceptance tooling only; no production changes",
4
+ "base": "3ce8f2e8bad0128960a4eaa15d6e71718036bc76",
5
+ "verification": [
6
+ {
7
+ "status": "VERIFIED",
8
+ "command": "PUB_CACHE=/tmp/lifeguide-acceptance-pub-cache flutter pub get --offline",
9
+ "output": "Got dependencies!",
10
+ "note": "First attempt with original cache failed errno28; task-local /tmp cache succeeded."
11
+ },
12
+ {
13
+ "status": "VERIFIED",
14
+ "command": "flutter test test/native_reminder_fixture_test.dart --reporter expanded",
15
+ "output": "5 tests passed; initial RED: missing fixture file/symbols, exit1"
16
+ },
17
+ {
18
+ "status": "VERIFIED",
19
+ "command": "flutter test --reporter expanded",
20
+ "output": "01:12 +282: All tests passed!",
21
+ "log": "lg-acceptance-flutter.log"
22
+ },
23
+ {
24
+ "status": "VERIFIED",
25
+ "command": "dart format --output=none --set-exit-if-changed lib test tool/native_reminder_fixture.dart",
26
+ "output": "Formatted 90 files (0 changed) in 0.90 seconds."
27
+ },
28
+ {
29
+ "status": "VERIFIED",
30
+ "command": "flutter analyze",
31
+ "output": "No issues found! (ran in 11.6s)",
32
+ "note": "Initial avoid_relative_lib_imports lint fixed; production lib unchanged."
33
+ },
34
+ {
35
+ "status": "VERIFIED",
36
+ "command": "python3 -m unittest discover -s apps/lifemate/tool -p 'test_native_reminders_android_test.py' -v",
37
+ "output": "Ran 21 tests in 0.006s; OK",
38
+ "note": "Host/parser/safety/model tests only; no adb. Review reproduced transport-error false process-absence; strict PRESENT/ABSENT probe and regression added."
39
+ }
40
+ ],
41
+ "androidEmulator": "UNVERIFIED — CI not executed at this checkpoint",
42
+ "physicalAndroid": "UNVERIFIED",
43
+ "realServerAcknowledgement": "UNVERIFIED — fixture explicitly simulates acknowledgement",
44
+ "safariIranRebootDozeSoundAndUserPermissionUI": "UNVERIFIED",
45
+ "deliveredApk": "Unchanged 0.7.2+8 from CI39170095124, not the fixture APK",
46
+ "mergeDeployLiveChanges": "Not performed"
47
+}
docs/operations/ANDROID_REMINDER_ACCEPTANCE.md
new
+34
@@ -0,0 +1,34 @@
1
+# آزمون اعلان در شبیهساز Android
2
+
3
+این بسته فقط آزمون است؛ APK تحویلی0.7.2+8، Backend، حریم خصوصی، ورود و سرویس زنده را تغییر نمیدهد. هیچ تماس، حساب یا دادهٔ واقعی استفاده نمیشود. دریافت اعلان در شبیهساز، پذیرش گوشی واقعی یا اتصال آنلاین کودک محسوب نمیشود.
4
+
5
+## مرز fixture
6
+
7
+entry point مستقل `apps/lifemate/tool/native_reminder_fixture.dart` فقط در debug و با `LG_NATIVE_REMINDER_FIXTURE=true` کار میکند. برنامهٔ اصلی آن را import نمیکند. این APK را نصب دستی یا توزیع نکنید؛ workflow آن را upload نمیکند. شناسهٔ بسته همان برنامه است، به همین دلیل harness **هر بستهٔ از قبل نصبشده و هر دستگاه فیزیکی را رد میکند**. فقط AVD تازه، پاک و یکبارمصرف قابل استفاده است.
8
+
9
+تأیید رکورد در این fixture **شبیهسازیشده** است و در JSON با `simulatedServerAcknowledgement:true` مشخص میشود؛ هیچ API، نشست یا تأیید واقعی سروری در آزمون نیست. پورت Dart و AlarmManager/NotificationManager اصلی بدون تغییر استفاده میشوند. UI یک متن canary ساختگی دارد؛ اعلان باید فقط نام همراه ساختگی و متن عمومی مجاز داشته باشد.
10
+
11
+## اجرای قابل تکرار
12
+
13
+پیشنیاز: Flutter3.47.6، Python3، Android SDK/adb و یک AVD تازه Android35 با سختافزار `ranchu/goldfish`؛ گوشی مالک را به این آزمون وصل نکنید. خود workflow با `-wipe-data -no-snapshot` شبیهساز تازه میسازد.
14
+
15
+```sh
16
+cd apps/lifemate
17
+flutter pub get
18
+flutter test
19
+python3 -m unittest discover -s tool -p 'test_native_reminders_android_test.py' -v
20
+flutter build apk --debug --target=tool/native_reminder_fixture.dart --dart-define=LG_NATIVE_REMINDER_FIXTURE=true
21
+python3 tool/test_native_reminders_android.py --serial emulator-5554 --apk build/app/outputs/flutter-apk/app-debug.apk --allow-synthetic-emulator-reset --output exports/native-reminders-android.json
22
+```
23
+
24
+harness به serial صریح، تأیید محیط ساختگی، manifest debug با شناسهٔ درست، وضعیت device، مشخصات emulator، API35 و نبود بسته پیش از نصب نیاز دارد. مجوز notification و exact alarm از adb فقط روی همین AVD داده میشود؛ **این کار آزمون جریان رضایت UI نیست**.
25
+
26
+سناریوها: زمانبندی ← Home و `am kill` با اثبات نبود PID ← مشاهدهٔ اعلان واقعی سیستم ← بازکردن inspect بدون activate و بررسی بقای اعلان/وضعیت delivered در preference بومی ← لغو اعلان نمایشدادهشده ← لغو مورد آینده و عبور از موعد بدون اعلان ← مجوز exact خاموش و ثبت وضعیت approximate ← خاموشکردن و پاکشدن وضعیت.
27
+
28
+هیچ `force-stop`، broadcast دستی به receiver خصوصی، پاککردن logcat، uninstall یا kill-server استفاده نمیشود. برای تشخیص اعلان فعال از `cmd notification list` استفاده میشود؛ dump خام سیستم یا preference در خروجی ذخیره نمیشود. فقط receipt محدود با نتیجه و شمارندههای ساختگی upload میشود.
29
+
30
+## خواندن نتیجه و حدود اعتبار
31
+
32
+فقط `PASS` در receipt و exit0 اجرای واقعی، نتیجهٔ همان شبیهساز را تأیید میکند. unit testها فقط منطق ابزار و دروازههای ایمنی را تأیید میکنند. شکست پیشنیاز یا timeout را موفقیت حساب نکنید. exact و approximate جدا گزارش میشوند؛ ثبت approximate، تضمین تحویل آن در چند ثانیه نیست.
33
+
34
+**UNVERIFIED:** نصب/ارتقای گوشی واقعی، صدا و لرزش، صفحهٔ قفل سازنده، reboot، Doze/محدودیت باتری، اجازهٔ واقعی کاربر، iPhone/Safari/PWA، شبکهٔ ایران، تأیید سرور و ورود خصوصی مستقل کودک. نتیجهٔ اجرا و دستور/خروجی در گزارش همین PR ثبت میشود؛ قبل از اجرای CI، خود سناریوی Android نیز UNVERIFIED است.