20 AI testers on 20 different phones, in parallel, on GitHub's free runners: Claude Code agents on iOS Simulators and Android emulators that find broken flows, translation, layout and accessibility bugs
Python accessibility-testingai-agentsai-testingandroidandroid-emulatorclaudeclaude-codee2e-testingexploratory-testingexpofluttergithub-actionsiosios-simulatorllmmobile-testingqareact-nativetest-automationui-testing
Tests: 32 offline checks on every push, Python 3.9 and 3.13
Pierre RAFFALLI565ec5be28e6
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlnew file mode 100644index 0000000..e96b3ed--- /dev/null+++ b/.github/workflows/tests.yml@@ -0,0 +1,28 @@+# Checks the scripts the testers rely on, on every push and pull request.+# Offline and free: no phone, no model, no secret.+name: Tests+on:+ push:+ branches: [main]+ pull_request:+permissions:+ contents: read+jobs:+ scripts:+ runs-on: ubuntu-latest+ strategy:+ matrix:+ python: ["3.9", "3.13"] # 3.9 is the python3 of a Mac without Homebrew (collect.sh runs there)+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with: { python-version: "${{ matrix.python }}" }+ - name: Unit tests (accessibility check, persona matrix, personas, summary, encrypted results)+ run: python3 -m unittest discover -s tests -v+ - name: Every Python script compiles+ run: python3 -m compileall -q scripts tests+ - name: Shell scripts+ if: matrix.python == '3.13'+ run: |+ for f in $(git ls-files '*.sh'); do bash -n "$f"; done+ shellcheck -S warning $(git ls-files '*.sh')diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bd95ccb..14d1e7b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ The first tagged version: everything behind the [LocalSend, AnkiDroid and Flutte- **Accessibility check** on every screen the agents read: controls with no name and touch targets under 48 dp (Android) or 44 pt (iOS).- **Encrypted results**: reports, screenshots, build logs and optional screen recordings (`record_video`) are encrypted with your public key before upload. Analytics hosts are blocked inside the phones.- **One summary**: `scripts/collect.sh <run id>` decrypts everything and groups the reports that describe the same bug into `runs/<id>/SUMMARY.md`.+- **Tests** run offline on every push, on Python 3.9 and 3.13: accessibility check, persona matrix, `personas.json`, summary, and the encrypted results path from the runner to `collect.sh`.- **Public app repos** need no token; private ones take a read-only `SOURCE_REPO_TOKEN`.- **Claude Code plugin**: `/plugin marketplace add pierridotite/mobile-agent-testers` sets it up for your app.diff --git a/README.es.md b/README.es.mdindex df9206c..307455b 100644--- a/README.es.md+++ b/README.es.md@@ -17,6 +17,7 @@ Multiplatform, Capacitor y .NET MAUI.<p align="center"><a href="assets/localsend-20.mp4"><img src="assets/localsend-20.gif" alt="Grabaciones de pantalla reales de 20 testers con IA usando LocalSend a la vez: 10 emuladores de Android y 10 simuladores de iOS en 14 idiomas, desde un Pixel pequeño hasta un iPad de 13 pulgadas. Cuando un tester termina, su teléfono muestra cuántos problemas encontró. Abre el vídeo." width="100%"></a><br><sub>Grabaciones de pantalla reales de la ejecución en LocalSend, sin los tiempos muertos. <a href="assets/localsend-20.mp4">Vídeo completo (MP4)</a> · <a href="docs/runs/localsend-20.md">La ejecución, dispositivo por dispositivo</a></sub></p>+[](https://github.com/pierridotite/mobile-agent-testers/actions/workflows/tests.yml)[](https://github.com/pierridotite/mobile-agent-testers/stargazers)[](LICENSE)@@ -153,6 +154,7 @@ toolkit de interfaz. Los widgets con etiqueta (`Semantics` de Flutter, `contentD- **Resultados cifrados**: los logs de un repositorio público son públicos, así que todo se cifra con tu clave.- **Analítica bloqueada** dentro de los teléfonos, para que las pruebas nunca toquen tus estadísticas reales.- **Un resumen** en tu máquina: Claude agrupa los informes que describen el mismo error, así ves cuántas personas encontraron cada uno y qué personas encontraron cada tipo de problema.+- **Pruebas** en cada push, sin conexión y sin teléfono: revisión de accesibilidad, matriz de personas, resumen, resultados cifrados ([tests/](tests/)).## Límitesdiff --git a/README.ja.md b/README.ja.mdindex dce5274..2504641 100644--- a/README.ja.md+++ b/README.ja.md@@ -17,6 +17,7 @@ Swift、Kotlin Multiplatform、Capacitor、.NET MAUI に対応しています。<p align="center"><a href="assets/localsend-20.mp4"><img src="assets/localsend-20.gif" alt="20 人の AI テスターが同時に LocalSend を使う実際の画面録画:Android エミュレーター 10 台と iOS シミュレーター 10 台、14 言語、小さな Pixel から 13 インチの iPad まで。テスターが終わると、その端末に見つけた問題の数が表示されます。クリックで動画を開きます。" width="100%"></a><br><sub>LocalSend での実行の実際の画面録画(待ち時間はカット)。<a href="assets/localsend-20.mp4">動画全体(MP4)</a> · <a href="docs/runs/localsend-20.md">端末ごとの実行記録</a></sub></p>+[](https://github.com/pierridotite/mobile-agent-testers/actions/workflows/tests.yml)[](https://github.com/pierridotite/mobile-agent-testers/stargazers)[](LICENSE)@@ -151,6 +152,7 @@ gh workflow run agent-testers.yml -f source_repo=you/app -f app_id=com.you.app \- **結果は暗号化**:公開リポジトリのログは公開されるので、すべてあなたの鍵で暗号化します。- **端末内で分析ツールをブロック**するので、テストが本番の統計に触れることはありません。- **手元で 1 つのまとめ**:同じバグを指すレポートを Claude がまとめるので、各バグに何人のペルソナが当たったか、どのペルソナがどの種類の問題を見つけたかがわかります。+- **プッシュごとにテスト**(オフライン、スマホ不要):アクセシビリティチェック、ペルソナの割り当て、まとめ、結果の暗号化([tests/](tests/))。## 制限diff --git a/README.md b/README.mdindex 83b59d0..5a6e807 100644--- a/README.md+++ b/README.md@@ -16,6 +16,7 @@ Multiplatform, Capacitor and .NET MAUI.<p align="center"><a href="assets/localsend-20.mp4"><img src="assets/localsend-20.gif" alt="Real screen recordings of 20 AI testers using LocalSend at the same time: 10 Android emulators and 10 iOS Simulators in 14 languages, from a small Pixel to a 13-inch iPad. When a tester finishes, its phone shows how many issues it found. Opens the video." width="100%"></a><br><sub>Real screen recordings of the LocalSend run, idle time cut. <a href="assets/localsend-20.mp4">Full video (MP4)</a> · <a href="docs/runs/localsend-20.md">The run, device by device</a></sub></p>+[](https://github.com/pierridotite/mobile-agent-testers/actions/workflows/tests.yml)[](https://github.com/pierridotite/mobile-agent-testers/stargazers)[](LICENSE)@@ -152,6 +153,7 @@ toolkit works. Labelled widgets (Flutter `Semantics`, `contentDescription`,- **Encrypted results**: public repo logs are public, so everything is encrypted with your key.- **Analytics blocked** inside the phones, so tests never touch your real stats.- **One summary** on your machine: Claude groups the reports that describe the same bug, so you see how many personas hit each one and which personas found which kind of issue.+- **Tests** on every push, offline and with no phone: accessibility check, persona matrix, summary, encrypted results ([tests/](tests/)).## Limitsdiff --git a/README.pt-BR.md b/README.pt-BR.mdindex 369581a..e85643c 100644--- a/README.pt-BR.md+++ b/README.pt-BR.md@@ -17,6 +17,7 @@ Multiplatform, Capacitor e .NET MAUI.<p align="center"><a href="assets/localsend-20.mp4"><img src="assets/localsend-20.gif" alt="Gravações de tela reais de 20 testadores com IA usando o LocalSend ao mesmo tempo: 10 emuladores de Android e 10 simuladores de iOS em 14 idiomas, de um Pixel pequeno a um iPad de 13 polegadas. Quando um testador termina, o celular mostra quantos problemas ele encontrou. Abre o vídeo." width="100%"></a><br><sub>Gravações de tela reais da execução no LocalSend, sem os tempos de espera. <a href="assets/localsend-20.mp4">Vídeo completo (MP4)</a> · <a href="docs/runs/localsend-20.md">A execução, aparelho por aparelho</a></sub></p>+[](https://github.com/pierridotite/mobile-agent-testers/actions/workflows/tests.yml)[](https://github.com/pierridotite/mobile-agent-testers/stargazers)[](LICENSE)@@ -153,6 +154,7 @@ toques mais precisos.- **Resultados criptografados**: os logs de um repositório público são públicos, então tudo é criptografado com a sua chave.- **Analytics bloqueado** dentro dos celulares, para os testes nunca mexerem nas suas estatísticas reais.- **Um resumo** na sua máquina: o Claude agrupa os relatórios que descrevem o mesmo bug, então você vê quantas personas encontraram cada um e quais personas encontraram cada tipo de problema.+- **Testes** a cada push, offline e sem celular: verificação de acessibilidade, matriz de personas, resumo, resultados criptografados ([tests/](tests/)).## Limitesdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 024392a..ae801a7 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -16,6 +16,7 @@<p align="center"><a href="assets/localsend-20.mp4"><img src="assets/localsend-20.gif" alt="20 个 AI 测试员同时使用 LocalSend 的真实录屏:10 台 Android 模拟器和 10 台 iOS 模拟器,14 种语言,从小屏 Pixel 到 13 英寸 iPad。测试员完成后,手机上会显示它发现的问题数量。点击打开视频。" width="100%"></a><br><sub>LocalSend 那次运行的真实录屏,已剪掉空闲时间。<a href="assets/localsend-20.mp4">完整视频(MP4)</a> · <a href="docs/runs/localsend-20.md">逐台设备查看这次运行</a></sub></p>+[](https://github.com/pierridotite/mobile-agent-testers/actions/workflows/tests.yml)[](https://github.com/pierridotite/mobile-agent-testers/stargazers)[](LICENSE)@@ -150,6 +151,7 @@ gh workflow run agent-testers.yml -f source_repo=you/app -f app_id=com.you.app \- **结果加密**:公开仓库的日志是公开的,所以一切都用你的密钥加密。- **手机内屏蔽统计分析**,测试不会碰到你的真实数据。- **在你的电脑上生成一份汇总**:Claude 把描述同一缺陷的报告归并起来,你能看到每个缺陷被多少个角色遇到,以及哪些角色发现了哪类问题。+- **每次推送都会测试**,离线、无需手机:无障碍检查、角色矩阵、汇总、加密结果([tests/](tests/))。## 限制diff --git a/scripts/ios/run_agent.sh b/scripts/ios/run_agent.shindex f5b94e6..c6b3d9c 100755--- a/scripts/ios/run_agent.sh+++ b/scripts/ios/run_agent.sh@@ -35,7 +35,7 @@ claude -p "Read $BRIEF and personas.json, then do the mission until the final reCODE=$?if [ -n "$REC" ]; thenkill -INT "$REC" 2>/dev/null- for i in $(seq 1 30); do kill -0 "$REC" 2>/dev/null || break; sleep 1; done+ for _ in $(seq 1 30); do kill -0 "$REC" 2>/dev/null || break; sleep 1; donecat "$RUNNER_TEMP/rec.log"; ls -l "results/$PERSONA/video"fiecho "Agent finished (exit $CODE), $(ls "results/$PERSONA" | wc -l) files"diff --git a/scripts/matrix.py b/scripts/matrix.pyindex 577cf60..ddd9f80 100644--- a/scripts/matrix.py+++ b/scripts/matrix.py@@ -13,6 +13,9 @@ elif wanted == ["all"]:missing = [p for p in wanted if p not in personas]if missing:raise SystemExit(f"Unknown personas: {missing}")+other = [p for p in wanted if personas[p].get("platform", platform) != platform]+if other: # its device settings would be silently replaced by defaults+ raise SystemExit(f"Not {platform} personas: {other}. Put them in the other platform's list.")rows = []for pid in wanted:p = personas[pid]diff --git a/tests/test_a11y.py b/tests/test_a11y.pynew file mode 100644index 0000000..e081b98--- /dev/null+++ b/tests/test_a11y.py@@ -0,0 +1,109 @@+"""scripts/a11y.py: the accessibility line printed under each screen's element list."""+import sys+import unittest+import xml.etree.ElementTree as ET+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))+import a11y # noqa: E402++# Android, 1080x2400 at 420 dpi: 1 dp = 2.625 px, so 48 dp = 126 px.+ANDROID_SCREEN = """<hierarchy rotation="0">+<node class="android.widget.FrameLayout" bounds="[0,0][1080,2400]" clickable="false">+ <node class="android.view.View" clickable="true" bounds="[0,0][1080,2400]" />+ <node class="android.widget.ImageButton" clickable="true" content-desc="" text="" bounds="[950,150][1030,230]" />+ <node class="android.widget.Button" clickable="true" text="Send" bounds="[100,600][980,760]" />+ <node class="android.widget.ImageView" clickable="true" content-desc="Edit" bounds="[100,800][163,863]" />+ <node class="android.widget.FrameLayout" clickable="true" bounds="[100,900][400,1100]">+ <node class="android.widget.TextView" text="Row with child text" bounds="[110,910][390,1090]" />+ </node>+ <node class="androidx.recyclerview.widget.RecyclerView" scrollable="true" bounds="[0,1200][1080,2000]">+ <node class="android.widget.LinearLayout" clickable="true" bounds="[0,1200][1080,1260]"><node text="Cut row" bounds="[0,1200][1080,1260]"/></node>+ <node class="android.widget.LinearLayout" clickable="true" bounds="[0,1300][1080,1500]"><node text="Full row" bounds="[0,1300][1080,1500]"/></node>+ </node>+ <node class="android.widget.Switch" checkable="true" clickable="true" text="" bounds="[900,2100][1000,2160]" />+ <node class="android.widget.Button" clickable="true" enabled="false" text="" bounds="[10,2200][60,2250]" />+</node></hierarchy>"""++IOS_SCREEN = [{"type": "Application", "frame": {"x": 0, "y": 0, "width": 375, "height": 667}, "children": [+ {"type": "Button", "AXLabel": "", "frame": {"x": 330, "y": 50, "width": 30, "height": 30}},+ {"type": "Button", "AXLabel": "Back", "frame": {"x": 0, "y": 44, "width": 80, "height": 44}},+ {"type": "Button", "AXLabel": "Close", "frame": {"x": 20, "y": 100, "width": 28, "height": 28}},+ {"type": "Switch", "AXLabel": "", "AXValue": "1", "frame": {"x": 300, "y": 200, "width": 51, "height": 31}},+ {"type": "Cell", "frame": {"x": 0, "y": 300, "width": 375, "height": 44}, "children": [+ {"type": "StaticText", "AXLabel": "Wi-Fi", "frame": {"x": 16, "y": 310, "width": 100, "height": 20}}]},+ {"type": "ScrollView", "frame": {"x": 0, "y": 400, "width": 375, "height": 200}, "children": [+ {"type": "Button", "AXLabel": "Half visible", "frame": {"x": 100, "y": 580, "width": 100, "height": 30}}]},+ {"type": "Keyboard", "frame": {"x": 0, "y": 450, "width": 375, "height": 217}, "children": [+ {"type": "Button", "AXLabel": "q", "frame": {"x": 3, "y": 460, "width": 31, "height": 42}}]},+]}]+++def ios_app(*children):+ return [{"type": "Application", "frame": {"x": 0, "y": 0, "width": 375, "height": 667}, "children": list(children)}]+++def button(label, x, y, w, h, **extra):+ return {"type": "Button", "AXLabel": label, "frame": {"x": x, "y": y, "width": w, "height": h}, **extra}+++class AndroidCheck(unittest.TestCase):+ def setUp(self):+ self.line = a11y.android(ET.fromstring(ANDROID_SCREEN), 420, 1080, 2400)++ def test_full_line(self):+ self.assertEqual(self.line, "accessibility check (confirm on the screenshot): "+ "2 controls with no name at (990,190) (950,2130); "+ "3 touch targets under 48 dp: 30x30 dp at (990,190), "+ "\"Edit\" 24x24 dp at (131,831), 38x23 dp at (950,2130)")++ def test_name_can_come_from_a_child(self):+ self.assertNotIn("(250,1000)", self.line)++ def test_skips_full_screen_scrim_disabled_button_and_rows_cut_by_the_list(self):+ for centre in ("(540,1200)", "(35,2225)", "(540,1230)"):+ self.assertNotIn(centre, self.line)++ def test_clean_screen_passes(self):+ clean = ET.fromstring('<hierarchy><node clickable="true" text="OK" bounds="[100,100][500,300]"/></hierarchy>')+ self.assertIsNone(a11y.android(clean, 420, 1080, 2400))++ def test_same_bounds_counted_once(self):+ nested = ET.fromstring('<hierarchy><node clickable="true" bounds="[10,10][60,60]">'+ '<node clickable="true" bounds="[10,10][60,60]"/></node></hierarchy>')+ self.assertTrue(a11y.android(nested, 160, 1080, 2400).endswith(": 1 control with no name at (35,35)"))++ def test_long_lists_are_shortened(self):+ nodes = "".join(f'<node clickable="true" bounds="[{x},10][{x + 40},50]"/>' for x in range(0, 600, 100))+ line = a11y.android(ET.fromstring(f"<hierarchy>{nodes}</hierarchy>"), 160, 1080, 2400)+ self.assertIn("6 controls with no name at (20,30) (120,30) (220,30) (320,30) and 2 more", line)+++class IosCheck(unittest.TestCase):+ def test_full_line(self):+ self.assertEqual(a11y.ios(IOS_SCREEN, 375, 667), "accessibility check (confirm on the screenshot): "+ "2 controls with no name at (345,65) (326,216); "+ "2 touch targets under 44 pt: 30x30 pt at (345,65), \"Close\" 28x28 pt at (34,114)")++ def test_keyboard_keys_are_ignored(self):+ self.assertNotIn("(18,481)", a11y.ios(IOS_SCREEN, 375, 667))++ def test_button_cut_by_a_scroll_view_is_ignored(self):+ self.assertIsNone(a11y.ios(ios_app({"type": "ScrollView", "frame": {"x": 0, "y": 400, "width": 375, "height": 200},+ "children": [button("Half", 100, 580, 100, 30)]}), 375, 667))++ def test_disabled_and_off_screen_controls_are_ignored(self):+ self.assertIsNone(a11y.ios(ios_app(button("", 10, 10, 20, 20, enabled=False),+ button("", 10, 900, 20, 20)), 375, 667))++ def test_switch_size_is_not_flagged(self):+ line = a11y.ios(ios_app({"type": "Switch", "AXLabel": "Wi-Fi", "frame": {"x": 300, "y": 200, "width": 51, "height": 31}}),+ 375, 667)+ self.assertIsNone(line)++ def test_clean_screen_passes(self):+ self.assertIsNone(a11y.ios(ios_app(button("Continue", 20, 600, 335, 50)), 375, 667))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_matrix.py b/tests/test_matrix.pynew file mode 100644index 0000000..a27ca51--- /dev/null+++ b/tests/test_matrix.py@@ -0,0 +1,104 @@+"""scripts/matrix.py (one job per persona), personas.json, and the workflow that reads both."""+import json+import os+import re+import subprocess+import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+PERSONAS = json.loads((ROOT / "personas.json").read_text(encoding="utf-8"))+WORKFLOW = (ROOT / ".github/workflows/agent-testers.yml").read_text(encoding="utf-8")+# Values `xcrun simctl ui <udid> content_size` accepts+IOS_TEXT_SIZES = {"extra-small", "small", "medium", "large", "extra-large", "extra-extra-large",+ "extra-extra-extra-large", "accessibility-medium", "accessibility-large",+ "accessibility-extra-large", "accessibility-extra-extra-large",+ "accessibility-extra-extra-extra-large"}+++def matrix(platform, personas):+ env = dict(os.environ, PLATFORM=platform, PERSONAS=personas)+ return subprocess.run([sys.executable, "scripts/matrix.py"], cwd=ROOT, env=env, capture_output=True, text=True)+++def rows(platform, personas):+ out = matrix(platform, personas)+ if out.returncode:+ raise AssertionError(out.stderr)+ key, _, value = out.stdout.strip().partition("=")+ assert key == platform, out.stdout+ return json.loads(value)+++def job(name):+ """Text of one job of the workflow, up to the next job."""+ return re.search(rf"\n {name}:\n(.*?)(?=\n [a-z-]+:\n|\Z)", WORKFLOW, re.S).group(1)+++class Matrix(unittest.TestCase):+ def test_all_takes_every_persona_of_the_platform(self):+ for platform in ("android", "ios"):+ expected = [p["id"] for p in PERSONAS if p["platform"] == platform]+ self.assertEqual([r["persona"] for r in rows(platform, "all")], expected)++ def test_none_and_empty_skip_the_platform(self):+ self.assertEqual(rows("ios", "none"), [])+ self.assertEqual(rows("android", ""), [])++ def test_names_keep_their_order_and_spaces_are_ignored(self):+ names = [p["id"] for p in PERSONAS if p["platform"] == "android"][:3]+ self.assertEqual([r["persona"] for r in rows("android", " , ".join(reversed(names)))], names[::-1])++ def test_unknown_persona_stops_the_run(self):+ out = matrix("android", "nobody")+ self.assertNotEqual(out.returncode, 0)+ self.assertIn("Unknown personas: ['nobody']", out.stderr)++ def test_persona_of_the_other_platform_stops_the_run(self):+ ios_one = next(p["id"] for p in PERSONAS if p["platform"] == "ios")+ out = matrix("android", ios_one)+ self.assertNotEqual(out.returncode, 0)+ self.assertIn(ios_one, out.stderr)++ def test_rows_have_every_key_the_jobs_read(self):+ for platform in ("android", "ios"):+ used = set(re.findall(r"matrix\.([a-z_]+)", job(platform)))+ for row in rows(platform, "all"):+ self.assertFalse(used - set(row), f"{platform} job reads {used - set(row)}, missing in {row}")+++class Personas(unittest.TestCase):+ def test_ids_are_unique_and_simple(self):+ ids = [p["id"] for p in PERSONAS]+ self.assertEqual(len(ids), len(set(ids)))+ for pid in ids:+ self.assertRegex(pid, r"^[a-z][a-z0-9_-]*$")++ def test_each_persona_is_complete(self):+ for p in PERSONAS:+ with self.subTest(p["id"]):+ self.assertIn(p["platform"], ("android", "ios"))+ for key in ("profile", "goal", "locale", "device"):+ self.assertTrue(p.get(key), key)+ self.assertRegex(p["locale"], r"^[a-z]{2,3}(-[A-Za-z0-9]+)*$")+ lat, lon = p["geo"]+ self.assertTrue(-90 <= lat <= 90 and -180 <= lon <= 180)+ self.assertIn(p["device"]["theme"], ("light", "dark"))++ def test_devices_use_values_the_emulators_accept(self):+ for p in PERSONAS:+ d = p["device"]+ with self.subTest(p["id"]):+ if p["platform"] == "ios":+ self.assertIn(d["text_size"], IOS_TEXT_SIZES)+ self.assertTrue(d["simulator"].startswith(("iPhone", "iPad")))+ self.assertIsInstance(d["ios"], int)+ else:+ self.assertIn(d["android_api"], range(29, 37))+ self.assertTrue(0.8 <= float(d["font_scale"]) <= 2.0)+ self.assertTrue(d["profile"] and d["name"])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_results_pipeline.py b/tests/test_results_pipeline.pynew file mode 100644index 0000000..c8ba997--- /dev/null+++ b/tests/test_results_pipeline.py@@ -0,0 +1,84 @@+"""The private results path, end to end and offline: encrypt_results.sh on the runner,+then collect.sh on your machine (with a stand-in for the GitHub CLI)."""+import json+import os+import shutil+import subprocess+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+FAKE_GH = """#!/usr/bin/env bash+# Stands in for the GitHub CLI: the run's artifacts are already in $FAKE_ARTIFACTS+case "$1 $2" in+ "repo view") echo "someone/app" ;;+ "run download") mkdir -p "$5" && cp -R "$FAKE_ARTIFACTS"/. "$5"/ ;;+ *) echo "unexpected gh call: $*" >&2; exit 1 ;;+esac+"""+REPORT = "Settings: the device name is cut to 'Secret C...'\n"+++def run(cmd, **kw):+ return subprocess.run(cmd, capture_output=True, text=True, check=True, **kw)+++def new_key(path):+ run(["openssl", "genpkey", "-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048", "-out", str(path)])+ return path++[email protected](shutil.which("openssl") and shutil.which("bash"), "needs openssl and bash")+class ResultsPipeline(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.tmp = Path(tempfile.mkdtemp())+ cls.key = new_key(cls.tmp / "private.pem")+ # The runner: a checkout with the public key and one persona's results+ cls.runner = cls.tmp / "runner"+ (cls.runner / "results" / "noah").mkdir(parents=True)+ run(["openssl", "pkey", "-in", str(cls.key), "-pubout", "-out", str(cls.runner / "results_public.pem")])+ (cls.runner / "results/noah/report.md").write_text(REPORT, encoding="utf-8")+ (cls.runner / "results/noah/findings.json").write_text(json.dumps(+ {"score": 6, "issues": [{"title": "Device name cut", "severity": "minor", "screen": "Settings"}]}))+ cls.encrypt = run(["bash", str(ROOT / "scripts/encrypt_results.sh"), "noah"], cwd=cls.runner)++ @classmethod+ def tearDownClass(cls):+ shutil.rmtree(cls.tmp)++ def test_runner_uploads_only_ciphertext(self):+ enc = self.runner / "results.enc"+ self.assertEqual(sorted(p.name for p in enc.iterdir()), ["noah.key.bin", "noah.tgz.enc"])+ self.assertFalse((self.runner / "results.tgz").exists())+ self.assertNotIn(b"Secret C", (enc / "noah.tgz.enc").read_bytes())+ # The AES key is only printed inside a mask command, which GitHub hides from the log+ self.assertTrue(all(line.startswith("::add-mask::") for line in self.encrypt.stdout.splitlines()))++ def test_collect_decrypts_and_writes_the_summary(self):+ shutil.copytree(self.runner / "results.enc", self.tmp / "artifacts" / "results-noah")+ bin_dir = self.tmp / "bin"+ bin_dir.mkdir()+ (bin_dir / "gh").write_text(FAKE_GH)+ (bin_dir / "gh").chmod(0o755)+ env = dict(os.environ, PATH=f"{bin_dir}{os.pathsep}{os.environ['PATH']}",+ FAKE_ARTIFACTS=str(self.tmp / "artifacts"), SUMMARY_GROUPING="0")+ out = self.tmp / "run"+ res = subprocess.run(["bash", str(ROOT / "scripts/collect.sh"), "123", str(self.key), str(out)],+ cwd=self.tmp, env=env, capture_output=True, text=True)+ self.assertEqual(res.returncode, 0, res.stdout + res.stderr)+ self.assertEqual((out / "noah/results/noah/report.md").read_text(encoding="utf-8"), REPORT)+ self.assertIn("| minor | Device name cut | 1 (noah) | Settings |",+ (out / "SUMMARY.md").read_text(encoding="utf-8"))++ def test_another_key_cannot_open_it(self):+ other = new_key(self.tmp / "other.pem")+ res = subprocess.run(["openssl", "pkeyutl", "-decrypt", "-inkey", str(other), "-pkeyopt",+ "rsa_padding_mode:oaep", "-in", str(self.runner / "results.enc/noah.key.bin")],+ capture_output=True)+ self.assertNotEqual(res.returncode, 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_summarize.py b/tests/test_summarize.pynew file mode 100644index 0000000..87a6747--- /dev/null+++ b/tests/test_summarize.py@@ -0,0 +1,104 @@+"""scripts/summarize.py: merges every persona's findings.json into SUMMARY.md."""+import contextlib+import io+import json+import os+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT / "scripts"))+import summarize # noqa: E402++FINDINGS = {+ "anna": {"score": 6, "issues": [+ {"title": "Send button cut at large text", "severity": "major", "screen": "Send"},+ {"title": "Icon buttons have no name", "severity": "minor", "screen": "Home"}]},+ "noah": {"score": 8, "issues": [+ {"title": "send button cut at large text", "severity": "minor", "screen": "Send"},+ {"title": "App crashes on rotate | landscape", "severity": "blocker", "screen": "Home"}]},+ "kenji": {"score": 7, "issues": [+ {"title": "Icon buttons have no name", "severity": "minor", "screen": "Settings"}]},+}+++def write_run(base, findings):+ """Same layout as a decrypted run: <persona>/results/<persona>/findings.json"""+ for persona, data in findings.items():+ d = Path(base, persona, "results", persona)+ d.mkdir(parents=True)+ (d / "findings.json").write_text(json.dumps(data) if isinstance(data, dict) else data, encoding="utf-8")+++class Summary(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ write_run(self.tmp.name, FINDINGS)+ self.findings, self.scores = summarize.load(self.tmp.name)++ def tearDown(self):+ self.tmp.cleanup()++ def test_load_reads_every_persona(self):+ self.assertEqual(len(self.findings), 5)+ self.assertEqual(sorted(self.scores), [6, 7, 8])+ self.assertEqual({f["persona"] for f in self.findings}, {"anna", "noah", "kenji"})++ def test_broken_findings_file_is_skipped(self):+ write_run(self.tmp.name, {"olga": "{not json"})+ self.assertEqual(len(summarize.load(self.tmp.name)[0]), 5)++ def test_identical_titles_merge_whatever_the_case(self):+ groups = summarize.group_by_title(self.findings)+ self.assertEqual(sorted(len(g["ids"]) for g in groups), [1, 2, 2])++ def test_most_severe_first_then_most_personas(self):+ md = summarize.render(self.findings, self.scores, summarize.group_by_title(self.findings), False)+ table = [line for line in md.splitlines() if line.startswith("| ") and "Severity" not in line]+ self.assertTrue(table[0].startswith("| blocker | App crashes on rotate \\| landscape"))+ self.assertTrue(table[1].startswith("| major | Send button cut at large text | 2 (anna, noah)"))+ self.assertIn("5 reports from 3 personas, average score 7.0/10.", md)++ def test_no_claude_call_when_grouping_is_off(self):+ with mock.patch.dict(os.environ, {"SUMMARY_GROUPING": "0"}), mock.patch.object(summarize.subprocess, "run") as run:+ self.assertIsNone(summarize.group_with_claude(self.findings))+ run.assert_not_called()++ def test_claude_answer_is_checked_before_use(self):+ # ids follow persona order: anna 1-2, kenji 3, noah 4-5+ answer = {"groups": [+ {"title": "Send button cut", "class": "layout and text size", "ids": [1, "4", 99]},+ {"title": "Icon buttons with no name", "class": "made-up class", "ids": [4, 2, 3]},+ "not a group"]}+ reply = mock.Mock(stdout=json.dumps({"result": "Here:\n" + json.dumps(answer)}))+ with mock.patch.dict(os.environ, {"SUMMARY_GROUPING": "1"}), \+ mock.patch.object(summarize.shutil, "which", return_value="/usr/bin/claude"), \+ mock.patch.object(summarize.subprocess, "run", return_value=reply), \+ contextlib.redirect_stderr(io.StringIO()):+ groups = summarize.group_with_claude(self.findings)+ # unknown id dropped, an id used twice kept once, unknown class emptied+ self.assertEqual(groups[0], {"title": "Send button cut", "class": "layout and text size", "ids": [1, 4]})+ self.assertEqual(groups[1], {"title": "Icon buttons with no name", "class": "", "ids": [2, 3]})+ self.assertEqual([g["ids"] for g in groups[2:]], [[5]]) # a report Claude forgot stays, alone++ def test_unusable_claude_answer_falls_back_to_titles(self):+ with mock.patch.dict(os.environ, {"SUMMARY_GROUPING": "1"}), \+ mock.patch.object(summarize.shutil, "which", return_value="/usr/bin/claude"), \+ mock.patch.object(summarize.subprocess, "run", return_value=mock.Mock(stdout="usage limit")), \+ contextlib.redirect_stderr(io.StringIO()):+ self.assertIsNone(summarize.group_with_claude(self.findings))++ def test_command_line(self):+ out = subprocess.run([sys.executable, str(ROOT / "scripts/summarize.py"), self.tmp.name],+ env=dict(os.environ, SUMMARY_GROUPING="0"), capture_output=True, text=True)+ self.assertEqual(out.returncode, 0, out.stderr)+ self.assertTrue(out.stdout.startswith("# Agent test summary\n"))+ self.assertIn("install the claude CLI", out.stdout)+++if __name__ == "__main__":+ unittest.main()