LifeMate — Personal, Family & Learning Companion
test/android-reminder-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
| 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 | self.background_delay = 0 |
| 53 | self.background_ready_at = 0 |
| 54 | self.pid_states = [] |
| 55 | self.restore_retained_task = False |
| 56 | self.retained_route = None |
| 57 | |
| 58 | def clock(self): |
| 59 | return self.elapsed |
| 60 | |
| 61 | def epoch(self): |
| 62 | return 1800000000000 + int(self.elapsed * 1000) |
| 63 | |
| 64 | def sleep(self, seconds): |
| 65 | self.elapsed += seconds |
| 66 | if self.state and self.exact: |
| 67 | for row in self.state["reminders"]: |
| 68 | if not row.get("delivered") and row["scheduledAtEpochMs"] <= self.epoch(): |
| 69 | row["delivered"] = True |
| 70 | self.posted = True |
| 71 | self.alive = True # The native receiver may start its process. |
| 72 | |
| 73 | def status(self): |
| 74 | return {"supported": True, "permissionGranted": True, |
| 75 | "active": self.state is not None, |
| 76 | "activeScope": subject.SCOPE if self.state else None, |
| 77 | "scheduledCount": sum(row["scheduledAtEpochMs"] > self.epoch() |
| 78 | for row in self.state["reminders"]) if self.state else 0, |
| 79 | "timing": "exact" if self.exact else "approximate", |
| 80 | "canScheduleExactAlarms": self.exact} |
| 81 | |
| 82 | def key(self): |
| 83 | return f"0|{subject.PACKAGE}|1|lifeguide-plan:{subject.REMINDER}|10123" |
| 84 | |
| 85 | def command(self, *parts, allow_failure=False): |
| 86 | self.calls.append(parts) |
| 87 | if parts[0] == "logcat": |
| 88 | return "\n".join(self.markers) |
| 89 | if parts[:4] == ("shell", "cmd", "appops", "set"): |
| 90 | self.exact = parts[-1] == "allow" |
| 91 | if parts == ("shell", "input", "keyevent", "KEYCODE_HOME"): |
| 92 | self.background_ready_at = self.elapsed + self.background_delay |
| 93 | return "" |
| 94 | if parts == ("shell", "am", "kill", subject.PACKAGE): |
| 95 | if self.refuse_kill: |
| 96 | self.alive = True |
| 97 | elif self.elapsed >= self.background_ready_at: |
| 98 | self.alive = False |
| 99 | return "" |
| 100 | if parts == ("shell", "pidof", subject.PACKAGE): |
| 101 | if self.pid_query_failure: |
| 102 | return "" |
| 103 | return "123\n" if self.alive else "" |
| 104 | if parts[:3] == ("shell", "sh", "-c"): |
| 105 | if self.pid_query_failure: |
| 106 | return "" |
| 107 | state = "PRESENT" if self.alive else "ABSENT" |
| 108 | self.pid_states.append(state) |
| 109 | return state |
| 110 | if parts == ("shell", "date", "+%s"): |
| 111 | return str(self.epoch() // 1000) |
| 112 | if parts[:3] == ("shell", "run-as", subject.PACKAGE): |
| 113 | if self.state is None: |
| 114 | return "<map/>" |
| 115 | return '<map><string name="active">' + escape(json.dumps(self.state)) + '</string></map>' |
| 116 | if parts == ("shell", "cmd", "notification", "list"): |
| 117 | return self.key() + "\n" if self.posted else "" |
| 118 | if parts[:3] == ("shell", "dumpsys", "notification"): |
| 119 | body = subject.CANARY if self.private_body else subject.GENERIC_BODY |
| 120 | return (f"NotificationRecord(pkg={subject.PACKAGE} key={self.key()})\n" |
| 121 | f" channel={subject.CHANNEL}\n" |
| 122 | f" android.title=String ({subject.COMPANION})\n" |
| 123 | f" android.text=String ({body})\n") |
| 124 | if parts[:3] == ("shell", "am", "start"): |
| 125 | # Android 15 Intent.parseCommandArgs has -f and clear-task, but |
| 126 | # rejects the nonexistent --activity-new-task named option. |
| 127 | if "--activity-new-task" in parts: |
| 128 | raise subject.AcceptanceError("adb_command_failed") |
| 129 | self.alive = True |
| 130 | flags = int(parts[parts.index("-f") + 1], 0) if "-f" in parts else 0 |
| 131 | fresh_task = flags & 0x10008000 == 0x10008000 |
| 132 | if not self.restore_retained_task or fresh_task or self.retained_route is None: |
| 133 | self.retained_route = parts[-1] |
| 134 | route = urlparse(self.retained_route) |
| 135 | mode = route.path.removeprefix("/") |
| 136 | query = parse_qs(route.query) |
| 137 | self.modes.append(mode) |
| 138 | if mode == "schedule": |
| 139 | self.generation += 1 |
| 140 | self.state = { |
| 141 | "scope": subject.SCOPE, |
| 142 | "generation": f"{self.generation:08x}-4444-4444-8444-444444444444", |
| 143 | "issuedAtEpochMs": self.epoch(), |
| 144 | "validUntilEpochMs": self.epoch() + 600000, |
| 145 | "reminders": [{"id": subject.REMINDER, "planItemId": subject.PLAN, |
| 146 | "companionName": subject.COMPANION, |
| 147 | "scheduledAtEpochMs": self.epoch() + 45000}], |
| 148 | } |
| 149 | self.posted = False |
| 150 | elif mode == "suppress" and self.state: |
| 151 | self.state["reminders"] = [] |
| 152 | self.posted = False |
| 153 | elif mode == "off": |
| 154 | self.state = None |
| 155 | self.posted = False |
| 156 | marker = {"nonce": query["nonce"][0], "mode": mode, |
| 157 | "status": self.status(), "simulatedServerAcknowledgement": True} |
| 158 | if mode == "schedule": |
| 159 | marker["scheduledAtEpochMs"] = self.state["reminders"][0]["scheduledAtEpochMs"] |
| 160 | self.markers.append(subject.MARKER + json.dumps(marker)) |
| 161 | return "Success" |
| 162 | return self.responses.get(parts, "") |
| 163 | |
| 164 | |
| 165 | class PreflightTest(unittest.TestCase): |
| 166 | def setUp(self): |
| 167 | self.directory = tempfile.TemporaryDirectory() |
| 168 | self.addCleanup(self.directory.cleanup) |
| 169 | self.apk = Path(self.directory.name) / "fixture.apk" |
| 170 | self.apk.write_bytes(b"synthetic APK placeholder; manifest check is mocked") |
| 171 | self.manifest = { |
| 172 | "result": "PASS", "mode": "debug", "package": subject.PACKAGE, |
| 173 | "debuggable": True, "targetSdkVersion": 36, "sha256": "a" * 64, |
| 174 | } |
| 175 | |
| 176 | def harness(self, adb, **overrides): |
| 177 | values = dict(serial="emulator-5554", apk=self.apk, allow_reset=True, |
| 178 | adb=adb, manifest_check=lambda path, mode: self.manifest) |
| 179 | values.update(overrides) |
| 180 | return subject.Harness(**values) |
| 181 | |
| 182 | def assert_read_only(self, adb): |
| 183 | for parts in adb.calls: |
| 184 | self.assertNotEqual(parts[0], "install") |
| 185 | if parts[0] == "shell": |
| 186 | self.assertIn(parts[1:3], [("getprop", "ro.kernel.qemu"), |
| 187 | ("getprop", "ro.boot.qemu"), ("getprop", "ro.hardware"), |
| 188 | ("getprop", "ro.product.name"), ("getprop", "ro.build.version.sdk"), |
| 189 | ("pm", "list")]) |
| 190 | |
| 191 | def test_physical_serial_refused_before_any_adb_call(self): |
| 192 | for serial in ("R58REALDEVICE", "", "emulator-5554;echo bad", "emulator-5554\n"): |
| 193 | with self.subTest(serial=serial): |
| 194 | adb = FakeAdb() |
| 195 | with self.assertRaises(subject.AcceptanceError): |
| 196 | self.harness(adb, serial=serial).install_fixture() |
| 197 | self.assertEqual(adb.calls, []) |
| 198 | |
| 199 | def test_reset_confirmation_required_before_any_adb_call(self): |
| 200 | adb = FakeAdb() |
| 201 | with self.assertRaises(subject.AcceptanceError): |
| 202 | self.harness(adb, allow_reset=False).install_fixture() |
| 203 | self.assertEqual(adb.calls, []) |
| 204 | |
| 205 | def test_missing_apk_refused_before_any_adb_call(self): |
| 206 | adb = FakeAdb() |
| 207 | with self.assertRaises(subject.AcceptanceError): |
| 208 | self.harness(adb, apk=self.apk.with_name("missing.apk")).install_fixture() |
| 209 | self.assertEqual(adb.calls, []) |
| 210 | |
| 211 | def test_bad_manifest_refused_before_any_adb_call(self): |
| 212 | adb = FakeAdb() |
| 213 | def reject(path, mode): |
| 214 | raise ValueError("do not expose arbitrary checker output") |
| 215 | with self.assertRaisesRegex(subject.AcceptanceError, "apk_manifest_rejected"): |
| 216 | self.harness(adb, manifest_check=reject).install_fixture() |
| 217 | self.assertEqual(adb.calls, []) |
| 218 | |
| 219 | def test_non_debug_or_wrong_target_manifest_is_rejected(self): |
| 220 | for changes in ({"debuggable": False}, {"targetSdkVersion": 35}, {"package": "other.app"}): |
| 221 | adb = FakeAdb() |
| 222 | with self.subTest(changes=changes): |
| 223 | with self.assertRaises(subject.AcceptanceError): |
| 224 | self.harness(adb, manifest_check=lambda path, mode: self.manifest | changes).install_fixture() |
| 225 | self.assertEqual(adb.calls, []) |
| 226 | |
| 227 | def test_each_emulator_gate_prevents_mutation(self): |
| 228 | cases = [ |
| 229 | {("get-state",): "offline\n"}, |
| 230 | {("shell", "getprop", "ro.kernel.qemu"): "", ("shell", "getprop", "ro.boot.qemu"): "0"}, |
| 231 | {("shell", "getprop", "ro.hardware"): "real-phone-chip"}, |
| 232 | {("shell", "getprop", "ro.product.name"): "owners_phone"}, |
| 233 | {("shell", "getprop", "ro.build.version.sdk"): "34"}, |
| 234 | {("shell", "pm", "list", "packages", subject.PACKAGE): "package:ir.lifeguide.app\n"}, |
| 235 | ] |
| 236 | for responses in cases: |
| 237 | with self.subTest(responses=responses): |
| 238 | adb = FakeAdb(responses) |
| 239 | with self.assertRaises(subject.AcceptanceError): |
| 240 | self.harness(adb).install_fixture() |
| 241 | self.assert_read_only(adb) |
| 242 | |
| 243 | def test_install_follows_all_gates_and_no_other_package_is_touched(self): |
| 244 | adb = FakeAdb() |
| 245 | self.harness(adb).install_fixture() |
| 246 | install_index = next(i for i, parts in enumerate(adb.calls) if parts[0] == "install") |
| 247 | self.assertIn(("shell", "pm", "list", "packages", subject.PACKAGE), adb.calls[:install_index]) |
| 248 | self.assertIn(("shell", "pm", "grant", subject.PACKAGE, "android.permission.POST_NOTIFICATIONS"), adb.calls) |
| 249 | self.assertIn(("shell", "cmd", "appops", "set", subject.PACKAGE, "SCHEDULE_EXACT_ALARM", "allow"), adb.calls) |
| 250 | flattened = " ".join(" ".join(parts) for parts in adb.calls) |
| 251 | for forbidden in ("force-stop", "kill-server", "uninstall", "logcat -c"): |
| 252 | self.assertNotIn(forbidden, flattened) |
| 253 | |
| 254 | |
| 255 | class ParsingTest(unittest.TestCase): |
| 256 | def key(self, reminder=subject.REMINDER): |
| 257 | return f"0|{subject.PACKAGE}|1|lifeguide-plan:{reminder}|10123" |
| 258 | |
| 259 | def test_active_keys_only_recognize_exact_package_id_and_tag(self): |
| 260 | own = self.key() |
| 261 | output = "\n".join((own, "0|other.app|1|lifeguide-plan:private|10124", |
| 262 | f"0|{subject.PACKAGE}.fake|1|lifeguide-plan:{subject.REMINDER}|10125")) |
| 263 | self.assertEqual(subject.active_fixture_keys(output), [own]) |
| 264 | self.assertEqual(subject.active_fixture_keys("no active keys\n"), []) |
| 265 | |
| 266 | def test_unknown_own_notification_is_refused_without_echoing_it(self): |
| 267 | with self.assertRaisesRegex(subject.AcceptanceError, "unexpected_fixture_notification") as caught: |
| 268 | subject.active_fixture_keys(f"0|{subject.PACKAGE}|9|private-user-title|10123") |
| 269 | self.assertNotIn("private-user-title", str(caught.exception)) |
| 270 | |
| 271 | def test_notification_check_uses_matching_record_only(self): |
| 272 | key = self.key() |
| 273 | dump = ("Notification List:\n NotificationRecord(pkg=other.app key=other)\n" |
| 274 | " android.text=String (SYNTHETIC_PRIVATE_TASK_CANARY)\n" |
| 275 | f" NotificationRecord(pkg={subject.PACKAGE} key={key})\n" |
| 276 | f" android.title=String ({subject.COMPANION})\n" |
| 277 | f" android.text=String ({subject.GENERIC_BODY})\n") |
| 278 | result = subject.check_notification_record(dump, key) |
| 279 | self.assertEqual(result, {"titleMatches": True, "genericBodyMatches": True, |
| 280 | "privateCanaryAbsent": True}) |
| 281 | self.assertNotIn("other.app", json.dumps(result)) |
| 282 | |
| 283 | def test_notification_canary_or_wrong_body_fails(self): |
| 284 | for body in ("wrong body", subject.GENERIC_BODY + " SYNTHETIC_PRIVATE_TASK_CANARY"): |
| 285 | dump = (f"NotificationRecord(pkg={subject.PACKAGE} key={self.key()})\n" |
| 286 | f"android.title=String ({subject.COMPANION})\nandroid.text=String ({body})") |
| 287 | with self.assertRaises(subject.AcceptanceError): |
| 288 | subject.check_notification_record(dump, self.key()) |
| 289 | |
| 290 | def test_android_record_key_terminator_and_channel_are_recognized(self): |
| 291 | dump = (f" NotificationRecord(abc: pkg={subject.PACKAGE} user=UserHandle{{0}} " |
| 292 | f"id=1 key={self.key()}: Notification(channel={subject.CHANNEL} vis=PRIVATE))\n" |
| 293 | f" android.title=String ({subject.COMPANION})\n" |
| 294 | f" android.text=String ({subject.GENERIC_BODY})\n") |
| 295 | result = subject.check_notification_record(dump, self.key(), require_channel=True) |
| 296 | self.assertTrue(result["genericBodyMatches"]) |
| 297 | |
| 298 | def test_marker_requires_nonce_mode_fixture_scope_and_simulation_label(self): |
| 299 | marker = {"nonce": "0123456789abcdef", "mode": "inspect", "simulatedServerAcknowledgement": True, |
| 300 | "status": {"supported": True, "permissionGranted": True, "active": True, |
| 301 | "activeScope": subject.SCOPE, "scheduledCount": 0, "timing": "exact", |
| 302 | "canScheduleExactAlarms": True}} |
| 303 | line = "I/flutter (123): LG_NATIVE_REMINDER_FIXTURE " + json.dumps(marker) |
| 304 | self.assertEqual(subject.fixture_marker(line, marker["nonce"], "inspect")["status"]["scheduledCount"], 0) |
| 305 | self.assertIsNone(subject.fixture_marker(line, "a" * 16, "inspect")) |
| 306 | for change in ({"simulatedServerAcknowledgement": False}, |
| 307 | {"status": marker["status"] | {"activeScope": "real-user-scope"}}): |
| 308 | with self.assertRaises(subject.AcceptanceError): |
| 309 | subject.fixture_marker("LG_NATIVE_REMINDER_FIXTURE " + json.dumps(marker | change), marker["nonce"], "inspect") |
| 310 | |
| 311 | def test_incomplete_or_inconsistent_status_is_a_sanitized_failure(self): |
| 312 | status = {"supported": True, "permissionGranted": True, "active": False, |
| 313 | "activeScope": None, "scheduledCount": 0, "timing": "exact", |
| 314 | "canScheduleExactAlarms": True} |
| 315 | for broken in ({key: value for key, value in status.items() if key != "activeScope"}, |
| 316 | status | {"canScheduleExactAlarms": False}): |
| 317 | marker = {"nonce": "0123456789abcdef", "mode": "inspect", "status": broken, |
| 318 | "simulatedServerAcknowledgement": True} |
| 319 | with self.subTest(status=broken): |
| 320 | with self.assertRaises(subject.AcceptanceError): |
| 321 | subject.fixture_marker(subject.MARKER + json.dumps(marker), marker["nonce"], "inspect") |
| 322 | |
| 323 | def test_native_preferences_only_accept_known_synthetic_payload(self): |
| 324 | state = {"scope": subject.SCOPE, "generation": "44444444-4444-4444-8444-444444444444", |
| 325 | "issuedAtEpochMs": 1800000000000, "validUntilEpochMs": 1800000600000, |
| 326 | "reminders": [{"id": subject.REMINDER, "planItemId": subject.PLAN, |
| 327 | "scheduledAtEpochMs": 1800000045000, |
| 328 | "companionName": subject.COMPANION, "delivered": True}]} |
| 329 | from xml.sax.saxutils import escape |
| 330 | xml = '<map><string name="active">' + escape(json.dumps(state)) + '</string></map>' |
| 331 | parsed = subject.parse_preferences(xml) |
| 332 | self.assertTrue(parsed["reminders"][0]["delivered"]) |
| 333 | self.assertIsNone(subject.parse_preferences('<map/>')) |
| 334 | state["reminders"][0]["companionName"] = "real private task text" |
| 335 | with self.assertRaisesRegex(subject.AcceptanceError, "unexpected_fixture_preferences") as caught: |
| 336 | subject.parse_preferences('<map><string name="active">' + escape(json.dumps(state)) + '</string></map>') |
| 337 | self.assertNotIn("real private task text", str(caught.exception)) |
| 338 | |
| 339 | def test_adb_shell_quoting_keeps_initial_route_a_single_argument(self): |
| 340 | completed = type("Completed", (), {"returncode": 0, "stdout": "", "stderr": ""})() |
| 341 | with patch.object(subject.subprocess, "run", return_value=completed) as run: |
| 342 | subject.Adb("emulator-5554").shell("am", "start", "--es", "route", "/schedule?nonce=abc12345&delay=45") |
| 343 | arguments = run.call_args.args[0] |
| 344 | self.assertEqual(arguments[:4], ["adb", "-s", "emulator-5554", "shell"]) |
| 345 | self.assertIn("'/schedule?nonce=abc12345&delay=45'", arguments[4]) |
| 346 | |
| 347 | |
| 348 | class LifecycleTest(unittest.TestCase): |
| 349 | def harness(self, adb): |
| 350 | directory = tempfile.TemporaryDirectory() |
| 351 | self.addCleanup(directory.cleanup) |
| 352 | apk = Path(directory.name) / "fixture.apk" |
| 353 | apk.write_bytes(b"synthetic only") |
| 354 | manifest = {"result": "PASS", "mode": "debug", "package": subject.PACKAGE, |
| 355 | "debuggable": True, "targetSdkVersion": 36, "sha256": "a" * 64} |
| 356 | return subject.Harness(serial="emulator-5554", apk=apk, allow_reset=True, adb=adb, |
| 357 | manifest_check=lambda path, mode: manifest, |
| 358 | clock=adb.clock, sleep=adb.sleep) |
| 359 | |
| 360 | def test_full_sequence_with_virtual_time_finishes_off_and_labels_limits(self): |
| 361 | adb = SyntheticEmulator() |
| 362 | receipt = self.harness(adb).run() |
| 363 | self.assertEqual(receipt["result"], "PASS") |
| 364 | self.assertEqual(adb.modes, ["inspect", "schedule", "inspect", "suppress", |
| 365 | "schedule", "suppress", "schedule", "off"]) |
| 366 | self.assertGreaterEqual(adb.elapsed, 95) |
| 367 | self.assertIsNone(adb.state) |
| 368 | self.assertFalse(adb.posted) |
| 369 | self.assertFalse(adb.exact) |
| 370 | self.assertTrue(all(value == "UNVERIFIED" for value in receipt["limitations"].values())) |
| 371 | self.assertEqual(receipt["checks"]["approximateAlarmDeliveryTiming"], "UNVERIFIED") |
| 372 | self.assertEqual(receipt["checks"]["notificationContent"]["privateCanaryAbsent"], True) |
| 373 | serialized = json.dumps(receipt) |
| 374 | self.assertNotIn(subject.CANARY, serialized) |
| 375 | self.assertNotIn("NotificationRecord", serialized) |
| 376 | self.assertNotIn("<map", serialized) |
| 377 | for index, parts in enumerate(adb.calls): |
| 378 | if parts[:3] == ("shell", "am", "start"): |
| 379 | self.assertEqual(adb.calls[index - 3:index], [ |
| 380 | ("shell", "input", "keyevent", "KEYCODE_HOME"), |
| 381 | ("shell", "am", "kill", subject.PACKAGE), |
| 382 | ("shell", "sh", "-c", subject.PID_QUERY)]) |
| 383 | commands = " ".join(" ".join(parts) for parts in adb.calls) |
| 384 | for forbidden in ("force-stop", "kill-server", "uninstall", "logcat -c"): |
| 385 | self.assertNotIn(forbidden, commands) |
| 386 | |
| 387 | def test_new_mode_replaces_retained_task_initial_route(self): |
| 388 | adb = SyntheticEmulator() |
| 389 | adb.restore_retained_task = True |
| 390 | receipt = self.harness(adb).run() |
| 391 | self.assertEqual(receipt["result"], "PASS") |
| 392 | self.assertEqual(adb.modes, ["inspect", "schedule", "inspect", "suppress", |
| 393 | "schedule", "suppress", "schedule", "off"]) |
| 394 | for parts in adb.calls: |
| 395 | if parts[:3] == ("shell", "am", "start"): |
| 396 | self.assertNotIn("--activity-new-task", parts) |
| 397 | self.assertEqual(parts[parts.index("-f") + 1], "0x10008000") |
| 398 | self.assertIn(subject.PACKAGE + "/.MainActivity", parts) |
| 399 | |
| 400 | def test_marker_timeout_reports_only_known_modes_and_error_boolean(self): |
| 401 | class StaleFixtureLogs(SyntheticEmulator): |
| 402 | def command(self, *parts, allow_failure=False): |
| 403 | if parts[0] == "logcat": |
| 404 | self.calls.append(parts) |
| 405 | return "\n".join([ |
| 406 | subject.MARKER + json.dumps({"nonce": "0123456789abcdef", |
| 407 | "mode": "inspect", "untrusted": subject.CANARY}), |
| 408 | subject.MARKER + json.dumps({"nonce": "0123456789abcdef", |
| 409 | "mode": "private-user-task"}), |
| 410 | "LG_NATIVE_REMINDER_FIXTURE_ERROR private-error-details", |
| 411 | ]) |
| 412 | return super().command(*parts, allow_failure=allow_failure) |
| 413 | |
| 414 | adb = StaleFixtureLogs() |
| 415 | harness = self.harness(adb) |
| 416 | harness.install_fixture() |
| 417 | with self.assertRaisesRegex(subject.AcceptanceError, "fixture_marker_timeout"): |
| 418 | harness.launch("schedule") |
| 419 | self.assertEqual(harness.receipt["currentPhase"], "waiting_schedule_marker") |
| 420 | self.assertEqual(harness.receipt["fixtureLogObservationScope"], "retained_logcat_buffer") |
| 421 | self.assertEqual(harness.receipt["observedFixtureModes"], ["inspect"]) |
| 422 | self.assertIs(harness.receipt["fixtureErrorSeen"], True) |
| 423 | serialized = json.dumps(harness.receipt) |
| 424 | for forbidden in (subject.CANARY, "private-user-task", "private-error-details", |
| 425 | "0123456789abcdef"): |
| 426 | self.assertNotIn(forbidden, serialized) |
| 427 | |
| 428 | def test_process_claim_fails_when_pid_remains(self): |
| 429 | adb = SyntheticEmulator() |
| 430 | adb.refuse_kill = True |
| 431 | harness = self.harness(adb) |
| 432 | with self.assertRaisesRegex(subject.AcceptanceError, "fixture_process_did_not_exit"): |
| 433 | harness.run() |
| 434 | self.assertEqual(adb.modes, []) |
| 435 | self.assertEqual(harness.receipt["currentPhase"], "before_launch_inspect") |
| 436 | self.assertEqual(harness.receipt["lastProcessState"], "PRESENT") |
| 437 | self.assertNotIn("processExit", harness.receipt) |
| 438 | |
| 439 | def test_retries_ordinary_kill_after_home_background_transition(self): |
| 440 | adb = SyntheticEmulator() |
| 441 | adb.background_delay = 1 |
| 442 | adb.alive = True |
| 443 | harness = self.harness(adb) |
| 444 | harness.install_fixture() |
| 445 | self.assertTrue(harness.process_dead()) |
| 446 | self.assertFalse(adb.alive) |
| 447 | self.assertEqual(adb.pid_states[0], "PRESENT") |
| 448 | self.assertEqual(adb.pid_states[-1], "ABSENT") |
| 449 | self.assertGreaterEqual(adb.elapsed, adb.background_delay) |
| 450 | self.assertLessEqual(adb.elapsed, 10) |
| 451 | kills = [parts for parts in adb.calls |
| 452 | if parts == ("shell", "am", "kill", subject.PACKAGE)] |
| 453 | self.assertGreater(len(kills), 1) |
| 454 | self.assertEqual(harness.receipt["processExit"], { |
| 455 | "confirmedAbsent": True, "ordinaryKillAttempts": len(kills)}) |
| 456 | |
| 457 | def test_late_process_absence_cannot_claim_death_before_alarm(self): |
| 458 | class SlowScheduledKill(SyntheticEmulator): |
| 459 | delayed = False |
| 460 | |
| 461 | def command(self, *parts, allow_failure=False): |
| 462 | if (parts == ("shell", "am", "kill", subject.PACKAGE) and |
| 463 | self.state and self.state["reminders"] and not self.delayed): |
| 464 | self.delayed = True |
| 465 | self.sleep(46) # The modeled receiver posts before kill completes. |
| 466 | return super().command(*parts, allow_failure=allow_failure) |
| 467 | |
| 468 | adb = SlowScheduledKill() |
| 469 | harness = self.harness(adb) |
| 470 | with self.assertRaisesRegex(subject.AcceptanceError, "process_absence_missed_alarm_deadline"): |
| 471 | harness.run() |
| 472 | self.assertTrue(adb.posted) |
| 473 | self.assertEqual(harness.receipt["currentPhase"], "after_schedule_created") |
| 474 | self.assertNotIn("processAbsentBeforeAlarm", harness.receipt["checks"]) |
| 475 | |
| 476 | def test_empty_failed_pid_query_cannot_claim_process_absence(self): |
| 477 | adb = SyntheticEmulator() |
| 478 | adb.pid_query_failure = True |
| 479 | with self.assertRaisesRegex(subject.AcceptanceError, "fixture_process_query_failed"): |
| 480 | self.harness(adb).run() |
| 481 | self.assertEqual(adb.modes, []) |
| 482 | |
| 483 | def test_os_post_with_private_body_fails_without_echoing_body(self): |
| 484 | adb = SyntheticEmulator() |
| 485 | adb.private_body = True |
| 486 | with self.assertRaises(subject.AcceptanceError) as caught: |
| 487 | self.harness(adb).run() |
| 488 | self.assertNotIn(subject.CANARY, str(caught.exception)) |
| 489 | |
| 490 | def test_cli_refusal_writes_only_sanitized_receipt_without_adb(self): |
| 491 | directory = tempfile.TemporaryDirectory() |
| 492 | self.addCleanup(directory.cleanup) |
| 493 | output = Path(directory.name) / "receipt.json" |
| 494 | with patch.object(subject, "Adb") as adb, contextlib.redirect_stdout(io.StringIO()): |
| 495 | exit_code = subject.main(["--serial", "REAL_PHONE", "--apk", "/nonexistent.apk", |
| 496 | "--allow-synthetic-emulator-reset", "--output", str(output)]) |
| 497 | self.assertEqual(exit_code, 1) |
| 498 | adb.assert_not_called() |
| 499 | receipt = json.loads(output.read_text()) |
| 500 | self.assertEqual(receipt["result"], "FAIL") |
| 501 | self.assertEqual(receipt["error"], "explicit_emulator_serial_required") |
| 502 | self.assertNotIn("REAL_PHONE", output.read_text()) |
| 503 | |
| 504 | |
| 505 | if __name__ == "__main__": |
| 506 | unittest.main() |