LifeMate — Personal, Family & Learning Companion

feat/aparat-learning-library
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 161 lines 11.4 KB
Raw
1 """Developer-only real HTTPS PWA load test; requires Playwright + Chromium.
2
3 The public CA must already be trusted normally by the browser. This program
4 never ignores TLS errors, intercepts network responses, or logs credentials.
5 Real Safari/Android and Iran reachability are separate acceptance gates.
6 """
7 import argparse
8 import json
9 import re
10 import time
11 from pathlib import Path
12 from urllib.parse import urlparse
13 from playwright.sync_api import sync_playwright
14
15 parser = argparse.ArgumentParser()
16 parser.add_argument("origin")
17 parser.add_argument("--chromium", default="/usr/bin/chromium")
18 parser.add_argument("--profile", required=True)
19 parser.add_argument("--screenshot", required=True)
20 parser.add_argument("--viewport-width", type=int, default=390)
21 parser.add_argument("--synthetic-login-email", choices=["stage0-mother@lifeguide.test", "stage0-father@lifeguide.test"])
22 parser.add_argument("--synthetic-password-file")
23 parser.add_argument("--expected-task-title")
24 parser.add_argument("--expected-recorded-seconds", type=int)
25 parser.add_argument("--expected-planned-seconds", type=int)
26 parser.add_argument("--expected-status")
27 parser.add_argument("--resume-parent-session", action="store_true")
28 args = parser.parse_args()
29 origin = args.origin.rstrip("/")
30 parsed = urlparse(origin)
31 if parsed.scheme != "https" or parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment:
32 raise SystemExit("Use one HTTPS origin without credentials/path/query/fragment")
33 requests, failures, errors, http_errors, auth_responses = [], [], [], [], []
34 login_verified, report_verified, report_body_verified, reported_task = False, False, False, None
35 if bool(args.synthetic_login_email) != bool(args.synthetic_password_file):
36 raise SystemExit("Synthetic login requires both the known fixture email and private local password file")
37 if args.resume_parent_session and not args.synthetic_login_email:
38 raise SystemExit("Resume requires a previously authenticated synthetic parent profile")
39 with sync_playwright() as playwright:
40 context = playwright.chromium.launch_persistent_context(
41 user_data_dir=args.profile, executable_path=args.chromium, headless=True,
42 viewport={"width": args.viewport_width, "height": 960}, ignore_https_errors=False,
43 service_workers="allow", timezone_id="Asia/Tehran",
44 )
45 try:
46 page = context.pages[0] if context.pages else context.new_page()
47 def requested(request):
48 url = urlparse(request.url)
49 requests.append({"origin": f"{url.scheme}://{url.netloc}", "path": url.path})
50 page.on("request", requested)
51 page.on("requestfailed", lambda request: failures.append({"path": urlparse(request.url).path, "failure": request.failure}))
52 page.on("pageerror", lambda error: errors.append(str(error)))
53 def responded(response):
54 path = urlparse(response.url).path
55 if response.status >= 400:
56 http_errors.append({"path": path, "status": response.status})
57 if path in ("/api/v1/auth/login", "/api/v1/auth/refresh"):
58 auth_responses.append({"path": path, "status": response.status})
59 page.on("response", responded)
60 initial_url = page.url
61 if initial_url.rstrip("/") == origin:
62 # Persistent Chromium may already be restoring the prior page.
63 # Never start a second navigation while it rotates refresh tokens.
64 response = None
65 page.wait_for_load_state("networkidle", timeout=90000)
66 else:
67 response = page.goto(origin, wait_until="networkidle", timeout=90000)
68 assert response and response.status == 200, "PWA navigation failed"
69 page.wait_for_selector("flt-glass-pane", state="attached", timeout=90000)
70 page.wait_for_function("() => !document.getElementById('startup-status')", timeout=90000)
71 placeholder = page.locator("flt-semantics-placeholder")
72 if placeholder.count():
73 placeholder.evaluate("element => element.click()")
74 page.wait_for_load_state("networkidle")
75 if args.synthetic_login_email:
76 if args.resume_parent_session:
77 pass
78 else:
79 password = Path(args.synthetic_password_file).read_text().strip()
80 assert len(password) >= 10, "Synthetic password too short"
81 page.get_by_label("ایمیل یا شماره تلفن", exact=True).fill(args.synthetic_login_email)
82 page.get_by_label("رمز عبور", exact=True).fill(password)
83 password = None
84 with page.expect_response(lambda response: urlparse(response.url).path == "/api/v1/auth/login" and response.request.method == "POST") as logged_in:
85 page.get_by_role("button", name="ورود", exact=True).click()
86 assert logged_in.value.status == 200, f"Synthetic parent login HTTP {logged_in.value.status}"
87 page.get_by_role("tab", name="خانواده", exact=True).wait_for(timeout=30000)
88 page.wait_for_load_state("networkidle")
89 if args.resume_parent_session:
90 assert {"path": "/api/v1/auth/refresh", "status": 200} in auth_responses, "Saved parent session did not refresh after browser restart"
91 # Flutter's RTL semantic tab has a transformed DOM rectangle. Use
92 # the actual visible centre tab of the five-destination navbar.
93 page.mouse.click(args.viewport_width / 2, 920)
94 child = page.get_by_role("button", name=re.compile("فرزند آزمایشی"))
95 child.wait_for(timeout=30000)
96 with page.expect_response(lambda response: urlparse(response.url).path.endswith("/learning-report")) as loaded_report:
97 child.evaluate("element => element.click()")
98 assert loaded_report.value.status == 200, "Permitted child report API failed"
99 # Chromium's restored tab can expose a response without retaining
100 # its CDP response body. Fresh-login runs independently validate
101 # server JSON; restart runs validate refresh, new report HTTP 200
102 # and the actual rendered values, without inventing a JSON check.
103 server_report = None if args.resume_parent_session else loaded_report.value.json()
104 report_body_verified = server_report is not None
105 if server_report is not None and args.expected_planned_seconds is not None:
106 assert server_report["metrics"]["plannedInRangeDurationSeconds"] == args.expected_planned_seconds, "Planned time for the selected report range differs"
107 page.get_by_role("heading", name=re.compile("گزارش یادگیری")).wait_for(timeout=30000)
108 if server_report is not None and args.expected_task_title:
109 reported_task = next((item for item in server_report["items"] if item["title"] == args.expected_task_title), None)
110 assert reported_task, "Expected synthetic homework missing from server report"
111 if args.expected_recorded_seconds is not None:
112 assert reported_task["recordedDurationSeconds"] == args.expected_recorded_seconds, "Reported task duration differs"
113 if args.expected_status:
114 assert reported_task["status"] == args.expected_status, "Reported task status differs"
115 assert "SYNTHETIC-OWNER-PRIVATE-NOTE" not in json.dumps(server_report), "Private owner note leaked to parent"
116 deadline = time.monotonic() + 30
117 while True:
118 rendered = page.locator("body").aria_snapshot()
119 if "زمان ثبت‌شده" in rendered and (not args.expected_task_title or args.expected_task_title in rendered):
120 break
121 assert time.monotonic() < deadline, "Expected allowed report was not rendered in PWA"
122 page.wait_for_timeout(100)
123 if args.expected_recorded_seconds is not None:
124 assert f"ثبت {round(args.expected_recorded_seconds / 60)} دقیقه" in rendered, "Recorded task duration not shown in PWA"
125 if args.expected_status == "completed":
126 assert "انجام‌شده به گزارش فرزند" in rendered, "Recorded completion status not shown in PWA"
127 if args.expected_planned_seconds is not None:
128 assert f"زمان برنامه‌ریزی‌شده: {round(args.expected_planned_seconds / 60)} دقیقه" in rendered, "Planned duration for report range not shown in PWA"
129 assert "SYNTHETIC-OWNER-PRIVATE-NOTE" not in rendered, "Private owner note rendered for parent"
130 login_verified, report_verified = True, True
131 external = [request for request in requests if request["origin"] != origin]
132 assert not external, f"Unexpected external request: {external}"
133 assert not failures, f"Network failure: {failures}"
134 assert not errors, f"Browser error: {errors}"
135 assert not http_errors, f"HTTP failure: {http_errors}"
136 assert any("/canvaskit/" in request["path"] and request["path"].endswith(".wasm") for request in requests), "Local CanvasKit WASM missing"
137 assert "LifeGuide" in page.title() and "لایف‌گاید" in page.title(), "Product title differs"
138 page.screenshot(path=args.screenshot, full_page=False)
139 print(json.dumps({"mode": "actual local HTTPS gateway, normal browser trust, real API", "browser": context.browser.version if context.browser else "Chromium", "http": response.status if response else "Chromium restored navigation; initial HTTP status UNVERIFIED",
140 "requestCount": len(requests), "externalRequests": external,
141 "failedRequests": failures, "browserErrors": errors,
142 "httpErrors": http_errors,
143 "syntheticParentLogin": login_verified and not args.resume_parent_session,
144 "syntheticParentAuthenticated": login_verified,
145 "permittedChildReportRendered": report_verified,
146 "serverReportBodyVerified": report_body_verified,
147 "reportBodyLimit": "Restored-tab JSON body UNVERIFIED; fresh-login runs independently validate JSON" if args.resume_parent_session else None,
148 "resumedPersistedParentSession": args.resume_parent_session,
149 "authResponses": auth_responses,
150 "reportedTask": None if reported_task is None else {key: reported_task.get(key) for key in ["title", "status", "recordedDurationSeconds", "plannedDurationSeconds", "activityState"]},
151 "fonts": [request["path"] for request in requests if request["path"].endswith((".ttf", ".otf", ".woff2"))],
152 "inputLabels": page.locator("input").evaluate_all("els => els.map(e => ({type:e.type,label:e.getAttribute('aria-label')}))"),
153 "serviceWorkers": len(context.service_workers),
154 "limitations": "Safari install, Android, three physical devices and Iran reachability UNVERIFIED"}, ensure_ascii=False, indent=2))
155 finally:
156 # Park the saved profile on a blank page before closing. Chromium may
157 # otherwise auto-restore the prior URL before a subsequent explicit
158 # navigation, accidentally racing two refresh rotations in this test.
159 for open_page in context.pages:
160 open_page.goto("about:blank")
161 context.close()