"""测三个"操作手机"的工具:读通知 / 开 App / 调音量。 ★ 这三个都属于"会真的动手机"的能力,所以除了正常路径, 重点测**失败路径**:权限没开、App 不存在、系统拒绝改音量。 这些必须**如实报错**,不能假装成功,也不能返回一个看着正常的空结果。 """ import json import sys import urllib.error import urllib.request try: sys.stdout.reconfigure(encoding="utf-8", errors="replace") except Exception: pass URL = "http://127.0.0.1:15199" fails = [] def call(path, payload=None, method="POST", timeout=90): data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None req = urllib.request.Request( URL + path, data=data, method=method, headers={"Content-Type": "application/json; charset=utf-8"}, ) try: with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode("utf-8")) except urllib.error.HTTPError as e: return json.loads(e.read().decode("utf-8", "replace")) def tool(name, args): """跑一个工具。 ★ 返回的是**顶层的 {ok, result} 或 {ok:false, error}**, 不是只有 result —— 第一版测试脚本只看了 result,于是工具抛错时 拿到空 dict,三条断言全红,看起来像"错误信息没给", 其实信息给得挺全(在顶层 error 里)。 测试脚本必须按**真实响应形状**取值。 """ return call("/api/tools/run", {"name": name, "args": args}) def tool_err(r): """从工具响应里取错误文本(顶层 error 或 result.error)""" if not isinstance(r, dict): return "" if r.get("error"): return str(r["error"]) return str((r.get("result") or {}).get("error") or "") def check(cond, label, detail=""): print(f" {'✓' if cond else '✗'} {label}" + (f" {detail}" if detail else "")) if not cond: fails.append(label) print("=== 0. 三个工具都被发现了吗 ===") tools = call("/api/tools", None, "GET") py = tools.get("python") or tools.get("tools") or [] if isinstance(py, dict): py = py.get("python") or [] names = [t.get("name") for t in py if isinstance(t, dict)] for n in ("notifications", "apps", "volume"): check(n in names, f"{n} 被内核发现") print("\n=== 1. 音量:读 ===") r = tool("volume", {"action": "get"}) res = (r or {}).get("result") or {} streams = res.get("streams") or [] check(bool(streams), f"读出 {len(streams)} 个音量流") for s in streams[:3]: print(f" {s.get('stream')}: {s.get('percent')}% ({s.get('level')})") print("\n=== 2. 音量:写(set 百分比 → 自动换算成档位)===") r = tool("volume", {"action": "set", "stream": "music", "mode": "set", "value": 40}) res = (r or {}).get("result") or {} if res.get("error"): print(" (这台机器不让改媒体音量:", str(res["error"])[:80], ")") else: check(res.get("percent") is not None, f"设置后读到 {res.get('percent')}%") check(abs(int(res.get("percent") or 0) - 40) <= 10, "百分比落在 40% 附近(说明换算对了)", f"实际 {res.get('percent')}%") print("\n=== 3. 音量:up / mute / unmute ===") r = tool("volume", {"action": "set", "stream": "music", "mode": "up"}) u = (r or {}).get("result") or {} check(u.get("before") is not None and u.get("current") is not None, "up 有前后值", f"{u.get('before')} -> {u.get('current')}") r = tool("volume", {"action": "set", "stream": "music", "mode": "mute"}) m = (r or {}).get("result") or {} check(m.get("current") == 0 or bool(str(m.get("error") or "")), "mute 生效或如实报错", f"current={m.get('current')} err={str(m.get('error'))[:40]}") r = tool("volume", {"action": "set", "stream": "music", "mode": "unmute"}) n = (r or {}).get("result") or {} check(int(n.get("current") or 0) > 0 or bool(str(n.get("error") or "")), "unmute 恢复到非零", f"current={n.get('current')}") print("\n=== 4. App:列出来 ===") r = tool("apps", {"action": "list"}) res = (r or {}).get("result") or {} check((res.get("total_installed") or 0) > 0, f"装了 {res.get('total_installed')} 个 App") for a in (res.get("apps") or [])[:4]: print(f" {a.get('label')} ({a.get('package')})") print("\n=== 5. App:找一个真实存在的 ===") r = tool("apps", {"action": "find", "name": "设置"}) res = (r or {}).get("result") or {} found = res.get("apps") or [] check(bool(found), f"找到 {len(found)} 个含「设置」的", (found[0].get("label") if found else "")) print("\n=== 6. ★ App:找不到时要**如实报错并给相近的名字** ===") r = tool("apps", {"action": "open", "name": "这个App绝对不存在xyz"}) check(r.get("ok") is False, "没有假装打开成功", f"ok={r.get('ok')}") err = tool_err(r) check("没找到" in err, "错误说清了'没找到'", err[:90]) check("action=" in err, "错误里给了下一步(说了该调哪个 action)", err[:110]) print("\n=== 7. ★ 通知:权限没开时必须报错(不是空列表)===") r = tool("notifications", {"action": "access"}) res = (r or {}).get("result") or {} granted = bool(res.get("granted")) print(f" 通知使用权:{'已开' if granted else '没开'}") if not granted: r2 = tool("notifications", {"action": "list"}) check(r2.get("ok") is False, "没权限时**工具失败**(不是返回空列表)") err2 = tool_err(r2) check("通知使用权" in err2, "错误说清了是权限问题", err2[:80]) check("设置" in err2 and "通知使用权" in err2, "错误里说了怎么开(设置路径)", err2[-90:]) else: r2 = tool("notifications", {"action": "list"}) res2 = (r2 or {}).get("result") or {} check("notifications" in res2, f"有权限 → 读到 {res2.get('count')} 条") print("\n=== 8. 通知:open_settings 能跳设置页 ===") r = tool("notifications", {"action": "open_settings"}) res = (r or {}).get("result") or {} check(bool(res.get("opened")) or bool(res.get("error")), "跳转设置页(或如实报错)", str(res)[:80]) print() if fails: print(f"❌ {len(fails)} 项不合格:") for f in fails: print(" -", f) sys.exit(1) print("✅ 全部通过")