Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

test: strengthen device regressions, tab grouping, and compare validation (#168)

Qinghe Liacd9b2e4f9ce
diff --git a/tests/device/compare.py b/tests/device/compare.py
index 392eda6..34134df 100644
--- a/tests/device/compare.py
+++ b/tests/device/compare.py
@@ -9,6 +9,8 @@ a phone that locked itself while idle would otherwise make one step 8 to 15 seco
slower when it takes over 20 % and over 0.1 s longer, or over 0.5 s longer (CONTRIBUTING.md, "Required tests",
part 2): those are marked SLOWER and need a reason in the pull request. Exit code 1 if any step is slower or the
two runs didn't do the same steps. No dependencies beyond the standard library.
+
+失败步骤、空轮次、各轮步骤不一致的输入直接返回 1,不把失败的快速返回或丢弃不完整轮次当作性能提升。
"""
import json
@@ -19,12 +21,17 @@ import sys
def medians(path: str):
with open(path, encoding="utf-8") as f:
data = json.load(f)
- runs = [r for r in data["runs"] if r]
+ runs = data["runs"]
+ if not runs or any(not r for r in runs):
+ raise ValueError(f"{path}:没有完整记录的轮次或包含空轮次,比较不可用")
steps = [(s["tool"], json.dumps(s["args"], ensure_ascii=False, sort_keys=True)) for s in runs[0]]
- same = [r for r in runs if [(s["tool"], json.dumps(s["args"], ensure_ascii=False, sort_keys=True)) for s in r] == steps]
- times = [statistics.median(max(r[i]["seconds"] - r[i].get("unlock_seconds", 0), 0) for r in same) for i in range(len(steps))]
+ if any([(s["tool"], json.dumps(s["args"], ensure_ascii=False, sort_keys=True)) for s in r] != steps for r in runs):
+ raise ValueError(f"{path}:各轮步骤不一致,不能丢弃不完整轮次后比较")
failed = sum(not s["ok"] for r in runs for s in r)
- return data.get("device", "?"), steps, times, len(same), len(runs), failed
+ if failed:
+ raise ValueError(f"{path}:包含 {failed} 个失败步骤,不能作为性能比较数据")
+ times = [statistics.median(max(r[i]["seconds"] - r[i].get("unlock_seconds", 0), 0) for r in runs) for i in range(len(steps))]
+ return data.get("device", "?"), steps, times, len(runs), len(runs), failed
def slower(base: float, new: float) -> bool:
@@ -36,7 +43,11 @@ def main() -> int:
if len(sys.argv) != 3:
print(__doc__)
return 2
- (dev_a, steps_a, t_a, n_a, all_a, bad_a), (dev_b, steps_b, t_b, n_b, all_b, bad_b) = map(medians, sys.argv[1:])
+ try:
+ (dev_a, steps_a, t_a, n_a, all_a, bad_a), (dev_b, steps_b, t_b, n_b, all_b, bad_b) = map(medians, sys.argv[1:])
+ except (OSError, ValueError) as e:
+ print(f"比较不可用:{e}")
+ return 1
print(f"base: {sys.argv[1]} {dev_a} ({n_a} of {all_a} runs, {bad_a} failed steps)")
print(f"new: {sys.argv[2]} {dev_b} ({n_b} of {all_b} runs, {bad_b} failed steps)")
wrong = 0
diff --git a/tests/device/device.py b/tests/device/device.py
index 7da0f2a..eae7a9c 100644
--- a/tests/device/device.py
+++ b/tests/device/device.py
@@ -27,6 +27,15 @@ APPEARED = T("已出现", "Appeared")
NO_KEYBOARD = T("屏幕上没有键盘", "No keyboard on screen")
AFTER = T("操作后的界面", "after the action")
UNAVAILABLE = T("WDA 不可用", "WDA unavailable") # the phone can't be controlled right now: not an answer to the call
+MANUAL_UNLOCK = T("需要人工解锁", "unlock it by hand")
+
+
+class ManualUnlockRequired(RuntimeError):
+ """当前调用已结束且明确要求人工解锁;记录失败后停止后续操作。"""
+
+
+def manual_unlock_required(text: str, is_error: bool) -> bool:
+ return is_error and any(s in text for s in MANUAL_UNLOCK)
def ready(status_text: str) -> bool:
@@ -71,17 +80,30 @@ def elements(text: str) -> list[Element]:
def tabs(text: str) -> list[Element]:
- """A tab bar's buttons: a row of three or more buttons of which exactly one says it is selected (value 1; the
- others say 0 natively, nothing through WDA). Found by what they say about themselves, not by their names, which
- follow the phone's language, nor by where the bar is (the bottom on an iPhone, the top on an iPad)"""
+ """找水平相邻的一组标签按钮,不按文字或顶部/底部位置判断。
+
+ iPad 的工具栏按钮和标签可能在同一行,必须先按间距分组,不能把远处的编辑/添加算作标签。
+ 每组至少三个按钮且仅一个 value=1;原生未选中时为 0,WDA 则可能不返回 value。
+ """
rows: dict[tuple[float, float], list[Element]] = {}
for e in elements(text):
if e.kind == "Button":
rows.setdefault((e.y, e.h), []).append(e)
+ candidates = []
for row in rows.values():
- if len(row) >= 3 and sum(e.value == "1" for e in row) == 1 and all(e.value in ("0", "1", None) for e in row):
- return sorted(row, key=lambda e: e.x)
- return []
+ groups: list[list[Element]] = []
+ right = 0.0
+ for e in sorted(row, key=lambda e: e.x):
+ if not groups or e.x - e.w / 2 > right + e.h:
+ groups.append([e])
+ right = e.x + e.w / 2
+ else:
+ groups[-1].append(e)
+ right = max(right, e.x + e.w / 2)
+ for group in groups:
+ if len(group) >= 3 and sum(e.value == "1" for e in group) == 1 and all(e.value in ("0", "1", None) for e in group):
+ candidates.append(group)
+ return max(candidates, key=len, default=[])
@dataclass
diff --git a/tests/device/run.py b/tests/device/run.py
index a839d97..f568001 100644
--- a/tests/device/run.py
+++ b/tests/device/run.py
@@ -64,6 +64,7 @@ class Runner:
self.records: list[dict] = []
self.quiet = False
self.sizes: list[tuple[int, int] | None] = [] # the pictures in the last answer
+ self.last_status = "" # 保留准备阶段的原始状态,避免把未取得尺寸的默认值误认为设备返回了 0×0。
def fail(self, name: str, why: str):
"""A check the step's own expectations don't cover"""
@@ -106,6 +107,10 @@ class Runner:
flag = "".join(f"\n FAILED: {w}" for w in wrong) if wrong else ""
head = f"=== {name} {json.dumps(args, ensure_ascii=False)} {dt:.2f}s{' ERROR' if res.is_error else ''}"
print(head + "\n" + "\n".join(out) + flag, flush=True)
+ if dev.manual_unlock_required(text, bool(res.is_error)):
+ if not wrong:
+ self.fail(name, "人工解锁阻塞不能作为预期拒绝的通过结果")
+ raise dev.ManualUnlockRequired(text)
return text
async def look(self, with_apps: bool = True) -> dev.Device:
@@ -114,6 +119,7 @@ class Runner:
try:
d = dev.Device()
status = await self.step("iphone_status")
+ self.last_status = status
d.model, d.ios, d.udid = dev.controlled(await self.step("iphone_list_devices"), status)
dev.read_status(d, status)
if with_apps:
@@ -179,6 +185,7 @@ async def main() -> int:
params = StdioServerParameters(command=cmd[0], args=cmd[1:], env=dict(os.environ))
t0 = time.time()
runs = []
+ blocked = False
async with connect(params) as session:
await session.initialize()
r = Runner(session, shots)
@@ -190,24 +197,31 @@ async def main() -> int:
print(f"### {d.line()}", flush=True)
if not steps and not (d.w and d.h):
print("--- the screen's size is unknown (is the daemon ready? `iphone-control status`)", flush=True)
+ print("--- 准备阶段的原始 iphone_status 响应(0×0 摘要也可能仅表示未取得尺寸字段):\n" + r.last_status, flush=True)
return 1
- for i in range(a.repeat):
- if a.repeat > 1:
- print(f"### run {i + 1} of {a.repeat}", flush=True)
- r.records = []
- if steps:
- for name, args, *expect in steps:
- if name == "sleep":
- await asyncio.sleep(float(args))
- else:
- await r.step(name, args, **(expect[0] if expect else {}))
- else:
- await default_steps(r, d)
- runs.append(r.records)
- now = await r.look(with_apps=False)
- if now.udid != d.udid:
- r.failed += 1
- print(f"FAILED: the device changed during the run: it was {d.udid}, now {now.udid or 'none'}", flush=True)
+ try:
+ for i in range(a.repeat):
+ if a.repeat > 1:
+ print(f"### run {i + 1} of {a.repeat}", flush=True)
+ r.records = []
+ if steps:
+ for name, args, *expect in steps:
+ if name == "sleep":
+ await asyncio.sleep(float(args))
+ else:
+ await r.step(name, args, **(expect[0] if expect else {}))
+ else:
+ await default_steps(r, d)
+ runs.append(r.records)
+ except dev.ManualUnlockRequired:
+ blocked = True
+ runs.append(r.records) # 保留失败的部分轮次,不再发送后续操作或下一轮。
+ print("ABORT: manual unlock required;剩余步骤未执行,需要在设备上人工解锁", flush=True)
+ if not blocked:
+ now = await r.look(with_apps=False)
+ if now.udid != d.udid:
+ r.failed += 1
+ print(f"FAILED: the device changed during the run: it was {d.udid}, now {now.udid or 'none'}", flush=True)
if a.json:
with open(a.json, "w", encoding="utf-8") as f:
json.dump({"device": d.line(), "command": shlex.join(cmd), "runs": runs}, f, ensure_ascii=False, indent=1)
diff --git a/tests/device/scenarios.py b/tests/device/scenarios.py
index a6d28a7..7ba7744 100644
--- a/tests/device/scenarios.py
+++ b/tests/device/scenarios.py
@@ -92,6 +92,8 @@ class Phone:
res = await asyncio.wait_for(self.s.call_tool(name, args or {}), timeout)
dt = time.time() - t
text = "\n".join(c.text for c in res.content if c.type == "text")
+ if dev.manual_unlock_required(text, bool(res.is_error)):
+ raise dev.ManualUnlockRequired(text)
sizes = [dev.jpeg_size(base64.b64decode(c.data)) for c in res.content if c.type == "image"]
return bool(res.is_error), text, dt, sizes
@@ -474,6 +476,10 @@ async def main() -> int:
t = time.time()
try:
await SCENARIOS[name](p)
+ except dev.ManualUnlockRequired as e:
+ check(name, "manual unlock required", False, str(e))
+ print("ABORT: manual unlock required;剩余场景未执行,需要在设备上人工解锁", flush=True)
+ break
except Exception as e: # noqa: BLE001 - a scenario that blew up is a failure, the next one still runs
traceback.print_exc()
check(name, f"scenario raised {type(e).__name__}", False, str(e))
diff --git a/tests/device/test_compare.py b/tests/device/test_compare.py
new file mode 100644
index 0000000..407bf70
--- /dev/null
+++ b/tests/device/test_compare.py
@@ -0,0 +1,48 @@
+"""耗时比较器的离线回归:失败和不完整的数据不能被当成性能提升。"""
+import contextlib
+import io
+import json
+from pathlib import Path
+import sys
+import tempfile
+import unittest
+from unittest.mock import patch
+
+import compare
+
+
+def step(tool="iphone_status", seconds=0.2, ok=True):
+ return {"tool": tool, "args": {}, "seconds": seconds, "unlock_seconds": 0, "ok": ok}
+
+
+class CompareTests(unittest.TestCase):
+ def compare_runs(self, old, new):
+ with tempfile.TemporaryDirectory() as folder:
+ a, b = Path(folder)/"old.json", Path(folder)/"new.json"
+ a.write_text(json.dumps({"device": "fixture", "runs": old}))
+ b.write_text(json.dumps({"device": "fixture", "runs": new}))
+ with patch.object(sys, "argv", ["compare.py", str(a), str(b)]), contextlib.redirect_stdout(io.StringIO()):
+ return compare.main()
+
+ def test_valid_equal_runs_pass(self):
+ self.assertEqual(self.compare_runs([[step()]], [[step()]]), 0)
+
+ def test_slower_valid_run_fails(self):
+ self.assertEqual(self.compare_runs([[step()]], [[step(seconds=0.8)]]), 1)
+
+ def test_failed_new_run_is_not_accepted_as_faster(self):
+ self.assertEqual(self.compare_runs([[step()]], [[step(seconds=0.001, ok=False)]]), 1)
+
+ def test_failed_baseline_is_not_accepted(self):
+ self.assertEqual(self.compare_runs([[step(ok=False)]], [[step()]]), 1)
+
+ def test_incomplete_run_is_not_silently_dropped(self):
+ whole = [step(), step("iphone_screenshot")]
+ self.assertEqual(self.compare_runs([whole, [step()]], [whole]), 1)
+
+ def test_empty_run_is_not_silently_dropped(self):
+ self.assertEqual(self.compare_runs([[step()], []], [[step()]]), 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/device/test_device.py b/tests/device/test_device.py
index c0b506a..deee20b 100644
--- a/tests/device/test_device.py
+++ b/tests/device/test_device.py
@@ -41,6 +41,28 @@ class DeviceTests(unittest.TestCase):
text = 'Button "甲" value="1" @(10,54) 20x36\nButton "乙" value="1" @(40,54) 20x36\nButton "丙" @(70,54) 20x36'
self.assertEqual(dev.tabs(text), [])
+ def test_tab_bar_excludes_separate_toolbar_buttons_on_same_row(self):
+ text = (
+ 'Button "编辑" @(42,54) 59x36\n'
+ 'Button "世界时钟" value="1" @(404,54) 101x36\n'
+ 'Button "闹钟" @(488,54) 67x36\n'
+ 'Button "秒表" @(554,54) 67x36\n'
+ 'Button "计时器" @(628,54) 84x36\n'
+ 'Button "添加" @(992,54) 36x36'
+ )
+ self.assertEqual([e.label for e in dev.tabs(text)], ["世界时钟", "闹钟", "秒表", "计时器"])
+
+ def test_selected_done_button_is_not_mistaken_for_a_tab(self):
+ text = (
+ 'Button "完成" value="1" @(42,54) 59x36\n'
+ 'Button "世界时钟" @(404,54) 101x36\n'
+ 'Button "闹钟" @(488,54) 67x36\n'
+ 'Button "秒表" @(554,54) 67x36\n'
+ 'Button "计时器" @(628,54) 84x36\n'
+ 'Button "添加" @(992,54) 36x36'
+ )
+ self.assertEqual(dev.tabs(text), [])
+
def test_ipad_twofold_region_is_valid(self):
self.assertTrue(dev.enlarged_region((682, 80), 341, 40))
self.assertTrue(dev.enlarged_region((600, 168), 143, 40))
@@ -81,6 +103,13 @@ class DeviceTests(unittest.TestCase):
self.assertEqual(dev.judge({"max_s": 1}, text, False, 9.2, []), [])
self.assertTrue(dev.judge({"max_s": 1}, text, False, 10, []))
+ def test_manual_unlock_stops_only_on_an_explicit_error(self):
+ for text in dev.MANUAL_UNLOCK:
+ self.assertTrue(dev.manual_unlock_required(text, True))
+ self.assertFalse(dev.manual_unlock_required(text, False))
+ for text in ("", "WDA unavailable", "Not found", "调用方已取消"):
+ self.assertFalse(dev.manual_unlock_required(text, True))
+
def test_unavailable_status_is_not_ready_even_with_screen_size(self):
self.assertTrue(dev.ready("Screen: 1024x768 points"))
self.assertFalse(dev.ready("WDA unavailable\nScreen: 1024x768 points"))