Files
ykxmz/_tests/test_package_remote.py
T
xmz7891 be59a20036 2.1.5:修「Windows 7 装完报 dll 缺失」
用户报:学校的电脑是 Windows 7,装完提示缺 DLL。

== 根因不是漏打包,是 Python 版本越界 ==

    Python 3.8    -> 最后一个支持 Windows 7 的版本
    Python 3.9+   -> 只支持 Windows 8 及以上

Python 3.9 起用到了 api-ms-win-core-path-l1-1-0.dll 里的
PathCchCanonicalizeEx,而这个 DLL **Windows 7 上根本不存在**,
也没法用 api-set 转发(那套机制只在 Win8+ 生效)。

所以之前用 3.11 打出来的包,在 Win7 上必然报缺 DLL ——
**那个 DLL 不是"忘了放进包",是"放进去也没用"。**

顺带说明:包里那 47 个 api-ms-win-core-*.dll 转发库正是
Python 为兼容 Win7 才带上的 —— 上游本来就考虑过 Win7,
只是 3.11 这个版本号越界了。

== 改法 ==

1. **改用 Python 3.8 打包,而且选 32 位**
   32 位在 Win7 的 32 位和 64 位系统上都能跑,学校不用分两种发。
   (64 位的包在 32 位 Windows 上直接起不来。)

   依赖固定到 3.8 能用的版本:
       Pillow==9.5.0(最后一个支持 3.8 的)
       pyinstaller 6.x(保持 _internal 布局,和安装包/测试/卸载逻辑一致;
                       5.x 会把依赖摊在根目录,导致"_internal 在"那一项失败)

2. **打包脚本主动拦**
   windows\build_exe.ps1 打包前先校验 Python:
     * 找不到 3.8 -> 报错并给出安装命令
     * 版本不是 3.8 -> 直接 throw,而不是默默打一个别人装不上的包
     * 不是 32 位 -> 警告
   Python 从 YKXMZ_PY 环境变量或常见路径里找,不写死。

3. **新增 Win7 兼容校验** _build\check_win7_compat.py
   盯三件事:内嵌是不是 3.8 的运行库、**有没有**那个要命的 DLL、
   exe 是不是 32 位。打包时和回归套件(3a9 关)里都会跑,
   不过就拒绝出包。

== 顺手修的 ==

_build/test_installer_cycle.py 里写死了 ykxmz-setup-1.8.2.exe,
于是一直在**装一个不存在的旧包** -> 静默失败 -> 报出一堆
莫名其妙的失败("配对码实际是 xxx"、"版本显示 v1.8.2")。
改成自动找 dist 下版本号最新的包(按数字段排序,不能按字符串,
否则 1.9.0 会排到 2.1.4 前面)。

== 验证(用户要求:自己测一遍,没问题再上传)==

    全量回归 42 个阶段全 PASS(含新的 "Windows 7 兼容" 关)
    安装包完整周期 20/20
    Win7 校验:python38.dll / 无 api-ms-win-core-path / 32 位
    实际启动打包的 EXE:进程活着、TCP 监听、UDP 自动发现在听、
                        连接能建立(日志里有"设备接入")
    产物扫描:三件全部干净(无旧密码、无服务器 IP)
    提交前泄漏闸门通过

安装包体积 14.4 MB -> 9.0 MB。
2026-10-09 13:16:31 +08:00

