fix(wifi_adb): 修 3 处导致 WiFi-ADB 自动连接失败的解析 bug
1) get_device_ip 把 ip route 输出里的网段当 IP 返回 原代码看到 "192.168.5.0/24 ... src 192.168.5.2" 时,扫到的第一个含 3 个点的字段是 "192.168.5.0/24",结果用 0/24 当 IP 调 adb connect 必然失败。 改成显式从 "src <ip>" 取,并优先 wlan 接口;加 ip addr show / ifconfig 兜底。 2) auto_connect_wifi_adb 顺序错误 原代码先 tcpip 5555(让设备 adbd 重启、USB 链路断开)再 get_device_ip(需要 USB), USB 已断必然取不到 IP。改成先 get_device_ip 再 enable_wifi_adb 再 connect。 3) connect_wifi_adb 把"未授权 / 连接被拒"当成功 adb connect 在 unauthorized / cannot connect / failed to authenticate 等场景下 returncode 也是 0;以前只看 returncode + "connected" 子串,未授权也判成功。 改成显式列出失败关键词,并对未授权给清晰的中文提示。 新增 20 个 wifi_adb 单元测试覆盖 3 处回归场景。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
a92cec4ff9
commit
23d370ae22
2 files changed
+391
-59
No files matched your search
+155
-59
@@ -108,7 +108,7 @@ def connect_wifi_adb(
|
||||
|
||||
Args:
|
||||
adb_exe: ADB可执行文件路径
|
||||
ip_address: 设备IP地址
|
||||
ip_address: 设备IP地址(支持 ip 或 ip:port)
|
||||
port: 端口号,默认5555
|
||||
|
||||
Returns:
|
||||
@@ -119,10 +119,7 @@ def connect_wifi_adb(
|
||||
return False, "ADB路径或IP地址为空"
|
||||
|
||||
# 支持 ip:port 或单纯 ip 的两种情况
|
||||
if ":" in ip_address:
|
||||
target = ip_address
|
||||
else:
|
||||
target = f"{ip_address}:{port}"
|
||||
target = ip_address if ":" in ip_address else f"{ip_address}:{port}"
|
||||
|
||||
# 连接到设备
|
||||
proc = subprocess.run(
|
||||
@@ -135,14 +132,40 @@ def connect_wifi_adb(
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
output = (proc.stdout or "") + "\n" + (proc.stderr or "")
|
||||
output = ((proc.stdout or "") + "\n" + (proc.stderr or "")).strip()
|
||||
low = output.lower()
|
||||
|
||||
# adb connect 在成功/已连接时常包含 'connected' 或 'already connected' 文本
|
||||
if proc.returncode == 0 and ("connected" in low or "already connected" in low):
|
||||
# adb connect 在很多失败场景下 returncode 也是 0,必须看输出文本
|
||||
# 失败关键词优先判断
|
||||
for fail_kw in (
|
||||
"failed to authenticate",
|
||||
"unauthorized",
|
||||
"cannot connect",
|
||||
"unable to connect",
|
||||
"connection refused",
|
||||
"no route to host",
|
||||
"host is down",
|
||||
"operation timed out",
|
||||
"cannot resolve",
|
||||
):
|
||||
if fail_kw in low:
|
||||
# 给"未授权"特别清晰的提示
|
||||
if "authenticate" in low or "unauthorized" in low:
|
||||
return False, (
|
||||
f"未授权: {target} 尚未授权 ADB 调试。"
|
||||
f"请在手机上确认弹窗(勾选'始终允许这台电脑调试'),然后重试。"
|
||||
)
|
||||
return False, f"连接失败: {output}"
|
||||
|
||||
if "connected" in low or "already connected" in low:
|
||||
return True, f"成功连接到 {target}"
|
||||
else:
|
||||
return False, f"连接失败: {output}"
|
||||
|
||||
# 兜底:returncode 非 0 视为失败
|
||||
if proc.returncode != 0:
|
||||
return False, f"连接失败: {output or '未知错误'}"
|
||||
|
||||
# returncode == 0 但输出未匹配关键词(罕见),按成功处理但提示
|
||||
return True, f"已发送连接请求到 {target}: {output}"
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, "连接WiFi ADB超时"
|
||||
@@ -207,11 +230,11 @@ def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]:
|
||||
Returns:
|
||||
tuple: (成功否, IP地址或错误消息)
|
||||
"""
|
||||
try:
|
||||
if not adb_exe or not device_id:
|
||||
return False, "ADB路径或设备ID为空"
|
||||
if not adb_exe or not device_id:
|
||||
return False, "ADB路径或设备ID为空"
|
||||
|
||||
# 获取网络接口信息
|
||||
# 1) 优先解析 `ip route`,从 "src <ip>" 字段取设备 IP(避免误把网段当 IP)
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[adb_exe, "-s", device_id, "shell", "ip", "route"],
|
||||
capture_output=True,
|
||||
@@ -221,26 +244,86 @@ def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]:
|
||||
check=False,
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
if proc.returncode == 0:
|
||||
# 解析输出获取IP地址
|
||||
lines = proc.stdout.strip().split("\n")
|
||||
for line in lines:
|
||||
if "src" in line:
|
||||
parts = line.split()
|
||||
for part in parts:
|
||||
if part.count(".") == 3: # IP地址格式
|
||||
return True, part
|
||||
return False, "无法从设备获取IP地址"
|
||||
else:
|
||||
error_msg = (proc.stdout or "") + "\n" + (proc.stderr or "")
|
||||
return False, f"获取IP地址失败: {error_msg}"
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, "获取设备IP超时"
|
||||
except Exception as e:
|
||||
return False, f"获取设备IP异常: {str(e)}"
|
||||
|
||||
if proc.returncode == 0 and (proc.stdout or "").strip():
|
||||
# 优先从 wlan0/wlan1 等无线接口的路由里抽 src
|
||||
wlan_ip = ""
|
||||
any_ip = ""
|
||||
for line in proc.stdout.strip().split("\n"):
|
||||
m = re.search(r"\bsrc\s+(\d+\.\d+\.\d+\.\d+)", line)
|
||||
if not m:
|
||||
continue
|
||||
ip = m.group(1)
|
||||
if "wlan" in line:
|
||||
wlan_ip = ip
|
||||
break
|
||||
if not any_ip:
|
||||
any_ip = ip
|
||||
ip = wlan_ip or any_ip
|
||||
if ip and not ip.endswith(".0"):
|
||||
return True, ip
|
||||
|
||||
# 2) 兜底:解析 `ip -f inet addr show`,从 wlan0 / wlan1 / rmnet 里挑 inet
|
||||
try:
|
||||
proc2 = subprocess.run(
|
||||
[adb_exe, "-s", device_id, "shell", "ip", "-f", "inet", "addr", "show"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
)
|
||||
except Exception:
|
||||
proc2 = None
|
||||
|
||||
if proc2 and proc2.returncode == 0 and (proc2.stdout or "").strip():
|
||||
# 按接口块分割:以 "数字: 接口名:" 开头的行作为分隔
|
||||
blocks = re.split(r"\n(?=\d+:\s)", proc2.stdout.strip())
|
||||
wlan_ip = ""
|
||||
any_ip = ""
|
||||
for blk in blocks:
|
||||
head_m = re.match(r"\d+:\s+([\w\.@\-]+):", blk)
|
||||
iface = head_m.group(1) if head_m else ""
|
||||
if "lo" in iface.split("@", 1)[0].lower():
|
||||
continue
|
||||
inet_m = re.search(r"\binet\s+(\d+\.\d+\.\d+\.\d+)", blk)
|
||||
if not inet_m:
|
||||
continue
|
||||
ip = inet_m.group(1)
|
||||
if iface.lower().startswith(("wlan", "wifi")):
|
||||
wlan_ip = ip
|
||||
break
|
||||
if not any_ip:
|
||||
any_ip = ip
|
||||
ip = wlan_ip or any_ip
|
||||
if ip:
|
||||
return True, ip
|
||||
|
||||
# 3) 最后兜底:传统 `ifconfig wlan0`
|
||||
try:
|
||||
proc3 = subprocess.run(
|
||||
[adb_exe, "-s", device_id, "shell", "ifconfig", "wlan0"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
)
|
||||
if proc3.returncode == 0:
|
||||
m = re.search(r"inet\s+addr:?\s*(\d+\.\d+\.\d+\.\d+)", proc3.stdout or "")
|
||||
if m:
|
||||
return True, m.group(1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return False, "无法从设备获取IP地址"
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -249,10 +332,17 @@ def auto_connect_wifi_adb(
|
||||
) -> tuple[bool, str]:
|
||||
"""自动启用WiFi ADB并连接设备
|
||||
|
||||
流程:
|
||||
1. 如果 device_id 已经是 ip:port 格式,直接 adb connect
|
||||
2. 否则(USB 序列号):先获取设备 IP(USB 还在线时取) → 再 tcpip 5555 → 再 connect ip:5555
|
||||
|
||||
注意:tcpip 命令会让设备 adbd 重启,USB 链路会短暂断开。
|
||||
所以必须在切 TCP 之前先把 IP 拿到。
|
||||
|
||||
Args:
|
||||
adb_exe: ADB可执行文件路径
|
||||
device_id: 设备ID
|
||||
max_attempts: 最大尝试次数
|
||||
device_id: 设备ID(USB 序列号或 ip:port)
|
||||
max_attempts: 切到 TCP 后重试连接的次数
|
||||
|
||||
Returns:
|
||||
tuple: (成功否, 消息)
|
||||
@@ -261,61 +351,67 @@ def auto_connect_wifi_adb(
|
||||
if not adb_exe or not device_id:
|
||||
return False, "ADB路径或设备ID为空"
|
||||
|
||||
# 先检查当前 adb 设备列表,看 device_id 是否已经以 WiFi 形式存在(ip:port)
|
||||
# 检查 adb devices,看 device_id 是否已经以 WiFi 形式存在(ip:port)
|
||||
try:
|
||||
current = list_adb_devices(adb_exe)
|
||||
except Exception:
|
||||
current = []
|
||||
|
||||
# 如果 device_id 本身就是 ip:port 格式,且已经在 adb devices 中,则视为已连接
|
||||
# 1) device_id 本身就是 ip:port,且已经在 adb devices 中 → 已连接
|
||||
if is_device_wifi_connected(adb_exe, device_id) and device_id in current:
|
||||
return True, f"设备已通过 WiFi 连接: {device_id}"
|
||||
|
||||
# 如果 device_id 是 ip:port 格式但不在 adb devices 中,尝试直接连接这个 target
|
||||
# 2) device_id 是 ip:port 但不在 adb devices 中 → 直接 connect
|
||||
if is_device_wifi_connected(adb_exe, device_id) and device_id not in current:
|
||||
conn_ok, conn_msg = connect_wifi_adb(adb_exe, device_id)
|
||||
if conn_ok:
|
||||
return True, f"直接连接成功: {device_id}"
|
||||
else:
|
||||
return False, f"直接连接失败: {conn_msg}"
|
||||
return False, f"直接连接失败: {conn_msg}"
|
||||
|
||||
# 如果 device_id 是 USB 序列(非 ip:port),执行启用 tcpip 流程作为后备
|
||||
# 3) device_id 是 USB 序列号 → 先取 IP(USB 还在线时),再切 TCP,最后 connect
|
||||
|
||||
# 先获取 IP(必须在 tcpip 切换前完成,否则 USB 断了取不到)
|
||||
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
|
||||
if not ip_success:
|
||||
return False, f"获取IP地址失败: {ip_msg}"
|
||||
|
||||
# 提取 ip 或 ip:port
|
||||
m = re.search(r"(\d+\.\d+\.\d+\.\d+)(?::(\d+))?", ip_msg)
|
||||
if m:
|
||||
host = m.group(1)
|
||||
port_found = m.group(2) or "5555"
|
||||
target = f"{host}:{port_found}"
|
||||
else:
|
||||
return False, f"获取的IP格式异常: {ip_msg}"
|
||||
|
||||
# 切到 TCP 模式(这一步会让 adbd 重启,USB 短暂断开)
|
||||
enable_success, enable_msg = enable_wifi_adb(adb_exe, device_id)
|
||||
if not enable_success:
|
||||
return False, f"启用WiFi ADB失败: {enable_msg}"
|
||||
|
||||
# 等待设备重启开始
|
||||
# 等待设备 adbd 重启完成
|
||||
time.sleep(3)
|
||||
|
||||
# 尝试多次获取IP并连接(优先提取纯 IPv4 地址或 ip:port)
|
||||
# 多次尝试连接(adbd 重启可能需要一点时间)
|
||||
last_msg = ""
|
||||
for attempt in range(max_attempts):
|
||||
wait_time = 5 + attempt * 2
|
||||
wait_time = 2 + attempt * 2
|
||||
time.sleep(wait_time)
|
||||
|
||||
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
|
||||
if not ip_success:
|
||||
if attempt == max_attempts - 1:
|
||||
return False, f"获取IP地址失败: {ip_msg}"
|
||||
continue
|
||||
|
||||
ip_address = ip_msg
|
||||
# 提取 ip 或 ip:port
|
||||
m = re.search(r"(\d+\.\d+\.\d+\.\d+)(?::(\d+))?", ip_address)
|
||||
if m:
|
||||
host = m.group(1)
|
||||
port_found = m.group(2) or "5555"
|
||||
target = f"{host}:{port_found}"
|
||||
else:
|
||||
target = ip_address
|
||||
|
||||
connect_success, connect_msg = connect_wifi_adb(adb_exe, target)
|
||||
last_msg = connect_msg
|
||||
if connect_success:
|
||||
return True, f"自动连接成功! target: {target}"
|
||||
|
||||
if attempt == max_attempts - 1:
|
||||
return False, f"连接失败: {connect_msg}"
|
||||
# 若返回 unauthorized,给用户清晰提示
|
||||
low = (connect_msg or "").lower()
|
||||
if "unauthorized" in low or "authenticate" in low:
|
||||
return False, (
|
||||
f"连接失败:设备 {target} 尚未授权。请在手机上确认 ADB 调试授权"
|
||||
f"(勾选'始终允许这台电脑调试'),然后重试。"
|
||||
)
|
||||
|
||||
return False, "自动连接超时,请稍后重试"
|
||||
return False, f"连接失败(已重试 {max_attempts} 次): {last_msg}"
|
||||
|
||||
except Exception as e:
|
||||
return False, f"自动连接异常: {str(e)}"
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
"""gui_core_pkg.wifi_adb 单元测试。
|
||||
|
||||
覆盖最关键的解析分支(修复 get_device_ip 把网段当 IP / connect_wifi_adb
|
||||
把 unauthorized 当成功 / auto_connect_wifi_adb 在 tcpip 后才取 IP 等)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from gui.gui_core_pkg import wifi_adb
|
||||
|
||||
|
||||
def _proc(stdout: str = "", stderr: str = "", returncode: int = 0):
|
||||
return SimpleNamespace(stdout=stdout, stderr=stderr, returncode=returncode)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# is_device_wifi_connected
|
||||
# ============================================================
|
||||
|
||||
class TestIsDeviceWifiConnected:
|
||||
def test_ip_port_format(self):
|
||||
assert wifi_adb.is_device_wifi_connected("/adb", "192.168.1.5:5555") is True
|
||||
|
||||
def test_usb_serial(self):
|
||||
assert wifi_adb.is_device_wifi_connected("/adb", "MB75DEFQZHZTGMLJ") is False
|
||||
|
||||
def test_empty(self):
|
||||
assert wifi_adb.is_device_wifi_connected("", "") is False
|
||||
|
||||
|
||||
# ============================================================
|
||||
# get_device_ip — 关键 bug:以前会把 "192.168.5.0/24" 当 IP 返回
|
||||
# ============================================================
|
||||
|
||||
class TestGetDeviceIp:
|
||||
IP_ROUTE_NORMAL = "192.168.5.0/24 dev wlan0 proto kernel scope link src 192.168.5.2"
|
||||
IP_ROUTE_MULTI = (
|
||||
"default via 10.0.0.1 dev wlan0\n"
|
||||
"10.0.0.0/24 dev wlan0 proto kernel scope link src 10.0.0.42\n"
|
||||
"192.168.42.0/24 dev rmnet_data0 proto kernel scope link src 192.168.42.1\n"
|
||||
)
|
||||
IP_ADDR_NORMAL = (
|
||||
"1: lo: <LOOPBACK,UP,LOWER_UP>\n"
|
||||
" inet 127.0.0.1/8 scope host lo\n"
|
||||
"33: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP>\n"
|
||||
" inet 192.168.5.2/24 brd 192.168.5.255 scope global wlan0\n"
|
||||
)
|
||||
|
||||
def test_extracts_src_ip_not_subnet(self):
|
||||
"""关键回归:'192.168.5.0/24 ... src 192.168.5.2' 应返回 192.168.5.2 而不是 .0。"""
|
||||
with patch("subprocess.run", return_value=_proc(self.IP_ROUTE_NORMAL, "", 0)):
|
||||
ok, ip = wifi_adb.get_device_ip("/adb", "DEVICE")
|
||||
assert ok is True
|
||||
assert ip == "192.168.5.2"
|
||||
|
||||
def test_prefers_wlan_over_other_interfaces(self):
|
||||
with patch("subprocess.run", return_value=_proc(self.IP_ROUTE_MULTI, "", 0)):
|
||||
ok, ip = wifi_adb.get_device_ip("/adb", "DEVICE")
|
||||
assert ok is True
|
||||
assert ip == "10.0.0.42"
|
||||
|
||||
def test_falls_back_to_addr_show(self):
|
||||
"""ip route 取不到 → ip addr show 兜底。"""
|
||||
calls = {"n": 0}
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
calls["n"] += 1
|
||||
if "route" in cmd:
|
||||
return _proc("", "", 0) # 路由空
|
||||
if "addr" in cmd:
|
||||
return _proc(self.IP_ADDR_NORMAL, "", 0)
|
||||
return _proc("", "", 1)
|
||||
|
||||
with patch("subprocess.run", side_effect=fake_run):
|
||||
ok, ip = wifi_adb.get_device_ip("/adb", "DEVICE")
|
||||
assert ok is True
|
||||
assert ip == "192.168.5.2"
|
||||
|
||||
def test_all_methods_fail(self):
|
||||
with patch("subprocess.run", return_value=_proc("", "", 1)):
|
||||
ok, ip = wifi_adb.get_device_ip("/adb", "DEVICE")
|
||||
assert ok is False
|
||||
|
||||
def test_empty_args(self):
|
||||
ok, _ = wifi_adb.get_device_ip("", "DEVICE")
|
||||
assert ok is False
|
||||
ok, _ = wifi_adb.get_device_ip("/adb", "")
|
||||
assert ok is False
|
||||
|
||||
def test_timeout_returns_false(self):
|
||||
with patch(
|
||||
"subprocess.run",
|
||||
side_effect=subprocess.TimeoutExpired(cmd="adb", timeout=10),
|
||||
):
|
||||
ok, msg = wifi_adb.get_device_ip("/adb", "DEVICE")
|
||||
assert ok is False
|
||||
assert "超时" in msg
|
||||
|
||||
|
||||
# ============================================================
|
||||
# connect_wifi_adb — 关键 bug:unauthorized / failed 也曾被认成功
|
||||
# ============================================================
|
||||
|
||||
class TestConnectWifiAdb:
|
||||
def test_success(self):
|
||||
with patch(
|
||||
"subprocess.run", return_value=_proc("connected to 192.168.5.2:5555", "", 0)
|
||||
):
|
||||
ok, msg = wifi_adb.connect_wifi_adb("/adb", "192.168.5.2")
|
||||
assert ok is True
|
||||
assert "192.168.5.2:5555" in msg
|
||||
|
||||
def test_already_connected(self):
|
||||
with patch(
|
||||
"subprocess.run",
|
||||
return_value=_proc("already connected to 192.168.5.2:5555", "", 0),
|
||||
):
|
||||
ok, _ = wifi_adb.connect_wifi_adb("/adb", "192.168.5.2:5555")
|
||||
assert ok is True
|
||||
|
||||
def test_unauthorized_returns_false_with_clear_message(self):
|
||||
"""以前 'failed to authenticate' 但 returncode=0 会被当成功。"""
|
||||
with patch(
|
||||
"subprocess.run",
|
||||
return_value=_proc("failed to authenticate to 192.168.5.2:5555", "", 0),
|
||||
):
|
||||
ok, msg = wifi_adb.connect_wifi_adb("/adb", "192.168.5.2:5555")
|
||||
assert ok is False
|
||||
assert "未授权" in msg
|
||||
|
||||
def test_cannot_connect(self):
|
||||
with patch(
|
||||
"subprocess.run",
|
||||
return_value=_proc(
|
||||
"cannot connect to 192.168.5.2:5555: Connection refused", "", 1
|
||||
),
|
||||
):
|
||||
ok, msg = wifi_adb.connect_wifi_adb("/adb", "192.168.5.2:5555")
|
||||
assert ok is False
|
||||
assert "连接失败" in msg
|
||||
|
||||
def test_timeout(self):
|
||||
with patch(
|
||||
"subprocess.run",
|
||||
side_effect=subprocess.TimeoutExpired(cmd="adb", timeout=10),
|
||||
):
|
||||
ok, msg = wifi_adb.connect_wifi_adb("/adb", "192.168.5.2:5555")
|
||||
assert ok is False
|
||||
assert "超时" in msg
|
||||
|
||||
def test_appends_default_port_when_missing(self):
|
||||
captured = {}
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
captured["cmd"] = cmd
|
||||
return _proc("connected to 192.168.5.2:5555", "", 0)
|
||||
|
||||
with patch("subprocess.run", side_effect=fake_run):
|
||||
wifi_adb.connect_wifi_adb("/adb", "192.168.5.2")
|
||||
# adb connect 192.168.5.2:5555
|
||||
assert captured["cmd"][-1] == "192.168.5.2:5555"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# auto_connect_wifi_adb — 关键 bug:以前先 tcpip 再 get_device_ip 必然失败
|
||||
# ============================================================
|
||||
|
||||
class TestAutoConnectWifiAdb:
|
||||
def test_already_connected_via_wifi(self):
|
||||
with patch.object(wifi_adb, "list_adb_devices", return_value=["192.168.5.2:5555"]):
|
||||
ok, msg = wifi_adb.auto_connect_wifi_adb("/adb", "192.168.5.2:5555")
|
||||
assert ok is True
|
||||
assert "已通过 WiFi 连接" in msg
|
||||
|
||||
def test_ip_port_input_directly_connects(self):
|
||||
with patch.object(wifi_adb, "list_adb_devices", return_value=[]), \
|
||||
patch.object(wifi_adb, "connect_wifi_adb", return_value=(True, "ok")):
|
||||
ok, msg = wifi_adb.auto_connect_wifi_adb("/adb", "192.168.5.2:5555")
|
||||
assert ok is True
|
||||
assert "直接连接成功" in msg
|
||||
|
||||
def test_usb_serial_gets_ip_before_tcpip(self):
|
||||
"""关键回归:USB 序列号入参时,必须先 get_device_ip 再 enable_wifi_adb。"""
|
||||
order = []
|
||||
|
||||
def get_ip(adb, dev):
|
||||
order.append("get_ip")
|
||||
return True, "192.168.5.2"
|
||||
|
||||
def enable(adb, dev):
|
||||
order.append("tcpip")
|
||||
return True, "ok"
|
||||
|
||||
def connect(adb, target, port="5555"):
|
||||
order.append("connect")
|
||||
return True, "ok"
|
||||
|
||||
with patch.object(wifi_adb, "list_adb_devices", return_value=["MB75DEFQZHZTGMLJ"]), \
|
||||
patch.object(wifi_adb, "get_device_ip", side_effect=get_ip), \
|
||||
patch.object(wifi_adb, "enable_wifi_adb", side_effect=enable), \
|
||||
patch.object(wifi_adb, "connect_wifi_adb", side_effect=connect), \
|
||||
patch.object(wifi_adb.time, "sleep", return_value=None):
|
||||
ok, msg = wifi_adb.auto_connect_wifi_adb("/adb", "MB75DEFQZHZTGMLJ")
|
||||
assert ok is True
|
||||
# get_ip 必须在 tcpip 之前
|
||||
assert order.index("get_ip") < order.index("tcpip")
|
||||
assert order.index("tcpip") < order.index("connect")
|
||||
|
||||
def test_get_ip_failure_returns_false_without_tcpip(self):
|
||||
"""get_device_ip 失败时不应该再切 tcpip 模式。"""
|
||||
with patch.object(wifi_adb, "list_adb_devices", return_value=["MB75DEFQZHZTGMLJ"]), \
|
||||
patch.object(wifi_adb, "get_device_ip", return_value=(False, "no ip")), \
|
||||
patch.object(wifi_adb, "enable_wifi_adb") as mock_enable:
|
||||
ok, msg = wifi_adb.auto_connect_wifi_adb("/adb", "MB75DEFQZHZTGMLJ")
|
||||
assert ok is False
|
||||
assert "获取IP地址失败" in msg
|
||||
mock_enable.assert_not_called()
|
||||
|
||||
def test_unauthorized_after_tcpip_returns_clear_message(self):
|
||||
with patch.object(wifi_adb, "list_adb_devices", return_value=["MB75DEFQZHZTGMLJ"]), \
|
||||
patch.object(wifi_adb, "get_device_ip", return_value=(True, "192.168.5.2")), \
|
||||
patch.object(wifi_adb, "enable_wifi_adb", return_value=(True, "ok")), \
|
||||
patch.object(
|
||||
wifi_adb,
|
||||
"connect_wifi_adb",
|
||||
return_value=(False, "未授权: 192.168.5.2:5555 尚未授权"),
|
||||
), \
|
||||
patch.object(wifi_adb.time, "sleep", return_value=None):
|
||||
ok, msg = wifi_adb.auto_connect_wifi_adb("/adb", "MB75DEFQZHZTGMLJ")
|
||||
assert ok is False
|
||||
assert "尚未授权" in msg
|
||||
Reference in new issue
Block a user