refactor(fudai): 拆出 task_count_zero 错误分支(3502→3334,-168 行)

把 _handle_in_fudai_detail 中 'last_status==error 且 reason==task_count_zero'
的 165 行处理逻辑抽到 fudai_detail_blocks.handle_task_count_zero_error:
- 累加 _fudai_detail_consecutive_failures 计数
- 第 3 次连续失败:关闭详情 + 强制切换直播间(含 ADB swipe 兜底)+ 重置计数
- 单次失败:清除任务数量标志后跳过本次

新增 6 个单元测试覆盖:第 1/3 次失败 / needswitch 开关 / status 不匹配 /
extra 不是 dict 等边界。1082 → 1088 用例全过。

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 02:26:18 +08:00
1 parent 17f1977a65
commit c5f2bbee9c
3 files changed
+212 -170

No files matched your search

+2 -170
View File
@@ -2892,176 +2892,8 @@ class fudai_analyse:
# 检查是否是优惠券弹窗、观看任务或识别错误:如果检测到,应该直接跳过,不继续处理
if fudai_detail_blocks.handle_status_based_early_return(self, start_time):
return
try:
last_status = getattr(self, "_last_fudai_detail_status", "")
if last_status == "error":
# 检查是否是任务数量为0的错误
try:
last_extra = getattr(self, "_last_fudai_detail_extra", {})
if (
isinstance(last_extra, dict)
and last_extra.get("reason") == "task_count_zero"
):
# 记录连续失败次数
consecutive_failures = (
getattr(self, "_fudai_detail_consecutive_failures", 0) or 0
)
consecutive_failures += 1
try:
self._fudai_detail_consecutive_failures = (
consecutive_failures
)
except Exception:
pass
# 如果连续失败3次,强制关闭详情页并切换直播间,避免卡死
if consecutive_failures >= 3:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:连续3次识别到任务数量为0,强制关闭详情页并切换直播间,避免卡死",
consecutive_failures=consecutive_failures,
)
except Exception:
pass
# 强制关闭详情页
try:
douyin_fudai_detail.close_fudai_detail(self)
self.operation.delay(0.5)
except Exception:
pass
# 切换直播间
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
try:
if hasattr(self, "swipe_up_to_next_live"):
self.swipe_up_to_next_live()
else:
rx = int(
getattr(self, "resolution_ratio_x", 1080)
or 1080
)
ry = int(
getattr(self, "resolution_ratio_y", 2400)
or 2400
)
start_x = 540 * rx // 1080
start_y = 1200 * ry // 2400
end_x = 540 * rx // 1080
end_y = 600 * ry // 2400
# 直接使用 ADB 内部滑动命令
try:
if hasattr(self.operation, "_adb_path"):
adb_cmd = self.operation._adb_path()
else:
adb_cmd = (
os.environ.get(
"ADB_EXECUTABLE", "adb"
)
or "adb"
)
if adb_cmd.startswith(
'"'
) and adb_cmd.endswith('"'):
adb_cmd = adb_cmd[1:-1]
cmd = [
adb_cmd,
"-s",
str(self.device_id),
"shell",
"input",
"swipe",
str(int(start_x)),
str(int(start_y)),
str(int(end_x)),
str(int(end_y)),
"300",
]
subprocess.run(
cmd,
timeout=5.0,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
except Exception:
# 回退到 operation.swipe
self.operation.swipe(
self.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
self.operation.delay(0.5)
except Exception:
pass
# 重置失败计数
try:
self._fudai_detail_consecutive_failures = 0
except Exception:
pass
# 清除任务数量标志
try:
self._fudai_detail_task_count_from_stage = None
try:
self._log_kv(
"福袋详情",
"_handle_in_fudai_detail:清除任务数量标志",
log_type="DEBUG",
)
except Exception:
pass
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(连续失败)",
elapsed_seconds=round(elapsed, 2),
)
return
else:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:检测到任务数量为0,跳过后续处理",
consecutive_failures=consecutive_failures,
)
except Exception:
pass
# 清除任务数量标志
try:
self._fudai_detail_task_count_from_stage = None
try:
self._log_kv(
"福袋详情",
"_handle_in_fudai_detail:清除任务数量标志",
log_type="DEBUG",
)
except Exception:
pass
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(任务数量为0)",
elapsed_seconds=round(elapsed, 2),
)
return
except Exception:
pass
except Exception:
pass
if fudai_detail_blocks.handle_task_count_zero_error(self, start_time):
return
# 如果成功读取,重置失败计数
try:
@@ -246,3 +246,146 @@ def handle_status_based_early_return(
return False
def _force_swipe_to_next_live_with_adb_fallback(analyser: Any) -> None:
"""task_count_zero 连续失败 3 次后强制切换直播间。
优先使用 analyser.swipe_up_to_next_live;若不可用则回退到直接 ADB 滑动命令。
"""
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if not needswitch:
return
try:
if hasattr(analyser, "swipe_up_to_next_live"):
analyser.swipe_up_to_next_live()
try:
analyser.operation.delay(0.5)
except Exception:
pass
return
import os
import subprocess
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
start_x = 540 * rx // 1080
start_y = 1200 * ry // 2400
end_x = 540 * rx // 1080
end_y = 600 * ry // 2400
try:
if hasattr(analyser.operation, "_adb_path"):
adb_cmd = analyser.operation._adb_path()
else:
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
if adb_cmd.startswith('"') and adb_cmd.endswith('"'):
adb_cmd = adb_cmd[1:-1]
cmd = [
adb_cmd,
"-s",
str(analyser.device_id),
"shell",
"input",
"swipe",
str(int(start_x)),
str(int(start_y)),
str(int(end_x)),
str(int(end_y)),
"300",
]
subprocess.run(
cmd,
timeout=5.0,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
except Exception:
try:
analyser.operation.swipe(
analyser.device_id, start_x, start_y, end_x, end_y, 300
)
except Exception:
pass
try:
analyser.operation.delay(0.5)
except Exception:
pass
except Exception:
pass
def handle_task_count_zero_error(analyser: Any, start_time: float) -> bool:
"""last_status == "error" 且 reason == "task_count_zero" 的处理。
返回 True 表示已处理(连续失败 3 次切换直播间,或单次失败跳过),
主流程应 return。返回 False 表示不属于该分支。
"""
try:
last_status = getattr(analyser, "_last_fudai_detail_status", "")
except Exception:
return False
if last_status != "error":
return False
try:
last_extra = getattr(analyser, "_last_fudai_detail_extra", {})
except Exception:
return False
if not isinstance(last_extra, dict) or last_extra.get("reason") != "task_count_zero":
return False
consecutive_failures = (
getattr(analyser, "_fudai_detail_consecutive_failures", 0) or 0
) + 1
try:
analyser._fudai_detail_consecutive_failures = consecutive_failures
except Exception:
pass
if consecutive_failures >= 3:
try:
analyser._log_kv(
"流程",
"_handle_in_fudai_detail:连续3次识别到任务数量为0,强制关闭详情页并切换直播间,避免卡死",
consecutive_failures=consecutive_failures,
)
except Exception:
pass
try:
from douyin.fudai import douyin_fudai_detail
douyin_fudai_detail.close_fudai_detail(analyser)
try:
analyser.operation.delay(0.5)
except Exception:
pass
except Exception:
pass
_force_swipe_to_next_live_with_adb_fallback(analyser)
try:
analyser._fudai_detail_consecutive_failures = 0
except Exception:
pass
cleanup_and_log_completion(analyser, start_time, "连续失败")
return True
cleanup_and_log_completion(
analyser,
start_time,
"任务数量为0",
pre_log_msg="_handle_in_fudai_detail:检测到任务数量为0,跳过后续处理",
pre_log_fields={"consecutive_failures": consecutive_failures},
)
return True
+67
View File
@@ -187,3 +187,70 @@ def test_status_error_returns_false_for_external_handling():
def test_status_attribute_missing_returns_false():
a = MagicMock(spec=[])
assert fudai_detail_blocks.handle_status_based_early_return(a, _time.time()) is False
# ---- handle_task_count_zero_error ---- #
def test_task_count_zero_first_failure_skips():
"""第一次 task_count_zero:增加计数器、跳过本次,主流程 return"""
a = MagicMock()
a._last_fudai_detail_status = "error"
a._last_fudai_detail_extra = {"reason": "task_count_zero"}
a._fudai_detail_consecutive_failures = 0
result = fudai_detail_blocks.handle_task_count_zero_error(a, _time.time())
assert result is True
assert a._fudai_detail_consecutive_failures == 1
def test_task_count_zero_third_failure_force_switches():
"""第3次连续失败:强制关闭详情 + 切换直播间 + 重置计数器"""
a = MagicMock()
a._last_fudai_detail_status = "error"
a._last_fudai_detail_extra = {"reason": "task_count_zero"}
a._fudai_detail_consecutive_failures = 2 # 第3次会触发
a.needswitch = True
with patch("douyin.fudai.douyin_fudai_detail.close_fudai_detail") as cd:
result = fudai_detail_blocks.handle_task_count_zero_error(a, _time.time())
assert result is True
cd.assert_called_once_with(a)
a.swipe_up_to_next_live.assert_called_once()
assert a._fudai_detail_consecutive_failures == 0 # 重置
def test_task_count_zero_no_switch_when_disabled():
"""needswitch=False 时不切换"""
a = MagicMock()
a._last_fudai_detail_status = "error"
a._last_fudai_detail_extra = {"reason": "task_count_zero"}
a._fudai_detail_consecutive_failures = 2
a.needswitch = False
with patch("douyin.fudai.douyin_fudai_detail.close_fudai_detail"):
result = fudai_detail_blocks.handle_task_count_zero_error(a, _time.time())
assert result is True
a.swipe_up_to_next_live.assert_not_called()
def test_task_count_zero_status_not_error_returns_false():
"""status != error 时返回 False"""
a = MagicMock()
a._last_fudai_detail_status = "ok"
a._last_fudai_detail_extra = {"reason": "task_count_zero"}
assert fudai_detail_blocks.handle_task_count_zero_error(a, _time.time()) is False
def test_task_count_zero_wrong_reason_returns_false():
"""status=error 但 reason 不是 task_count_zero 返回 False(留给主流程其他分支处理)"""
a = MagicMock()
a._last_fudai_detail_status = "error"
a._last_fudai_detail_extra = {"reason": "other_error"}
assert fudai_detail_blocks.handle_task_count_zero_error(a, _time.time()) is False
def test_task_count_zero_extra_not_dict_returns_false():
a = MagicMock()
a._last_fudai_detail_status = "error"
a._last_fudai_detail_extra = None
assert fudai_detail_blocks.handle_task_count_zero_error(a, _time.time()) is False