# -*- coding: utf-8 -*- """修测试里的 get() 帮助函数:裸 urlopen 不带 UA 会被 Cloudflare 拦。 test_relay_e2e.py 里的 get() 是这么写的: with urllib.request.urlopen(URL + path, timeout=timeout) as resp: urlopen 直接接 URL 字符串时不能带 headers, 必须包一个 Request 才行。三个测试脚本里的 post() 已经改对了, get() 还没改。 """ from __future__ import annotations import re import sys from pathlib import Path TESTS = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote\_tests") FILES = ["test_relay_e2e.py", "test_relay_local.py", "test_relay_admin_login.py"] # 匹配:with urllib.request.urlopen(<非 req 变量>, ...) as : PATTERN = re.compile( r"urllib\.request\.urlopen\(\s*(URL \+ path|RELAY_URL \+ path)\s*," r"\s*(timeout=[^)]*)\)") def main() -> int: ok = True for name in FILES: path = TESTS / name if not path.is_file(): continue text = path.read_text(encoding="utf-8") if "_UA" not in text: print(f" {name}: 没有 _UA,跳过") continue hits = PATTERN.findall(text) if not hits: print(f" {name}: get() 已经改过") continue # 把每处换成先建 Request 再 urlopen text = PATTERN.sub( lambda m: (f'_req = urllib.request.Request({m.group(1)}, ' f'headers=_UA)\n' f' with urllib.request.urlopen(_req, {m.group(2)}) ' f'as resp:'), text) # 上面的替换会把 "with " 留在前面,形成 "with _req = ..." 这种错误 text = text.replace("with _req = urllib.request.Request(", "_req = urllib.request.Request(") path.write_text(text, encoding="utf-8", newline="\n") import ast try: ast.parse(text) print(f" {name}: 改了 {len(hits)} 处,语法 OK") except SyntaxError as exc: print(f" {name}: 语法错误 {exc}") ok = False return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())