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
py 502 lines 23.4 KB
Raw
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 "currentPhase": "preflight",
236 "simulatedServerAcknowledgement": True,
237 "limitations": LIMITATIONS.copy(), "checks": {}}
238
239 def install_fixture(self):
240 validate_serial(self.serial)
241 require(self.allow_reset is True, "synthetic_emulator_reset_flag_required")
242 require(self.apk.is_file(), "apk_file_required")
243 try:
244 manifest = self.manifest_check(self.apk, "debug")
245 require(isinstance(manifest, dict) and manifest.get("result") == "PASS" and
246 manifest.get("mode") == "debug" and manifest.get("package") == PACKAGE and
247 manifest.get("debuggable") is True and
248 type(manifest.get("targetSdkVersion")) is int and
249 manifest["targetSdkVersion"] == 36 and
250 re.fullmatch(r"[0-9a-f]{64}", manifest.get("sha256", "")) is not None,
251 "apk_manifest_rejected")
252 except Exception:
253 raise AcceptanceError("apk_manifest_rejected") from None
254 if self.adb is None:
255 self.adb = Adb(self.serial)
256 require(self.adb.command("get-state").strip() == "device", "emulator_not_ready")
257 kernel = self.adb.shell("getprop", "ro.kernel.qemu").strip()
258 boot = self.adb.shell("getprop", "ro.boot.qemu").strip()
259 require("1" in (kernel, boot), "qemu_emulator_required")
260 require(self.adb.shell("getprop", "ro.hardware").strip() in ("ranchu", "goldfish"),
261 "android_emulator_hardware_required")
262 product = self.adb.shell("getprop", "ro.product.name").strip()
263 require(re.fullmatch(r"sdk_(?:gphone|phone)[A-Za-z0-9_]*", product) is not None,
264 "synthetic_sdk_product_required")
265 require(self.adb.shell("getprop", "ro.build.version.sdk").strip() == "35",
266 "api_35_required")
267 require(not self.adb.shell("pm", "list", "packages", PACKAGE).strip(),
268 "fresh_emulator_required_package_already_present")
269 installed = self.adb.command("install", str(self.apk))
270 require("Failure" not in installed and "Error" not in installed,
271 "fixture_install_failed")
272 self.installed = True
273 self.adb.shell("pm", "grant", PACKAGE, "android.permission.POST_NOTIFICATIONS")
274 self.adb.shell("cmd", "appops", "set", PACKAGE, "SCHEDULE_EXACT_ALARM", "allow")
275 self.receipt["apk"] = {name: manifest[name] for name in
276 ("sha256", "package", "debuggable", "targetSdkVersion")}
277 self.receipt["checks"]["emulatorAndFreshInstallGates"] = "PASS"
278
279 def _ready(self):
280 require(self.installed, "fixture_not_installed_by_this_runner")
281
282 def process_dead(self):
283 self._ready()
284 self.receipt.pop("processExit", None)
285 self.receipt["lastProcessState"] = "UNVERIFIED"
286 self.adb.shell("input", "keyevent", "KEYCODE_HOME")
287 self.adb.shell("am", "kill", PACKAGE)
288 attempts = 1
289 until = self.clock() + 10
290 while True:
291 state = self.adb.shell("sh", "-c", PID_QUERY).strip()
292 require(state in ("PRESENT", "ABSENT"), "fixture_process_query_failed")
293 self.receipt["lastProcessState"] = state
294 if state == "ABSENT":
295 self.receipt["processExit"] = {
296 "confirmedAbsent": True, "ordinaryKillAttempts": attempts}
297 return True
298 require(self.clock() < until, "fixture_process_did_not_exit")
299 self.sleep(0.25)
300 # HOME demotion is asynchronous. Ordinary am kill can initially be
301 # a no-op while Android still considers the app foreground.
302 self.adb.shell("am", "kill", PACKAGE)
303 attempts += 1
304
305 def launch(self, mode):
306 self._ready()
307 require(mode in MODES, "invalid_fixture_request")
308 self.receipt["currentPhase"] = "before_launch_" + mode
309 self.process_dead()
310 nonce = secrets.token_hex(8)
311 route = "/" + mode + "?nonce=" + nonce
312 if mode == "schedule":
313 route += "&delay=45"
314 self.receipt["currentPhase"] = "starting_" + mode + "_activity"
315 # A killed singleTop activity can retain its old route in task history.
316 # Recreate only this fixture's task so Flutter main gets the new intent.
317 # Intent.parseCommandArgs accepts -f; NEW_TASK has no named CLI option.
318 # 0x10008000 = FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK.
319 output = self.adb.shell("am", "start", "-W", "-f", "0x10008000",
320 "-n", PACKAGE + "/.MainActivity",
321 "--es", "route", route)
322 require("Error" not in output and "Exception" not in output,
323 "fixture_activity_launch_failed")
324 self.receipt["currentPhase"] = "waiting_" + mode + "_marker"
325 until = self.clock() + 30
326 observed_modes = set()
327 fixture_error_seen = False
328 while True:
329 logs = self.adb.command("logcat", "-d", "-v", "brief", "-s", "flutter:I")
330 for line in logs.splitlines():
331 if "LG_NATIVE_REMINDER_FIXTURE_ERROR" in line:
332 fixture_error_seen = True
333 if MARKER in line:
334 try:
335 logged = json.loads(line.split(MARKER, 1)[1])
336 except ValueError:
337 logged = None
338 if (isinstance(logged, dict) and isinstance(logged.get("mode"), str)
339 and logged["mode"] in MODES):
340 observed_modes.add(logged["mode"])
341 marker = fixture_marker(line, nonce, mode)
342 if marker is not None:
343 self.receipt["currentPhase"] = "after_" + mode + "_marker"
344 return marker
345 if self.clock() >= until:
346 # Retained logs may include prior launches. These are diagnostic
347 # observations, not evidence that this launch ran any old mode.
348 self.receipt["fixtureLogObservationScope"] = "retained_logcat_buffer"
349 self.receipt["observedFixtureModes"] = sorted(observed_modes)
350 self.receipt["fixtureErrorSeen"] = fixture_error_seen
351 raise AcceptanceError("fixture_marker_timeout")
352 self.sleep(0.5)
353
354 def preferences(self):
355 self._ready()
356 script = ("if [ -f " + PREFERENCES + " ]; then cat " + PREFERENCES +
357 "; else printf '<map/>'; fi")
358 return parse_preferences(self.adb.shell("run-as", PACKAGE, "sh", "-c", script))
359
360 def active_keys(self):
361 self._ready()
362 return active_fixture_keys(self.adb.shell("cmd", "notification", "list"))
363
364 def device_epoch_ms(self):
365 output = self.adb.shell("date", "+%s").strip()
366 require(re.fullmatch(r"[0-9]{10,}", output) is not None, "emulator_clock_unavailable")
367 return int(output) * 1000
368
369 def assert_status(self, marker, *, active, count, exact):
370 status = marker["status"]
371 require(status["permissionGranted"] is True and status["active"] is active and
372 status["scheduledCount"] == count and
373 status["canScheduleExactAlarms"] is exact and
374 status["timing"] == ("exact" if exact else "approximate"),
375 "fixture_status_assertion_failed")
376
377 def scheduled(self, *, exact):
378 marker = self.launch("schedule")
379 self.assert_status(marker, active=True, count=1, exact=exact)
380 at = marker.get("scheduledAtEpochMs")
381 require(_integer(at) and 15000 < at - self.device_epoch_ms() <= 47000,
382 "fixture_schedule_not_future_45_seconds")
383 state = self.preferences()
384 require(state is not None and len(state["reminders"]) == 1 and
385 state["reminders"][0]["scheduledAtEpochMs"] == at and
386 state["reminders"][0].get("delivered", False) is False,
387 "fixture_schedule_not_persisted")
388 require(self.active_keys() == [], "unexpected_fixture_notification_before_deadline")
389 self.receipt["currentPhase"] = "after_schedule_created"
390 return at, state
391
392 def wait_for_post(self, at):
393 until = self.clock() + max(0, (at - self.device_epoch_ms()) / 1000) + 30
394 while True:
395 keys = self.active_keys()
396 if keys:
397 require(self.device_epoch_ms() + 1000 >= at,
398 "fixture_notification_posted_before_deadline")
399 return keys[0]
400 require(self.clock() < until, "fixture_notification_not_posted")
401 self.sleep(1)
402
403 def assert_no_post_through(self, at):
404 # Check throughout the interval, not only a final snapshot.
405 remaining = max(0, (at - self.device_epoch_ms()) / 1000) + 5
406 until = self.clock() + remaining
407 while True:
408 require(self.active_keys() == [], "canceled_fixture_notification_posted")
409 if self.clock() >= until:
410 return
411 self.sleep(min(1, until - self.clock()))
412
413 def run(self):
414 self.install_fixture()
415 checks = self.receipt["checks"]
416 initial = self.launch("inspect")
417 self.assert_status(initial, active=False, count=0, exact=True)
418 require(self.preferences() is None and not self.active_keys(),
419 "fresh_inspect_created_native_state")
420 checks["inspectDoesNotActivate"] = "PASS"
421
422 at, scheduled = self.scheduled(exact=True)
423 self.process_dead()
424 require(self.device_epoch_ms() + 1000 < at,
425 "process_absence_missed_alarm_deadline")
426 require(self.preferences() == scheduled and not self.active_keys(),
427 "alarm_delivery_preceded_process_absence_proof")
428 checks["processAbsentBeforeAlarm"] = "PASS"
429 key = self.wait_for_post(at)
430 delivered = self.preferences()
431 require(delivered is not None and delivered["generation"] == scheduled["generation"] and
432 len(delivered["reminders"]) == 1 and
433 delivered["reminders"][0].get("delivered") is True,
434 "native_delivered_marker_missing")
435 checks["notificationAfterProcessDeath"] = "PASS"
436 checks["notificationContent"] = check_notification_record(
437 self.adb.shell("dumpsys", "notification", "--noredact"), key,
438 require_channel=True)
439 checks["notificationChannel"] = CHANNEL
440
441 inspected = self.launch("inspect")
442 self.assert_status(inspected, active=True, count=0, exact=True)
443 require(self.preferences() == delivered and self.active_keys() == [key],
444 "inspect_changed_delivered_state_or_post")
445 checks["relaunchPreservesDeliveredStateAndPost"] = "PASS"
446
447 suppressed = self.launch("suppress")
448 self.assert_status(suppressed, active=True, count=0, exact=True)
449 state = self.preferences()
450 require(state is not None and state["reminders"] == [] and not self.active_keys(),
451 "suppress_did_not_clear_delivered_post")
452 checks["suppressClearsDeliveredPost"] = "PASS"
453
454 canceled_at, _ = self.scheduled(exact=True)
455 suppressed = self.launch("suppress")
456 self.assert_status(suppressed, active=True, count=0, exact=True)
457 require(self.device_epoch_ms() < canceled_at, "fixture_cancellation_missed_deadline")
458 state = self.preferences()
459 require(state is not None and state["reminders"] == [],
460 "fixture_cancellation_not_persisted")
461 self.process_dead()
462 self.assert_no_post_through(canceled_at)
463 checks["cancelBeforeDeadlineHasNoOSPost"] = "PASS"
464
465 self.adb.shell("cmd", "appops", "set", PACKAGE, "SCHEDULE_EXACT_ALARM", "deny")
466 self.scheduled(exact=False)
467 checks["deniedExactAccessReportsApproximate"] = "PASS"
468 checks["approximateAlarmDeliveryTiming"] = "UNVERIFIED"
469 off = self.launch("off")
470 self.assert_status(off, active=False, count=0, exact=False)
471 require(self.preferences() is None and not self.active_keys(),
472 "off_did_not_clear_native_state_and_posts")
473 checks["offClearsNativeStateAndPosts"] = "PASS"
474 self.receipt["currentPhase"] = "complete"
475 self.receipt["result"] = "PASS"
476 return self.receipt
477
478
479 def main(argv=None):
480 parser = argparse.ArgumentParser(description=__doc__)
481 parser.add_argument("--serial", required=True)
482 parser.add_argument("--apk", type=Path, required=True)
483 parser.add_argument("--allow-synthetic-emulator-reset", action="store_true")
484 parser.add_argument("--output", type=Path)
485 options = parser.parse_args(argv)
486 harness = Harness(serial=options.serial, apk=options.apk,
487 allow_reset=options.allow_synthetic_emulator_reset)
488 try:
489 receipt = harness.run()
490 except AcceptanceError as error:
491 receipt = harness.receipt
492 receipt["error"] = str(error)
493 serialized = json.dumps(receipt, ensure_ascii=False, indent=2) + "\n"
494 if options.output:
495 options.output.parent.mkdir(parents=True, exist_ok=True)
496 options.output.write_text(serialized, encoding="utf-8")
497 print(serialized, end="")
498 return 0 if receipt["result"] == "PASS" else 1
499
500
501 if __name__ == "__main__":
502 raise SystemExit(main())