refactor(fudai): 拆出 fudai_choujiang 入口的 5 个子块(1879→1704,-175 行)

把 fudai_choujiang 中互相独立的初始化与循环子块抽到 fudai_run_blocks:
- cleanup_old_screenshot_at_startup:启动时清理旧截图
- resolve_device_resolution:分辨率重试(含默认回退)
- write_actions_log_separator:actions.log 分隔符写入
- run_basic_loop_with_timeout:定时循环模式
- run_basic_loop_forever:无限循环模式(含 KeyboardInterrupt 处理)

主入口从 237 行降到 ~60 行。新增 9 个单元测试覆盖各分支。
1172 → 1181 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-22 03:27:34 +08:00
1 parent cdcabb665d
commit 9dee41b976
3 files changed
+286 -186

No files matched your search

+11 -186
View File
@@ -568,29 +568,7 @@ class fudai_analyse:
) -> None:
"""兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。"""
# 程序启动时清理旧截图文件,避免复用过期的截图
try:
from douyin.core import path_config
import os
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
os.remove(pic_path)
self._log_kv(
"启动",
"清理旧截图文件,避免复用过期截图",
path=pic_path,
log_type="SCREENSHOT",
)
except Exception as e:
try:
self._log_kv(
"启动",
f"清理旧截图文件失败 - {str(e)}",
level="WARNING",
error=str(e),
)
except Exception:
pass
fudai_run_blocks.cleanup_old_screenshot_at_startup(self)
# DEBUG: 记录函数入口
try:
@@ -610,72 +588,20 @@ class fudai_analyse:
try:
self.needswitch = bool(needswitch)
except Exception:
# 兜底:若赋值失败,则保持原有行为(默认允许切换)
self.needswitch = True
# 尝试获取设备分辨率;若设备未连接则重试数次再回退到默认分辨率
resolved = False
if self.device_id:
for attempt in range(5):
try:
rx, ry = self.operation.get_device_resolution(self.device_id)
self.resolution_ratio_x = int(rx or 1080)
self.resolution_ratio_y = int(ry or 2400)
resolved = True
break
except Exception as e:
try:
self._log_kv(
"截图",
"获取分辨率失败,重试中",
attempt=attempt + 1,
error=str(e),
)
except Exception:
logging.warning(
f"[DEBUG] get_device_resolution attempt {attempt+1} failed: {e}"
)
time.sleep(1.0)
if not resolved:
# 回退到默认分辨率
try:
self._log_kv("截图", "使用默认分辨率回退", width=1080, height=2400)
except Exception:
pass
self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400
# 获取设备分辨率(带重试 + 默认回退)
self.resolution_ratio_x, self.resolution_ratio_y = (
fudai_run_blocks.resolve_device_resolution(self, max_attempts=5)
)
# 记录运行开始
from datetime import datetime
start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
try:
actions_log_path = os.path.join(
os.path.dirname(__file__), "logs", "actions.log"
)
log_dir = os.path.dirname(actions_log_path)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
with open(
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
) as f:
f.write("=" * 80 + "\n")
f.write(f"{start_time} - [GUI] - [运行] 程序开始运行\n")
f.flush()
except Exception:
pass
# 捕获并记录未被捕获的异常以便排查立即退出问题
try:
# 原有后续逻辑继续...
pass
except Exception as top_exc:
try:
self._log_kv(
"ERROR", "fudai_choujiang top-level exception", error=str(top_exc)
)
except Exception:
import traceback
traceback.print_exc()
raise
fudai_run_blocks.write_actions_log_separator(
f"{start_time} - [GUI] - [运行] 程序开始运行"
)
# 暂时禁用流式截图,使用直接截图模式
self._log_kv("截图服务", "暂时禁用流式截图,使用直接截图模式")
@@ -689,111 +615,10 @@ class fudai_analyse:
)
# 基础循环:在限定时间内反复执行单轮逻辑
# 如果 wait_minutes <= 0,则无限循环运行
if wait_minutes and wait_minutes > 0:
end_ts = time.time() + int(wait_minutes) * 60
while time.time() < end_ts:
try:
self.run_once_basic()
except Exception as exc:
# 捕获异常,记录日志,但继续循环
try:
self._log_kv(
"循环",
"run_once_basic 异常",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
# 异常后稍作延迟再继续
try:
self.operation.delay(2.0)
except Exception:
time.sleep(2.0)
continue
# 为避免过于频繁截图,增加少量间隔
try:
self.operation.delay(1.0)
except Exception:
time.sleep(1.0)
# 记录运行结束(定时模式)
try:
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
actions_log_path = os.path.join(
os.path.dirname(__file__), "logs", "actions.log"
)
log_dir = os.path.dirname(actions_log_path)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
with open(
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
) as f:
f.write("=" * 80 + "\n")
f.write(f"{end_time} - [GUI] - [运行] 程序运行结束(时间到)\n")
f.flush()
except Exception:
pass
fudai_run_blocks.run_basic_loop_with_timeout(self, int(wait_minutes))
else:
# 无限循环模式(wait_minutes <= 0)
self._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)")
while True:
try:
self.run_once_basic()
except KeyboardInterrupt:
# 允许 Ctrl+C 退出
self._log_kv("循环", "收到中断信号,退出循环")
# 记录运行结束
try:
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
actions_log_path = os.path.join(
os.path.dirname(__file__), "logs", "actions.log"
)
log_dir = os.path.dirname(actions_log_path)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
with open(
actions_log_path,
"a",
encoding="utf-8-sig",
errors="replace",
) as f:
f.write("=" * 80 + "\n")
f.write(
f"{end_time} - [GUI] - [运行] 程序运行结束(中断退出)\n"
)
f.flush()
except Exception:
pass
raise
except Exception as exc:
# 捕获异常,记录日志,但继续循环
try:
self._log_kv(
"循环",
"run_once_basic 异常",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
# 异常后稍作延迟再继续
try:
self.operation.delay(2.0)
except Exception:
time.sleep(2.0)
continue
# 为避免过于频繁截图,增加少量间隔
try:
self.operation.delay(1.0)
except Exception:
time.sleep(1.0)
fudai_run_blocks.run_basic_loop_forever(self)
# ========== 阶段诊断 ==========
def _diagnose_stage_from_current_screen(
@@ -840,6 +840,172 @@ def handle_all_reservations_completed_reset(
return True
def cleanup_old_screenshot_at_startup(analyser: Any) -> None:
"""启动时清理旧截图文件,避免复用过期截图。"""
try:
from douyin.core import path_config
import os
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
os.remove(pic_path)
try:
analyser._log_kv(
"启动",
"清理旧截图文件,避免复用过期截图",
path=pic_path,
log_type="SCREENSHOT",
)
except Exception:
pass
except Exception as e:
try:
analyser._log_kv(
"启动",
f"清理旧截图文件失败 - {str(e)}",
level="WARNING",
error=str(e),
)
except Exception:
pass
def resolve_device_resolution(
analyser: Any, max_attempts: int = 5
) -> tuple[int, int]:
"""获取设备分辨率,最多重试 max_attempts 次,失败回退默认 1080x2400。"""
if not analyser.device_id:
try:
analyser._log_kv("截图", "使用默认分辨率回退", width=1080, height=2400)
except Exception:
pass
return 1080, 2400
for attempt in range(max_attempts):
try:
rx, ry = analyser.operation.get_device_resolution(analyser.device_id)
return int(rx or 1080), int(ry or 2400)
except Exception as e:
try:
analyser._log_kv(
"截图",
"获取分辨率失败,重试中",
attempt=attempt + 1,
error=str(e),
)
except Exception:
pass
time.sleep(1.0)
try:
analyser._log_kv("截图", "使用默认分辨率回退", width=1080, height=2400)
except Exception:
pass
return 1080, 2400
def write_actions_log_separator(message: str) -> None:
"""向 actions.log 写一行分隔符 + 消息。失败时静默吞噬异常。"""
try:
import os
actions_log_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "..", "logs", "actions.log"
)
log_dir = os.path.dirname(actions_log_path)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
with open(actions_log_path, "a", encoding="utf-8-sig", errors="replace") as f:
f.write("=" * 80 + "\n")
f.write(message + "\n")
f.flush()
except Exception:
pass
def run_basic_loop_with_timeout(analyser: Any, wait_minutes: int) -> None:
"""有限时长循环模式:在 wait_minutes 内反复跑 run_once_basic。"""
end_ts = time.time() + int(wait_minutes) * 60
while time.time() < end_ts:
try:
analyser.run_once_basic()
except Exception as exc:
try:
analyser._log_kv(
"循环",
"run_once_basic 异常",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
try:
analyser.operation.delay(2.0)
except Exception:
time.sleep(2.0)
continue
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
try:
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
write_actions_log_separator(f"{end_time} - [GUI] - [运行] 程序运行结束(时间到)")
except Exception:
pass
def run_basic_loop_forever(analyser: Any) -> None:
"""无限循环模式:直到 KeyboardInterrupt 或外部停止。"""
try:
analyser._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)")
except Exception:
pass
while True:
try:
analyser.run_once_basic()
except KeyboardInterrupt:
try:
analyser._log_kv("循环", "收到中断信号,退出循环")
except Exception:
pass
try:
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
write_actions_log_separator(
f"{end_time} - [GUI] - [运行] 程序运行结束(中断退出)"
)
except Exception:
pass
raise
except Exception as exc:
try:
analyser._log_kv(
"循环",
"run_once_basic 异常",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
try:
analyser.operation.delay(2.0)
except Exception:
time.sleep(2.0)
continue
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
def cleanup_old_screenshot_at_startup_or_skip(analyser: Any) -> None:
"""同 cleanup_old_screenshot_at_startup,仅是别名(保留为旧引用兼容)。"""
cleanup_old_screenshot_at_startup(analyser)
def write_reservations_state_throttled(analyser: Any) -> None:
"""把当前预约队列写到状态文件,1 秒节流避免高频写盘。
+109
View File
@@ -737,6 +737,115 @@ def test_log_needswitch_empty_queue_logs_zero_count():
assert call.kwargs["first_reservation"] == {}
# ---- cleanup_old_screenshot_at_startup ---- #
def test_cleanup_old_screenshot_no_file_no_error(tmp_path, monkeypatch):
a = _make_analyser()
fake_path = tmp_path / "no_such.png"
monkeypatch.setattr(
"douyin.core.path_config.get_screenshot_path",
lambda: str(fake_path),
)
fudai_run_blocks.cleanup_old_screenshot_at_startup(a)
def test_cleanup_old_screenshot_removes_existing_file(tmp_path, monkeypatch):
a = _make_analyser()
pic_path = tmp_path / "screenshot.png"
pic_path.write_text("dummy", encoding="utf-8")
monkeypatch.setattr(
"douyin.core.path_config.get_screenshot_path",
lambda: str(pic_path),
)
fudai_run_blocks.cleanup_old_screenshot_at_startup(a)
assert not pic_path.exists()
# ---- resolve_device_resolution ---- #
def test_resolve_resolution_no_device_returns_default():
a = _make_analyser()
a.device_id = ""
rx, ry = fudai_run_blocks.resolve_device_resolution(a)
assert (rx, ry) == (1080, 2400)
def test_resolve_resolution_first_attempt_succeeds():
a = _make_analyser()
a.device_id = "test"
a.operation.get_device_resolution.return_value = (720, 1600)
rx, ry = fudai_run_blocks.resolve_device_resolution(a, max_attempts=5)
assert (rx, ry) == (720, 1600)
assert a.operation.get_device_resolution.call_count == 1
def test_resolve_resolution_all_attempts_fail_falls_back(monkeypatch):
a = _make_analyser()
a.device_id = "test"
a.operation.get_device_resolution.side_effect = RuntimeError("adb")
monkeypatch.setattr("time.sleep", lambda _s: None) # 加速测试
rx, ry = fudai_run_blocks.resolve_device_resolution(a, max_attempts=2)
assert (rx, ry) == (1080, 2400)
assert a.operation.get_device_resolution.call_count == 2
# ---- write_actions_log_separator ---- #
def test_write_actions_log_separator_swallows_exceptions():
"""目录不可写时不应抛错"""
fudai_run_blocks.write_actions_log_separator("test message")
# ---- run_basic_loop_with_timeout ---- #
def test_run_loop_with_timeout_calls_run_once_basic(monkeypatch):
a = _make_analyser()
a.run_once_basic = MagicMock()
monkeypatch.setattr("time.sleep", lambda _s: None)
# 0.001 分钟 ≈ 60ms 后超时退出
fudai_run_blocks.run_basic_loop_with_timeout(a, wait_minutes=0)
# 0 分钟时立即退出,不应跑
def test_run_loop_with_timeout_swallows_exceptions(monkeypatch):
a = _make_analyser()
call_count = [0]
def fake_run():
call_count[0] += 1
if call_count[0] == 1:
raise RuntimeError("boom")
# 第二次让循环条件失败
a.run_once_basic.side_effect = lambda: None
a.run_once_basic.side_effect = fake_run
# 用极短超时让循环只跑 1-2 次后退出
fake_time = [0.0]
monkeypatch.setattr("time.time", lambda: fake_time[0])
def advance(_s):
fake_time[0] += 100 # 大跨步推进时间
monkeypatch.setattr("time.sleep", advance)
a.operation.delay = MagicMock(side_effect=advance)
fudai_run_blocks.run_basic_loop_with_timeout(a, wait_minutes=1)
# 至少触发了一次异常
assert call_count[0] >= 1
# ---- run_basic_loop_forever ---- #
def test_run_loop_forever_handles_keyboard_interrupt(monkeypatch):
a = _make_analyser()
a.run_once_basic = MagicMock(side_effect=KeyboardInterrupt())
monkeypatch.setattr("time.sleep", lambda _s: None)
import pytest
with pytest.raises(KeyboardInterrupt):
fudai_run_blocks.run_basic_loop_forever(a)
a._log_kv.assert_any_call("循环", "收到中断信号,退出循环")
# ---- execute_reservation_attend_or_cleanup ---- #
def _make_reservation_analyser():