LifeMate — Personal, Family & Learning Companion
docs/offline-data-rescue-options
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 | #!/usr/bin/env python3 |
| 2 | """Bounded, synthetic acceptance of the real device-only SQLite/Android path. |
| 3 | |
| 4 | Only a fresh API35 SDK emulator is accepted. Install the deliverable first and |
| 5 | capture its ordinary onboarding launch, then upgrade that owned install to the |
| 6 | separately built, never-distributed fixture with the identical certificate. |
| 7 | No uninstall, data clearing, force-stop, or network service is used. |
| 8 | """ |
| 9 | import argparse |
| 10 | import hashlib |
| 11 | import json |
| 12 | import os |
| 13 | import re |
| 14 | import secrets |
| 15 | import shutil |
| 16 | import struct |
| 17 | import subprocess |
| 18 | import time |
| 19 | import uuid |
| 20 | import xml.etree.ElementTree as ET |
| 21 | from pathlib import Path |
| 22 | |
| 23 | # Reuse transport and the strict serial boundary without changing the online |
| 24 | # acceptance tool's fixed application identity or its regression tests. |
| 25 | from test_native_reminders_android import Adb, AcceptanceError, require, validate_serial |
| 26 | |
| 27 | PACKAGE = "ir.lifeguide.app.device" |
| 28 | COMPONENT = PACKAGE + "/ir.lifeguide.app.MainActivity" |
| 29 | LABEL = "لایفگاید شخصی" |
| 30 | SCOPE = "device-planner:v1:11111111-1111-4111-8111-111111111111" |
| 31 | DATABASE = "standalone_acceptance.sqlite" |
| 32 | COMPANION = "LifeGuide EMULATOR FIXTURE" |
| 33 | GENERIC_BODY = "برای دیدن برنامهٔ شخصی، لایفگاید را باز کنید." |
| 34 | CHANNEL = "lifeguide_personal_plan_v1" |
| 35 | CANARY = "SYNTHETIC_PRIVATE_TASK_CANARY" |
| 36 | MARKER = "LG_STANDALONE_ACCEPTANCE " |
| 37 | MODES = {"seed", "inspect", "change", "cancel", "off"} |
| 38 | CHECKS = {"rawSqlAfterClose", "profilePersists", "weeklyDifferentTimes", |
| 39 | "onceAndEveryTwoDays", "independentEditAndTick", "archivePersists"} |
| 40 | PREFERENCES = "shared_prefs/lifeguide_local_reminders_v1.xml" |
| 41 | UUID = r"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}" |
| 42 | PID_QUERY = ("pids=$(pidof " + PACKAGE + "); code=$?; " |
| 43 | "if [ \"$code\" -eq 0 ] && [ -n \"$pids\" ]; then printf PRESENT; " |
| 44 | "elif [ \"$code\" -eq 1 ] && [ -z \"$pids\" ]; then printf ABSENT; " |
| 45 | "else exit 2; fi") |
| 46 | LIMITATIONS = {name: "UNVERIFIED" for name in ( |
| 47 | "physicalDevice", "reboot", "Doze", "soundOrVibration", "permissionConsentUI", |
| 48 | "Safari", "signedRelease", "onlineFamilyOrSynchronization")} |
| 49 | |
| 50 | |
| 51 | def _positive(value): |
| 52 | return type(value) is int and value > 0 |
| 53 | |
| 54 | |
| 55 | def manifest_check(apk): |
| 56 | # Kept lazy so host safety tests need no APK inspection/build dependency. |
| 57 | from check_standalone_apk import check |
| 58 | return check(apk) |
| 59 | |
| 60 | |
| 61 | def certificate_digest(apk): |
| 62 | signer = shutil.which("apksigner") |
| 63 | if signer is None: |
| 64 | for key in ("ANDROID_HOME", "ANDROID_SDK_ROOT"): |
| 65 | root = os.environ.get(key) |
| 66 | if root: |
| 67 | choices = sorted((Path(root) / "build-tools").glob("*/apksigner")) |
| 68 | if choices: |
| 69 | signer = str(choices[-1]) |
| 70 | break |
| 71 | require(signer is not None, "apksigner_required") |
| 72 | try: |
| 73 | result = subprocess.run([signer, "verify", "--print-certs", str(apk)], |
| 74 | capture_output=True, text=True, timeout=30, check=False) |
| 75 | values = re.findall(r"(?m)^(?:Signer #\d+|V[1-4](?:\.\d+)? Signer:) certificate SHA-256 digest: ([0-9a-fA-F]{64})\s*$", result.stdout) |
| 76 | require(result.returncode == 0 and len(values) == 1, "apk_signature_rejected") |
| 77 | return values[0].lower() |
| 78 | except (OSError, subprocess.SubprocessError): |
| 79 | raise AcceptanceError("apk_signature_rejected") from None |
| 80 | |
| 81 | |
| 82 | def fixture_marker(line, nonce, mode): |
| 83 | require(re.fullmatch(r"[0-9a-f]{8,32}", nonce) is not None and mode in MODES, |
| 84 | "invalid_fixture_request") |
| 85 | if MARKER not in line: |
| 86 | return None |
| 87 | raw = line.split(MARKER, 1)[1] |
| 88 | try: |
| 89 | marker = json.loads(raw) |
| 90 | except ValueError: |
| 91 | if nonce in raw: |
| 92 | raise AcceptanceError("invalid_fixture_marker") from None |
| 93 | return None |
| 94 | if not isinstance(marker, dict) or marker.get("nonce") != nonce: |
| 95 | return None |
| 96 | require(marker.get("mode") == mode and marker.get("syntheticDataOnly") is True |
| 97 | and marker.get("database") == DATABASE, "invalid_fixture_marker") |
| 98 | status = marker.get("status") |
| 99 | required = {"supported", "permissionGranted", "active", "activeScope", "enabled", |
| 100 | "scheduledCount", "timing", "canScheduleExactAlarms"} |
| 101 | require(isinstance(status, dict) and required <= set(status), "invalid_fixture_status") |
| 102 | require(status["supported"] is True and |
| 103 | all(type(status[k]) is bool for k in ("permissionGranted", "active", "enabled", "canScheduleExactAlarms")) |
| 104 | and type(status["scheduledCount"]) is int and status["scheduledCount"] in (0, 1) |
| 105 | and status["timing"] in ("exact", "approximate") |
| 106 | and status["canScheduleExactAlarms"] == (status["timing"] == "exact") |
| 107 | and (re.fullmatch("device-planner:v1:" + UUID, status["activeScope"] or "") is not None |
| 108 | if status["active"] else status["activeScope"] is None) |
| 109 | and (status["active"] or status["scheduledCount"] == 0), "invalid_fixture_status") |
| 110 | checks = marker.get("checks") |
| 111 | require(isinstance(checks, dict) and all(type(checks.get(k)) is bool for k in CHECKS & checks.keys()), |
| 112 | "invalid_fixture_database_checks") |
| 113 | clean = {"nonce": nonce, "mode": mode, "syntheticDataOnly": True, |
| 114 | "database": DATABASE, "status": {k: status[k] for k in sorted(required)}, |
| 115 | "checks": {k: checks[k] for k in sorted(CHECKS & checks.keys())}} |
| 116 | if "scheduledAtEpochMs" in marker: |
| 117 | require(mode in ("seed", "change") and _positive(marker["scheduledAtEpochMs"]), |
| 118 | "invalid_fixture_deadline") |
| 119 | clean["scheduledAtEpochMs"] = marker["scheduledAtEpochMs"] |
| 120 | return clean |
| 121 | |
| 122 | |
| 123 | def active_fixture_keys(output): |
| 124 | keys = [] |
| 125 | for line in output.splitlines(): |
| 126 | key = line.strip() |
| 127 | pieces = key.split("|") |
| 128 | if len(pieces) < 2 or pieces[1] != PACKAGE: |
| 129 | continue |
| 130 | require(len(pieces) == 5 and pieces[0] == "0" and pieces[2] == "1" and |
| 131 | re.fullmatch("lifeguide-plan:" + UUID, pieces[3]) is not None and |
| 132 | re.fullmatch(r"[0-9]+", pieces[4]) is not None and key not in keys, |
| 133 | "unexpected_fixture_notification") |
| 134 | keys.append(key) |
| 135 | require(len(keys) <= 1, "unexpected_fixture_notification") |
| 136 | return keys |
| 137 | |
| 138 | |
| 139 | def check_notification_record(dump, key): |
| 140 | require(active_fixture_keys(key) == [key], "invalid_fixture_notification_key") |
| 141 | records = re.split(r"(?m)(?=^[ \t]*NotificationRecord\()", dump) |
| 142 | matches = [r for r in records if |
| 143 | re.search(r"\bkey=" + re.escape(key) + r"(?=[\s):])", r) and |
| 144 | re.search(r"\bpkg=" + re.escape(PACKAGE) + r"(?=[\s)])", r)] |
| 145 | require(len(matches) == 1, "fixture_notification_record_missing_or_ambiguous") |
| 146 | record = matches[0] |
| 147 | titles = re.findall(r"android\.title=String \(([^\n]*)\)", record) |
| 148 | bodies = re.findall(r"android\.text=String \(([^\n]*)\)", record) |
| 149 | # Android dumps the private notification first and then its publicVersion. |
| 150 | # The latter deliberately uses the product name on the lock screen. |
| 151 | require(bool(titles) and titles[0] == COMPANION and |
| 152 | all(t == "LifeGuide" for t in titles[1:]), "fixture_notification_title_mismatch") |
| 153 | require(bool(bodies) and all(b == GENERIC_BODY for b in bodies), "fixture_notification_body_mismatch") |
| 154 | require(CANARY not in record, "fixture_notification_contains_private_canary") |
| 155 | require(re.search(r"(?:channel=|mId=['\"]?)" + re.escape(CHANNEL) + r"(?=['\"\s,)])", record), |
| 156 | "fixture_notification_channel_mismatch") |
| 157 | return {"titleMatches": True, "genericBodyMatches": True, "privateCanaryAbsent": True} |
| 158 | |
| 159 | |
| 160 | def parse_preferences(xml, *, expected_scope=None): |
| 161 | """Validate the isolated synthetic native state, never publish raw XML.""" |
| 162 | try: |
| 163 | require(len(xml) <= 32768 and "<!" not in xml, "unexpected_fixture_preferences") |
| 164 | root = ET.fromstring(xml) |
| 165 | require(root.tag == "map" and not root.attrib, "unexpected_fixture_preferences") |
| 166 | if len(root) == 0: |
| 167 | return None |
| 168 | require(len(root) == 1 and root[0].tag == "string" and |
| 169 | root[0].attrib == {"name": "active"} and len(root[0]) == 0, "unexpected_fixture_preferences") |
| 170 | state = json.loads(root[0].text or "") |
| 171 | require(isinstance(state, dict) and set(state) <= { |
| 172 | "scope", "generation", "issuedAtEpochMs", "validUntilEpochMs", "reminders", "deliveryExpired", "leaseKind"} |
| 173 | and re.fullmatch("device-planner:v1:" + UUID, state.get("scope", "")) is not None |
| 174 | and (expected_scope is None or state["scope"] == expected_scope) |
| 175 | and str(uuid.UUID(state["generation"], version=4)) == state["generation"] |
| 176 | and _positive(state.get("issuedAtEpochMs")) and _positive(state.get("validUntilEpochMs")) |
| 177 | and 0 < state["validUntilEpochMs"] - state["issuedAtEpochMs"] <= 31 * 86400000 |
| 178 | and state.get("leaseKind") == "device-planner-v1" |
| 179 | and isinstance(state.get("reminders"), list) and len(state["reminders"]) <= 1, |
| 180 | "unexpected_fixture_preferences") |
| 181 | if "deliveryExpired" in state: |
| 182 | require(type(state["deliveryExpired"]) is bool, "unexpected_fixture_preferences") |
| 183 | for row in state["reminders"]: |
| 184 | require(isinstance(row, dict) and set(row) <= { |
| 185 | "id", "planItemId", "scheduledAtEpochMs", "companionName", "delivered"} |
| 186 | and re.fullmatch(UUID, row.get("id", "")) is not None |
| 187 | and re.fullmatch(UUID, row.get("planItemId", "")) is not None |
| 188 | and row.get("companionName") == COMPANION and _positive(row.get("scheduledAtEpochMs")) |
| 189 | and state["issuedAtEpochMs"] < row["scheduledAtEpochMs"] <= state["validUntilEpochMs"] |
| 190 | and type(row.get("delivered", False)) is bool, "unexpected_fixture_preferences") |
| 191 | return state |
| 192 | except (ET.ParseError, ValueError, TypeError, KeyError, AttributeError): |
| 193 | raise AcceptanceError("unexpected_fixture_preferences") from None |
| 194 | |
| 195 | |
| 196 | class Harness: |
| 197 | def __init__(self, *, serial, user_apk, fixture_apk, allow_reset, screenshot, |
| 198 | adb=None, manifest_check=manifest_check, certificate_check=certificate_digest, |
| 199 | clock=time.monotonic, sleep=time.sleep): |
| 200 | self.serial, self.user_apk, self.fixture_apk = serial, Path(user_apk), Path(fixture_apk) |
| 201 | self.allow_reset, self.screenshot = allow_reset, Path(screenshot) |
| 202 | self.adb, self.manifest_check, self.certificate_check = adb, manifest_check, certificate_check |
| 203 | self.clock, self.sleep = clock, sleep |
| 204 | self.installed = self.user_launched = self.fixture_installed = False |
| 205 | self.scope = None |
| 206 | self.receipt = {"schemaVersion": 1, "result": "FAIL", "syntheticDataOnly": True, |
| 207 | "scope": "fresh API35 emulator; actual isolated SQLite and native notification", |
| 208 | "currentPhase": "preflight", "limitations": LIMITATIONS.copy(), "checks": {}} |
| 209 | |
| 210 | def install_user(self): |
| 211 | validate_serial(self.serial) |
| 212 | require(self.allow_reset is True, "synthetic_emulator_reset_flag_required") |
| 213 | require(self.user_apk.is_file() and self.fixture_apk.is_file(), "two_apk_files_required") |
| 214 | manifests, certificates = [], [] |
| 215 | for apk in (self.user_apk, self.fixture_apk): |
| 216 | try: |
| 217 | report = self.manifest_check(apk) |
| 218 | require(isinstance(report, dict) and report.get("result") == "PASS" and |
| 219 | report.get("package") == PACKAGE and report.get("label") == LABEL and |
| 220 | report.get("debuggable") is True and report.get("internetPermission") is False and |
| 221 | report.get("targetSdkVersion") == 36 and |
| 222 | re.fullmatch(r"[0-9a-f]{64}", report.get("sha256", "")) is not None, |
| 223 | "apk_manifest_rejected") |
| 224 | certificate = self.certificate_check(apk) |
| 225 | require(re.fullmatch(r"[0-9a-f]{64}", certificate or "") is not None, "apk_signature_rejected") |
| 226 | except AcceptanceError: |
| 227 | raise |
| 228 | except Exception: |
| 229 | raise AcceptanceError("apk_manifest_rejected") from None |
| 230 | manifests.append(report) |
| 231 | certificates.append(certificate) |
| 232 | require(certificates[0] == certificates[1], "apk_certificates_differ") |
| 233 | if self.adb is None: |
| 234 | self.adb = Adb(self.serial) |
| 235 | require(self.adb.command("get-state").strip() == "device", "emulator_not_ready") |
| 236 | kernel = self.adb.shell("getprop", "ro.kernel.qemu").strip() |
| 237 | boot = self.adb.shell("getprop", "ro.boot.qemu").strip() |
| 238 | require("1" in (kernel, boot), "qemu_emulator_required") |
| 239 | require(self.adb.shell("getprop", "ro.hardware").strip() in ("ranchu", "goldfish"), "android_emulator_hardware_required") |
| 240 | require(re.fullmatch(r"sdk_(?:gphone|phone)[A-Za-z0-9_]*", |
| 241 | self.adb.shell("getprop", "ro.product.name").strip()) is not None, "synthetic_sdk_product_required") |
| 242 | require(self.adb.shell("getprop", "ro.build.version.sdk").strip() == "35", "api_35_required") |
| 243 | require(not self.adb.shell("pm", "list", "packages", PACKAGE).strip(), "fresh_emulator_required_package_already_present") |
| 244 | output = self.adb.command("install", str(self.user_apk)) |
| 245 | require("Success" in output.splitlines() and "Failure" not in output and "Error" not in output, |
| 246 | "user_apk_install_failed") |
| 247 | self.installed = True |
| 248 | self.receipt["apks"] = {role: {name: report[name] for name in ( |
| 249 | "sha256", "package", "label", "debuggable", "internetPermission", "targetSdkVersion")} |
| 250 | for role, report in zip(("user", "fixtureNeverDistribute"), manifests)} |
| 251 | self.receipt["certificateSha256"] = certificates[0] |
| 252 | self.receipt["checks"]["emulatorAndFreshInstallGates"] = "PASS" |
| 253 | |
| 254 | def _ready(self): |
| 255 | require(self.installed, "package_not_installed_by_this_runner") |
| 256 | |
| 257 | def process_state(self): |
| 258 | self._ready() |
| 259 | state = self.adb.shell("sh", "-c", PID_QUERY).strip() |
| 260 | require(state in ("PRESENT", "ABSENT"), "fixture_process_query_failed") |
| 261 | return state |
| 262 | |
| 263 | def process_dead(self, *, before=None): |
| 264 | self._ready() |
| 265 | self.receipt.pop("processExit", None) |
| 266 | self.adb.shell("input", "keyevent", "KEYCODE_HOME") |
| 267 | until, attempts = self.clock() + 10, 0 |
| 268 | while True: |
| 269 | self.adb.shell("am", "kill", PACKAGE) |
| 270 | attempts += 1 |
| 271 | state = self.process_state() |
| 272 | self.receipt["lastProcessState"] = state |
| 273 | if state == "ABSENT": |
| 274 | if before is not None: |
| 275 | require(self.device_epoch_ms() + 1000 < before, "process_absence_missed_alarm_deadline") |
| 276 | self.receipt["processExit"] = {"confirmedAbsent": True, "ordinaryKillAttempts": attempts} |
| 277 | return |
| 278 | require(self.clock() < until, "fixture_process_did_not_exit") |
| 279 | self.sleep(0.25) |
| 280 | |
| 281 | def first_user_launch(self): |
| 282 | self._ready() |
| 283 | require(not self.fixture_installed, "fixture_cannot_prove_user_first_launch") |
| 284 | self.receipt["currentPhase"] = "user_first_launch" |
| 285 | output = self.adb.shell("am", "start", "-W", "-f", "0x10008000", "-n", COMPONENT) |
| 286 | require("Error" not in output and "Exception" not in output, "user_activity_launch_failed") |
| 287 | self.sleep(3) |
| 288 | require(self.process_state() == "PRESENT", "user_first_launch_process_not_alive") |
| 289 | # No UI interaction or profile creation occurs before this screenshot. |
| 290 | try: |
| 291 | result = subprocess.run(["adb", "-s", self.serial, "exec-out", "screencap", "-p"], |
| 292 | capture_output=True, timeout=30, check=False) |
| 293 | png = result.stdout |
| 294 | require(result.returncode == 0 and 24 <= len(png) <= 16 * 1024 * 1024 and |
| 295 | png[:8] == b"\x89PNG\r\n\x1a\n" and png[12:16] == b"IHDR", "user_screenshot_failed") |
| 296 | width, height = struct.unpack(">II", png[16:24]) |
| 297 | require(100 <= width <= 4096 and 100 <= height <= 4096, "user_screenshot_failed") |
| 298 | self.screenshot.parent.mkdir(parents=True, exist_ok=True) |
| 299 | self.screenshot.write_bytes(png) |
| 300 | except (OSError, subprocess.SubprocessError): |
| 301 | raise AcceptanceError("user_screenshot_failed") from None |
| 302 | ui = self.adb.shell("uiautomator", "dump", "/dev/tty", allow_failure=True) |
| 303 | require(not any(text in ui for text in ("https://", "http://", "نشانی API", "آدرس API")), |
| 304 | "user_launch_url_prompt_detected") |
| 305 | self.receipt["userFirstLaunch"] = {"processAlive": True, |
| 306 | "ordinaryLaunchNoExtras": True, "screenshotSha256": hashlib.sha256(png).hexdigest(), |
| 307 | "screenshotFile": self.screenshot.name, "urlPromptDetected": False, |
| 308 | "localWelcomeText": "PASS" if "جای کوچکی برای برنامههای تو" in ui else "UNVERIFIED"} |
| 309 | self.user_launched = True |
| 310 | self.receipt["checks"]["actualUserApkFirstLaunchScreenshot"] = "PASS" |
| 311 | |
| 312 | def install_fixture(self): |
| 313 | self._ready() |
| 314 | require(self.user_launched, "user_first_launch_not_verified") |
| 315 | require(not self.fixture_installed, "fixture_already_installed") |
| 316 | self.process_dead() |
| 317 | output = self.adb.command("install", "-r", str(self.fixture_apk)) |
| 318 | require("Success" in output.splitlines() and "Failure" not in output and "Error" not in output, |
| 319 | "owned_fixture_upgrade_failed") |
| 320 | self.fixture_installed = True |
| 321 | self.adb.shell("pm", "grant", PACKAGE, "android.permission.POST_NOTIFICATIONS") |
| 322 | self.adb.shell("cmd", "appops", "set", PACKAGE, "SCHEDULE_EXACT_ALARM", "allow") |
| 323 | self.receipt["checks"]["ownedFreshInstallFixtureUpgrade"] = "PASS" |
| 324 | |
| 325 | def launch(self, mode): |
| 326 | require(self.fixture_installed and mode in MODES, "fixture_not_ready") |
| 327 | self.receipt["currentPhase"] = "before_launch_" + mode |
| 328 | self.process_dead() |
| 329 | nonce = secrets.token_hex(8) |
| 330 | route = "/" + mode + "?nonce=" + nonce |
| 331 | output = self.adb.shell("am", "start", "-W", "-f", "0x10008000", |
| 332 | "-n", COMPONENT, "--es", "route", route) |
| 333 | require("Error" not in output and "Exception" not in output, "fixture_activity_launch_failed") |
| 334 | self.receipt["currentPhase"] = "waiting_" + mode + "_marker" |
| 335 | until = self.clock() + 30 |
| 336 | while True: |
| 337 | logs = self.adb.command("logcat", "-d", "-v", "brief", "-s", "flutter:I") |
| 338 | for line in logs.splitlines(): |
| 339 | marker = fixture_marker(line, nonce, mode) |
| 340 | if marker is not None: |
| 341 | self.receipt["currentPhase"] = "after_" + mode + "_marker" |
| 342 | return marker |
| 343 | require(self.clock() < until, "fixture_marker_timeout") |
| 344 | self.sleep(0.5) |
| 345 | |
| 346 | def device_epoch_ms(self): |
| 347 | value = self.adb.shell("date", "+%s").strip() |
| 348 | require(re.fullmatch(r"[0-9]{10,}", value) is not None, "emulator_clock_unavailable") |
| 349 | return int(value) * 1000 |
| 350 | |
| 351 | def align_to_minute(self): |
| 352 | # Product records have minute precision. At second 10..15, the next |
| 353 | # whole minute is genuinely 45..50 seconds away, without a test clock. |
| 354 | until = self.clock() + 65 |
| 355 | while True: |
| 356 | second = self.device_epoch_ms() // 1000 % 60 |
| 357 | if 10 <= second <= 15: |
| 358 | return |
| 359 | require(self.clock() < until, "emulator_clock_alignment_timeout") |
| 360 | self.sleep(min(1, (70 - second) % 60 or 1)) |
| 361 | |
| 362 | def preferences(self): |
| 363 | script = "if [ -f " + PREFERENCES + " ]; then cat " + PREFERENCES + "; else printf '<map/>'; fi" |
| 364 | return parse_preferences(self.adb.shell("run-as", PACKAGE, "sh", "-c", script), expected_scope=self.scope) |
| 365 | |
| 366 | def active_keys(self): |
| 367 | return active_fixture_keys(self.adb.shell("cmd", "notification", "list")) |
| 368 | |
| 369 | def assert_status(self, marker, *, active, count): |
| 370 | status = marker["status"] |
| 371 | require(status["permissionGranted"] is True and status["active"] is active and |
| 372 | status["enabled"] is active and |
| 373 | status["scheduledCount"] == count and status["timing"] == "exact" and |
| 374 | status["canScheduleExactAlarms"] is True, "fixture_status_assertion_failed") |
| 375 | if active: |
| 376 | if self.scope is None: |
| 377 | self.scope = status["activeScope"] |
| 378 | require(status["activeScope"] == self.scope, "fixture_scope_changed") |
| 379 | |
| 380 | def assert_database(self, marker, names): |
| 381 | require(all(marker["checks"].get(name) is True for name in names), "real_sqlite_assertion_failed") |
| 382 | for name in names: |
| 383 | self.receipt["checks"][name] = "PASS" |
| 384 | |
| 385 | def assert_scheduled(self, marker): |
| 386 | self.assert_status(marker, active=True, count=1) |
| 387 | at = marker.get("scheduledAtEpochMs") |
| 388 | require(_positive(at) and 30000 < at - self.device_epoch_ms() <= 55000, |
| 389 | "real_record_not_near_45_seconds") |
| 390 | state = self.preferences() |
| 391 | require(state is not None and len(state["reminders"]) == 1 and |
| 392 | state["reminders"][0]["scheduledAtEpochMs"] == at and |
| 393 | not state["reminders"][0].get("delivered", False), "real_record_schedule_not_persisted") |
| 394 | require(not self.active_keys(), "unexpected_fixture_notification_before_deadline") |
| 395 | return at, state |
| 396 | |
| 397 | def wait_for_post(self, at): |
| 398 | until = self.clock() + max(0, (at - self.device_epoch_ms()) / 1000) + 30 |
| 399 | while True: |
| 400 | keys = self.active_keys() |
| 401 | if keys: |
| 402 | require(self.device_epoch_ms() + 1000 >= at, "fixture_notification_posted_before_deadline") |
| 403 | return keys[0] |
| 404 | require(self.clock() < until, "fixture_notification_not_posted") |
| 405 | self.sleep(1) |
| 406 | |
| 407 | def assert_no_post_through(self, at): |
| 408 | until = self.clock() + max(0, (at - self.device_epoch_ms()) / 1000) + 5 |
| 409 | while True: |
| 410 | require(not self.active_keys(), "canceled_fixture_notification_posted") |
| 411 | if self.clock() >= until: |
| 412 | return |
| 413 | self.sleep(min(1, until - self.clock())) |
| 414 | |
| 415 | def run(self): |
| 416 | self.install_user() |
| 417 | self.first_user_launch() |
| 418 | self.install_fixture() |
| 419 | self.align_to_minute() |
| 420 | seeded = self.launch("seed") |
| 421 | self.assert_database(seeded, {"rawSqlAfterClose", "profilePersists", "weeklyDifferentTimes", "onceAndEveryTwoDays"}) |
| 422 | at, scheduled = self.assert_scheduled(seeded) |
| 423 | self.process_dead(before=at) |
| 424 | require(self.preferences() == scheduled and not self.active_keys(), "alarm_preceded_process_absence_proof") |
| 425 | self.receipt["checks"]["processAbsentBeforeAlarm"] = "PASS" |
| 426 | key = self.wait_for_post(at) |
| 427 | require(key.split("|")[3] == "lifeguide-plan:" + scheduled["reminders"][0]["id"], "notification_not_from_sqlite_record") |
| 428 | delivered = self.preferences() |
| 429 | require(delivered is not None and delivered["generation"] == scheduled["generation"] and |
| 430 | len(delivered["reminders"]) == 1 and delivered["reminders"][0].get("delivered") is True, |
| 431 | "native_delivered_marker_missing") |
| 432 | self.receipt["checks"]["notificationAfterProcessDeath"] = "PASS" |
| 433 | self.receipt["checks"]["notificationContent"] = check_notification_record( |
| 434 | self.adb.shell("dumpsys", "notification", "--noredact"), key) |
| 435 | inspected = self.launch("inspect") |
| 436 | self.assert_status(inspected, active=True, count=0) |
| 437 | self.assert_database(inspected, {"rawSqlAfterClose", "profilePersists", "weeklyDifferentTimes", "onceAndEveryTwoDays"}) |
| 438 | require(self.preferences() == delivered and self.active_keys() == [key], "inspect_changed_delivered_state_or_post") |
| 439 | self.receipt["checks"]["relaunchReadOnlyPreservesNativeGeneration"] = "PASS" |
| 440 | self.align_to_minute() |
| 441 | changed = self.launch("change") |
| 442 | self.assert_database(changed, {"rawSqlAfterClose", "profilePersists", "independentEditAndTick"}) |
| 443 | canceled_at, _ = self.assert_scheduled(changed) |
| 444 | canceled = self.launch("cancel") |
| 445 | self.assert_status(canceled, active=True, count=0) |
| 446 | self.assert_database(canceled, {"rawSqlAfterClose", "archivePersists", "independentEditAndTick"}) |
| 447 | require(self.device_epoch_ms() + 1000 < canceled_at, "fixture_cancellation_missed_deadline") |
| 448 | state = self.preferences() |
| 449 | require(state is not None and state["reminders"] == [] and not self.active_keys(), "archive_did_not_cancel_native_alarm") |
| 450 | self.process_dead(before=canceled_at) |
| 451 | self.assert_no_post_through(canceled_at) |
| 452 | self.receipt["checks"]["archiveBeforeDeadlineHasNoOSPost"] = "PASS" |
| 453 | off = self.launch("off") |
| 454 | self.assert_status(off, active=False, count=0) |
| 455 | require(self.preferences() is None and not self.active_keys(), "off_did_not_clear_native_state") |
| 456 | self.receipt["checks"]["offClearsNativeState"] = "PASS" |
| 457 | self.receipt["currentPhase"], self.receipt["result"] = "complete", "PASS" |
| 458 | return self.receipt |
| 459 | |
| 460 | |
| 461 | def main(argv=None): |
| 462 | parser = argparse.ArgumentParser(description=__doc__) |
| 463 | parser.add_argument("--user-apk", required=True, type=Path) |
| 464 | parser.add_argument("--fixture-apk", required=True, type=Path) |
| 465 | parser.add_argument("--serial", required=True) |
| 466 | parser.add_argument("--allow-synthetic-emulator-reset", action="store_true") |
| 467 | parser.add_argument("--output", required=True, type=Path) |
| 468 | options = parser.parse_args(argv) |
| 469 | harness = Harness(serial=options.serial, user_apk=options.user_apk, |
| 470 | fixture_apk=options.fixture_apk, allow_reset=options.allow_synthetic_emulator_reset, |
| 471 | screenshot=options.output.with_name("standalone-user-first-launch.png")) |
| 472 | try: |
| 473 | harness.run() |
| 474 | except AcceptanceError as error: |
| 475 | harness.receipt["error"] = str(error) |
| 476 | except Exception: |
| 477 | harness.receipt["error"] = "unexpected_acceptance_failure" |
| 478 | options.output.parent.mkdir(parents=True, exist_ok=True) |
| 479 | options.output.write_text(json.dumps(harness.receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") |
| 480 | print(json.dumps({"result": harness.receipt["result"], "error": harness.receipt.get("error")})) |
| 481 | return 0 if harness.receipt["result"] == "PASS" else 1 |
| 482 | |
| 483 | |
| 484 | if __name__ == "__main__": |
| 485 | raise SystemExit(main()) |