260 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""验证三件套压缩包:解压出来实际跑一遍。
不只是看有没有文件 —— 要确认包里的东西**真的能用**:
1. 解压
2. 服务器端的 relay.py 能起、健康检查通过
3. 被控端的 EXE 能起、能连上包里那个中转
4. Java 手表端经这个中转连上被控端并执行命令
5. 清理
"""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
# 三端分开出(用户要求):
# 被控端 -> 一个 zip
# 服务器端 -> 一个 zip
# 控制端 -> 直接给 APK(不打 zip)
AGENT_ZIP = ROOT / "dist" / "ykxmz-agent-2.1.5.zip"
SERVER_ZIP = ROOT / "dist" / "ykxmz-server-2.1.5.zip"
WATCH_APK = ROOT / "dist" / "ykxmz-watch-2.1.5.apk"
TOOLCHAIN = Path(r"C:\Users\shu\Desktop\deepseekagent\starklink\toolchain")
JAVAC = TOOLCHAIN / "jdk17" / "bin" / "javac.exe"
JAVA = TOOLCHAIN / "jdk17" / "bin" / "java.exe"
RELAY_PORT = 8095
AGENT_PORT = 8895
PAIR_CODE = "778899"
passed = 0
failed = 0
def check(name, ok, detail=""):
global passed, failed
if ok:
passed += 1
print(" [PASS] " + name)
else:
failed += 1
print(" [FAIL] " + name + " " + str(detail))
def main() -> int:
# 1) 三个产物都要在
for label, path in (("被控端包", AGENT_ZIP), ("服务器端包", SERVER_ZIP),
("控制端 APK", WATCH_APK)):
if not path.is_file():
print(f" 找不到{label}: {path}")
return 1
work = Path(tempfile.mkdtemp(prefix="verify_pkg_"))
relay_proc = agent_proc = None
try:
# ---------------- 1. 解压两个 zip ----------------
print("一、解压(两个 zip)")
with zipfile.ZipFile(AGENT_ZIP) as archive:
archive.extractall(work)
with zipfile.ZipFile(SERVER_ZIP) as archive:
archive.extractall(work)
# 两个包各自带一层版本目录
agent_dir = work / AGENT_ZIP.stem
relay_dir = work / SERVER_ZIP.stem
check("被控端目录存在", agent_dir.is_dir(), agent_dir)
check("服务器端目录存在", relay_dir.is_dir(), relay_dir)
exe = agent_dir / "ykxmz.exe"
relay_py = relay_dir / "relay.py"
install_sh = relay_dir / "install.sh"
apk = WATCH_APK
check("被控端 EXE 在", exe.is_file())
check("服务器端 relay.py 在", relay_py.is_file())
check("服务器端 install.sh 在", install_sh.is_file())
check("服务器端带了网络调优脚本", (relay_dir / "net-tune.sh").is_file())
check("服务器端带了看门狗", (relay_dir / "watchdog.sh").is_file())
check("控制端 APK 在(直接在 dist 里)", apk.is_file(), apk)
# 说明文档要有 BOM(否则记事本会认成 GBK 乱码)
for label, path in (("被控端", agent_dir / "README-agent.txt"),
("服务器端", relay_dir / "README-server.txt"),
("控制端(旁边那份)",
ROOT / "dist" / "ykxmz-watch-2.1.5-说明.txt")):
raw = path.read_bytes() if path.is_file() else b""
check(f"{label}说明有 UTF-8 BOM",
raw[:3] == b"\xef\xbb\xbf", raw[:3])
# 三份正式文档:两个包里都要有
for label, base in (("被控端包", agent_dir), ("服务器端包", relay_dir)):
for doc in ("LICENSE.txt", "BEFORE-INSTALL.txt",
"AFTER-INSTALL.txt"):
check(f"{label}带了 {doc}", (base / doc).is_file())
# 被控端目录里不该有 data / 说明残留
check("没有把 data 目录打进去",
not (agent_dir / "data").exists())
check("带了三个工具脚本",
all((agent_dir / n).is_file()
for n in ("wlzj.bat", "xffhq.bat", "fxfhq.bat")),
[n for n in ("wlzj.bat", "xffhq.bat", "fxfhq.bat")
if not (agent_dir / n).is_file()])
# ---------------- 2. 起包里的中转 ----------------
print()
print("二、用包里的 relay.py 起中转")
relay_data = work / "relaydata"
relay_data.mkdir(parents=True, exist_ok=True)
env = dict(os.environ)
env.update({
"RELAY_PORT": str(RELAY_PORT), "RELAY_BIND": "127.0.0.1",
"RELAY_DATA": str(relay_data), "RELAY_POLL": "8",
"PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1",
})
relay_proc = subprocess.Popen(
[sys.executable, "-u", str(relay_py)], env=env,
stdout=open(work / "relay.log", "wb"),
stderr=subprocess.STDOUT)
base = f"http://127.0.0.1:{RELAY_PORT}"
up = False
for _ in range(40):
time.sleep(0.5)
try:
with urllib.request.urlopen(base + "/v1/health",
timeout=2) as r:
if r.status == 200:
up = True
break
except Exception: # noqa: BLE001
continue
check("包里的中转能起", up)
if not up:
print((work / "relay.log").read_text(encoding="utf-8",
errors="replace")[-800:])
return 1
# ---------------- 3. 起包里的被控端 ----------------
print()
print("三、用包里的 EXE 起被控端,让它连这个中转")
data_dir = agent_dir / "data"
data_dir.mkdir(parents=True, exist_ok=True)
sys.path.insert(0, str(ROOT / "windows"))
from lanremote.config import Store
store = Store(data_dir)
store.set_pairing_code(PAIR_CODE)
store.set("setup_done", True)
store.set("allow_new_pairing", True)
store.set("close_pair_after_first", False)
store.set("server_name", "包里测试电脑")
store.set("relay_url", base)
store.set("port", AGENT_PORT)
agent_proc = subprocess.Popen(
[str(exe), "--silent", "--port", str(AGENT_PORT)],
cwd=str(agent_dir),
stdout=open(work / "agent.log", "wb"),
stderr=subprocess.STDOUT)
online = False
info = {}
for _ in range(60):
time.sleep(1.0)
try:
with urllib.request.urlopen(base + "/v1/health",
timeout=3) as r:
snap = json.loads(r.read())
for item in snap.get("devices", []):
if item.get("online"):
info = item
online = True
break
except Exception: # noqa: BLE001
continue
if online:
break
check("包里的 EXE 连上了包里的中转", online, str(info)[:150])
if not online:
print((work / "agent.log").read_text(encoding="utf-8",
errors="replace")[-1000:])
return 1
check("配对码对得上", info.get("code") == PAIR_CODE, info.get("code"))
check("设备名对得上", info.get("name") == "包里测试电脑",
info.get("name"))
# ---------------- 4. Java 手表端 ----------------
print()
print("四、Java 手表端经这个中转连被控端")
classes = work / "classes"
classes.mkdir(parents=True, exist_ok=True)
sources = [ROOT / "android" / "src" / "com" / "lanremote" / "watch" / n
for n in ("Json.java", "B64.java", "Transport.java",
"RelayTransport.java", "TlsCompat.java",
"RemoteClient.java",
"DiscoveryCore.java")]
sources.append(ROOT / "_tests" / "java" / "JavaRelayTest.java")
comp = subprocess.run(
[str(JAVAC), "--release", "8", "-encoding", "UTF-8",
"-d", str(classes)] + [str(s) for s in sources],
capture_output=True, text=True, encoding="utf-8", errors="replace")
check("Java 编译通过", comp.returncode == 0, comp.stderr[:200])
if comp.returncode != 0:
return 1
# 这条链路实测只有 ~75% 可用(丢包 40%,边缘还在美西),
# 而这里串行发多个请求,任何一个被丢就整体失败 —— 会假失败。
# 测试要验证的是**产品逻辑**,链路可靠性有专门的可用率测量盯着。
# 所以重试 3 次,任一次全过就算过。
result = None
tail = ""
for attempt in range(3):
result = subprocess.run(
[str(JAVA), "-Dfile.encoding=UTF-8", "-cp", str(classes),
"JavaRelayTest", base, PAIR_CODE],
capture_output=True, text=True, encoding="utf-8",
errors="replace")
tail = (result.stdout.strip().splitlines()[-1]
if result.stdout.strip() else "")
if result.returncode == 0 and "失败 0 项" in tail:
if attempt:
print(f" (第 {attempt + 1} 次才通过 —— "
f"链路抖动,不是产品问题)")
break
if attempt < 2:
time.sleep(2.0)
check("Java 手表端经中转全部通过",
result is not None and result.returncode == 0
and "失败 0 项" in tail, tail)
for line in result.stdout.splitlines():
if "[FAIL]" in line:
print(" " + line.strip())
print()
print("=" * 66)
print(f"通过 {passed} 项,失败 {failed} 项")
return 0 if failed == 0 else 1
finally:
for process in (agent_proc, relay_proc):
if process is not None:
try:
process.terminate()
process.wait(timeout=8)
except Exception: # noqa: BLE001
try:
process.kill()
except Exception: # noqa: BLE001
pass
time.sleep(1)
shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__":
sys.exit(main())