"""单元测试:douyin/core/fudai_modules/fudai_run_blocks.py 覆盖从 run_once_basic 提取出的 4 个独立子块的核心分支: - 等待开奖结果(超时、未触发、检测到结果) - 30 分钟未参与超时 - 桌面误返回自救 - 高价值房间重访 """ from __future__ import annotations import time from unittest.mock import MagicMock, patch import pytest from douyin.core.fudai_modules import fudai_run_blocks # ---- 基础桩 ---- # def _make_analyser(**overrides): a = MagicMock() a._log_kv = MagicMock() a._waiting_for_lottery_result = False a._lottery_result_expected_ts = 0.0 a._current_attending_reservation_fudai = False a._lottery_wait_start_ts = 0.0 a.needswitch = True a.swipe_up_to_next_live = MagicMock() a._handle_lottery_result_by_ocr = MagicMock() a._check_lottery_result_by_ocr = MagicMock(return_value=None) a.operation = MagicMock() a.operation.get_screenshot = MagicMock() a.operation.delay = MagicMock() a.operation.get_top_package = MagicMock(return_value="com.ss.android.ugc.aweme") a._last_successful_attend_ts = 0.0 a._no_attend_timeout_minutes = 30.0 a._run_start_ts = time.time() a._return_to_recommend_and_reenter_live = MagicMock() a.high_value_room_revisit_enabled = False a.run_once_basic = MagicMock() a.click = MagicMock() a.desktop_icon_x = 153 a.desktop_icon_y = 260 a.yanghao_fallback_live_x = 100 a.yanghao_fallback_live_y = 200 a.yanghao_fallback_enter_live_x = 300 a.yanghao_fallback_enter_live_y = 400 a.device_id = "test" for k, v in overrides.items(): setattr(a, k, v) return a # ---- handle_waiting_for_lottery_result ---- # def test_lottery_not_waiting_returns_false(): a = _make_analyser(_waiting_for_lottery_result=False) assert fudai_run_blocks.handle_waiting_for_lottery_result(a, time.time()) is False def test_lottery_already_timed_out_clears_flag_and_continues(): """超时太久(已经超过 future_ts + 10s):清标志后返回 False(继续主流程)""" past_ts = time.time() - 100 a = _make_analyser( _waiting_for_lottery_result=True, _lottery_result_expected_ts=past_ts, ) result = fudai_run_blocks.handle_waiting_for_lottery_result(a, time.time()) assert result is False assert a._waiting_for_lottery_result is False assert a._current_attending_reservation_fudai is False def test_lottery_detected_during_wait_handles_and_returns_true(): future_ts = time.time() + 5 a = _make_analyser( _waiting_for_lottery_result=True, _lottery_result_expected_ts=future_ts, _lottery_wait_start_ts=time.time(), ) a._check_lottery_result_by_ocr.return_value = "won" result = fudai_run_blocks.handle_waiting_for_lottery_result(a, time.time()) assert result is True a._handle_lottery_result_by_ocr.assert_called_once_with("won") assert a._waiting_for_lottery_result is False # ---- handle_no_attend_timeout ---- # def test_no_attend_timeout_with_recent_attend_returns_false(): a = _make_analyser(_last_successful_attend_ts=time.time() - 60) # 1 分钟前 assert fudai_run_blocks.handle_no_attend_timeout(a, time.time()) is False def test_no_attend_timeout_exceeded_with_last_attend_returns_true(): a = _make_analyser( _last_successful_attend_ts=time.time() - 31 * 60, # 31 分钟前 _no_attend_timeout_minutes=30.0, ) assert fudai_run_blocks.handle_no_attend_timeout(a, time.time()) is True a._return_to_recommend_and_reenter_live.assert_called_once() def test_no_attend_timeout_exceeded_without_attend_returns_true(): a = _make_analyser( _last_successful_attend_ts=0.0, _run_start_ts=time.time() - 31 * 60, _no_attend_timeout_minutes=30.0, ) assert fudai_run_blocks.handle_no_attend_timeout(a, time.time()) is True a._return_to_recommend_and_reenter_live.assert_called_once() def test_no_attend_timeout_within_run_returns_false(): a = _make_analyser( _last_successful_attend_ts=0.0, _run_start_ts=time.time() - 5 * 60, # 5 分钟前启动 _no_attend_timeout_minutes=30.0, ) assert fudai_run_blocks.handle_no_attend_timeout(a, time.time()) is False # ---- handle_desktop_recovery ---- # def test_desktop_recovery_in_douyin_returns_false(): a = _make_analyser() a.operation.get_top_package.return_value = "com.ss.android.ugc.aweme" assert fudai_run_blocks.handle_desktop_recovery(a) is False # 不在桌面,不应该触发 click a.click.assert_not_called() def test_desktop_recovery_on_desktop_triggers_recovery(): a = _make_analyser() a.operation.get_top_package.return_value = "com.android.launcher3" assert fudai_run_blocks.handle_desktop_recovery(a) is True # 触发自救后,应该 click 桌面图标 + 直播按钮 + 进入直播间(多次) assert a.click.call_count >= 2 # 应该递归调用一次 run_once_basic a.run_once_basic.assert_called_once() def test_desktop_recovery_empty_top_pkg_returns_false(): a = _make_analyser() a.operation.get_top_package.return_value = "" assert fudai_run_blocks.handle_desktop_recovery(a) is False def test_desktop_recovery_top_pkg_exception_returns_false(): a = _make_analyser() a.operation.get_top_package.side_effect = Exception("adb fail") assert fudai_run_blocks.handle_desktop_recovery(a) is False # ---- handle_high_value_room_revisit ---- # def test_revisit_disabled_returns_false(): a = _make_analyser(high_value_room_revisit_enabled=False) assert fudai_run_blocks.handle_high_value_room_revisit(a, time.time()) is False def test_revisit_enabled_but_module_import_error_returns_false(): """import 失败的话异常被吞,返回 False(继续主流程)""" a = _make_analyser(high_value_room_revisit_enabled=True) # 这里实际会 import douyin.other.douyin_high_value_room,模块存在则可能往下走 # 我们只需保证不崩 result = fudai_run_blocks.handle_high_value_room_revisit(a, time.time()) assert isinstance(result, bool) # ---- handle_fansclub_join_stage ---- # def _make_fansclub_analyser(): a = _make_analyser() a.resolution_ratio_x = 1080 a.resolution_ratio_y = 2400 a.auto_join_fansclub = False a.fansclub_fail_action = "stay" a._diagnose_stage_from_current_screen = MagicMock(return_value=("OK", "")) return a def test_fansclub_join_happy_path_clicks_three_positions(): """正常路径:3 次点击(参与按钮 + 2 次预设位置 + 关闭详情)= 共 4 次 click""" a = _make_fansclub_analyser() fudai_run_blocks.handle_fansclub_join_stage(a, time.time()) # click 调用次数:参与按钮 + 第一次预设 + 第二次预设 + 关闭详情 = 4 assert a.operation.click.call_count == 4 def test_fansclub_join_failure_with_auto_join_retries(): """主路径出错且 auto_join=True → 重新诊断后重试两次点击""" a = _make_fansclub_analyser() a.auto_join_fansclub = True # 让第一次 click 抛错触发 except 分支 a.operation.click.side_effect = [ RuntimeError("first click fail"), # 第一次 click 就失败 ] + [None] * 20 # 后续 click 正常 a._diagnose_stage_from_current_screen.return_value = ("FANSCLUB_JOIN", "") fudai_run_blocks.handle_fansclub_join_stage(a, time.time()) # 仍应完成(不抛错) a._log_kv.assert_any_call("粉丝团处理", "处理粉丝团加入失败", error="first click fail") def test_fansclub_join_failure_without_auto_join_waits(): """主路径出错且 auto_join=False → 等待 15 秒""" a = _make_fansclub_analyser() a.auto_join_fansclub = False a.operation.click.side_effect = [RuntimeError("boom")] + [None] * 20 fudai_run_blocks.handle_fansclub_join_stage(a, time.time()) # 应当调用 delay(15.0) delay_calls = [c.args[0] for c in a.operation.delay.call_args_list] assert 15.0 in delay_calls def test_fansclub_join_failure_with_switch_action_swipes(): """主路径出错且 fansclub_fail_action=switch → 切换直播间""" a = _make_fansclub_analyser() a.fansclub_fail_action = "switch" a.auto_join_fansclub = False a.operation.click.side_effect = [RuntimeError("boom")] + [None] * 20 fudai_run_blocks.handle_fansclub_join_stage(a, time.time()) a.swipe_up_to_next_live.assert_called_once() def test_fansclub_join_logs_completion(): a = _make_fansclub_analyser() fudai_run_blocks.handle_fansclub_join_stage(a, time.time()) completion_calls = [ c for c in a._log_kv.call_args_list if c.args == ("流程", "run_once_basic完成(处理粉丝团)") or (len(c.args) >= 2 and c.args[1] == "run_once_basic完成(处理粉丝团)") ] assert len(completion_calls) >= 1 # ---- handle_coupon_popup_stage ---- # def test_coupon_popup_clicks_back_and_logs_completion(): a = _make_analyser() fudai_run_blocks.handle_coupon_popup_stage(a, time.time()) a.operation.click_back.assert_called_once_with("test") completion_msgs = [ c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2 and "run_once_basic完成(处理优惠券弹窗)" in c.args[1] ] assert len(completion_msgs) == 1 def test_coupon_popup_swallows_click_back_failure(): a = _make_analyser() a.operation.click_back.side_effect = RuntimeError("boom") fudai_run_blocks.handle_coupon_popup_stage(a, time.time()) # 应当记录失败日志且仍记录完成 failure_calls = [ c for c in a._log_kv.call_args_list if len(c.args) >= 2 and "按返回键关闭优惠券弹窗失败" in c.args[1] ] assert len(failure_calls) == 1 # ---- handle_shopping_redpacket_popup_stage ---- # def test_shopping_redpacket_clicks_close_button(): a = _make_analyser() a.resolution_ratio_x = 1080 a.resolution_ratio_y = 2400 fudai_run_blocks.handle_shopping_redpacket_popup_stage(a, time.time()) a.operation.click.assert_called_once_with("test", 530, 1647) def test_shopping_redpacket_swallows_click_failure(): a = _make_analyser() a.resolution_ratio_x = 1080 a.resolution_ratio_y = 2400 a.operation.click.side_effect = RuntimeError("boom") fudai_run_blocks.handle_shopping_redpacket_popup_stage(a, time.time()) # ---- handle_lottery_result_stage ---- # def test_lottery_result_with_ocr_match_calls_handler(): a = _make_analyser() a._check_lottery_result_by_ocr.return_value = "won" fudai_run_blocks.handle_lottery_result_stage(a, time.time()) a._handle_lottery_result_by_ocr.assert_called_once_with("won") assert a._waiting_for_lottery_result is False assert a._current_attending_reservation_fudai is False def test_lottery_result_no_ocr_falls_back_to_back_and_swipe(): a = _make_analyser() a._check_lottery_result_by_ocr.return_value = None fudai_run_blocks.handle_lottery_result_stage(a, time.time()) a.operation.click_back.assert_called_once() a.swipe_up_to_next_live.assert_called_once() a._handle_lottery_result_by_ocr.assert_not_called() # ---- handle_live_closed_stage ---- # def test_live_closed_swipes_to_next_and_logs_completion(): a = _make_analyser() fudai_run_blocks.handle_live_closed_stage(a, time.time()) a.swipe_up_to_next_live.assert_called_once() completion = [ c for c in a._log_kv.call_args_list if len(c.args) >= 2 and "run_once_basic完成(直播结束)" in c.args[1] ] assert len(completion) == 1 # ---- handle_recommend_page_stage ---- # def _make_recommend_analyser(): a = _make_analyser() a.resolution_ratio_x = 1080 a.resolution_ratio_y = 2400 a.FOLLOW_TAB_CLICK_DELAY = 0.5 a.ENTER_LIVE_CLICK_DELAY = 0.6 a.ENTER_LIVE_FINAL_DELAY = 1.0 a.RETURN_STEP_DELAY_SECONDS = 0.8 return a def test_recommend_page_clicks_live_tab_and_enter_live_twice(): a = _make_recommend_analyser() fudai_run_blocks.handle_recommend_page_stage(a, "RECOMMEND_PAGE", "") # 点击次数:直播页 1 + 直播间 2 = 3 assert a.operation.click.call_count == 3 def test_recommend_page_handles_click_failure(): a = _make_recommend_analyser() a.operation.click.side_effect = RuntimeError("boom") fudai_run_blocks.handle_recommend_page_stage(a, "RECOMMEND_PAGE", "") # 异常时 fallback 调用 click_back a.operation.click_back.assert_called_once() # ---- handle_in_live_room_stage ---- # def test_in_live_room_no_just_switched_calls_handler(): a = _make_analyser() a._just_switched_room = False a._handle_live_room_has_or_not_fudai = MagicMock() fudai_run_blocks.handle_in_live_room_stage(a, "IN_LIVE_ROOM", time.time()) a._handle_live_room_has_or_not_fudai.assert_called_once() # 不应该调用 delay(没切换不需要等加载) a.operation.delay.assert_not_called() def test_in_live_room_just_switched_waits_for_load(): a = _make_analyser() a._just_switched_room = True a.switch_room_wait_after_stage_diag_seconds = 5.0 a._handle_live_room_has_or_not_fudai = MagicMock() fudai_run_blocks.handle_in_live_room_stage(a, "IN_LIVE_ROOM", time.time()) # 应当 delay(5.0) delays = [c.args[0] for c in a.operation.delay.call_args_list] assert 5.0 in delays # 标志已清除 assert a._just_switched_room is False a._handle_live_room_has_or_not_fudai.assert_called_once() def test_in_live_room_logs_completion(): a = _make_analyser() a._just_switched_room = False a._handle_live_room_has_or_not_fudai = MagicMock() fudai_run_blocks.handle_in_live_room_stage(a, "LIVE_OR_UNKNOWN", time.time()) completion = [ c for c in a._log_kv.call_args_list if len(c.args) >= 2 and "run_once_basic完成(处理直播间)" in c.args[1] ] assert len(completion) == 1 # ---- take_screenshot_with_retries ---- # def test_screenshot_success_first_try(): a = _make_analyser() a.operation.get_screenshot.return_value = True ok, elapsed = fudai_run_blocks.take_screenshot_with_retries(a, time.time()) assert ok is True assert elapsed >= 0 def test_screenshot_success_second_try(): a = _make_analyser() a.operation.get_screenshot.side_effect = [False, True] ok, _ = fudai_run_blocks.take_screenshot_with_retries(a, time.time(), max_retries=3) assert ok is True # 重试一次,所以 delay 被调用一次 assert a.operation.delay.call_count == 1 def test_screenshot_all_retries_fail_logs_error(): a = _make_analyser() a.operation.get_screenshot.return_value = False ok, _ = fudai_run_blocks.take_screenshot_with_retries(a, time.time(), max_retries=3) assert ok is False # 应记录"获取截图失败(多次重试后仍失败)" failure_logs = [ c for c in a._log_kv.call_args_list if len(c.args) >= 2 and "获取截图失败" in c.args[1] ] assert len(failure_logs) == 1 def test_screenshot_get_screenshot_exception_treated_as_false(): a = _make_analyser() a.operation.get_screenshot.side_effect = RuntimeError("adb fail") ok, _ = fudai_run_blocks.take_screenshot_with_retries(a, time.time(), max_retries=2) assert ok is False # ---- maybe_clear_reservation_queue_on_first_run ---- # def test_clear_queue_first_run_clears_reservations(): a = MagicMock() a._first_run_once_basic = True a.reservations = [{"future_ts": 100}, {"future_ts": 200}] a._reservations_state_path = None # 跳过 write 状态文件 fudai_run_blocks.maybe_clear_reservation_queue_on_first_run(a) assert a.reservations == [] assert a._first_run_once_basic is False def test_clear_queue_non_first_run_keeps_reservations(): a = MagicMock() a._first_run_once_basic = False original = [{"future_ts": 100}] a.reservations = original fudai_run_blocks.maybe_clear_reservation_queue_on_first_run(a) # 队列保持 assert a.reservations is original def test_clear_queue_first_run_no_state_path_still_clears(): a = MagicMock() a._first_run_once_basic = True a.reservations = [{"future_ts": 100}] a._reservations_state_path = None fudai_run_blocks.maybe_clear_reservation_queue_on_first_run(a) assert a.reservations == [] def test_clear_queue_swallows_log_exceptions(): a = MagicMock() a._first_run_once_basic = True a.reservations = [{"future_ts": 100}] a._log_kv.side_effect = RuntimeError("boom") a._reservations_state_path = None # 应不抛错 fudai_run_blocks.maybe_clear_reservation_queue_on_first_run(a) assert a.reservations == [] # ---- handle_just_recorded_reservation ---- # def test_just_recorded_not_set_returns_false(): a = _make_analyser() a._just_recorded_reservation = False assert fudai_run_blocks.handle_just_recorded_reservation(a, time.time()) is False def test_just_recorded_with_switch_swipes_up(): a = _make_analyser() a._just_recorded_reservation = True a.needswitch = True assert fudai_run_blocks.handle_just_recorded_reservation(a, time.time()) is True a.swipe_up_to_next_live.assert_called_once() assert a._just_recorded_reservation is False def test_just_recorded_no_switch_skips_swipe(): a = _make_analyser() a._just_recorded_reservation = True a.needswitch = False assert fudai_run_blocks.handle_just_recorded_reservation(a, time.time()) is True a.swipe_up_to_next_live.assert_not_called() def test_just_recorded_swipe_failure_still_returns_true(): a = _make_analyser() a._just_recorded_reservation = True a.needswitch = True a.swipe_up_to_next_live.side_effect = RuntimeError("boom") assert fudai_run_blocks.handle_just_recorded_reservation(a, time.time()) is True # ---- handle_skip_stage_diagnosis ---- # def test_skip_stage_diag_not_set_returns_false(): a = _make_analyser() a._skip_stage_diagnosis_and_find_fudai = False assert fudai_run_blocks.handle_skip_stage_diagnosis(a, time.time()) is False def test_skip_stage_diag_set_calls_handler_and_clears_flag(): a = _make_analyser() a._skip_stage_diagnosis_and_find_fudai = True a._handle_live_room_has_or_not_fudai = MagicMock() assert fudai_run_blocks.handle_skip_stage_diagnosis(a, time.time()) is True a._handle_live_room_has_or_not_fudai.assert_called_once() assert a._skip_stage_diagnosis_and_find_fudai is False def test_skip_stage_diag_handler_failure_still_returns_true(): a = _make_analyser() a._skip_stage_diagnosis_and_find_fudai = True a._handle_live_room_has_or_not_fudai = MagicMock(side_effect=RuntimeError("boom")) assert fudai_run_blocks.handle_skip_stage_diagnosis(a, time.time()) is True # ---- log_reservation_trigger_check ---- # def test_log_trigger_check_disabled_logs_skip(): a = MagicMock() fudai_run_blocks.log_reservation_trigger_check(a, False, None, 0) msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2] assert any("预约功能未启用" in m for m in msgs) def test_log_trigger_check_empty_queue_logs_skip(): a = MagicMock() fudai_run_blocks.log_reservation_trigger_check(a, True, [], 0) msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2] assert any("预约队列为空" in m for m in msgs) def test_log_trigger_check_with_reservations_logs_overview(): a = MagicMock() reservations = [ {"future_ts": 1700000100, "prize_value_yuan": 5.0, "pos_seen": 3}, {"future_ts": 1700000200, "prize_value_yuan": 10.0, "pos_seen": 5}, ] fudai_run_blocks.log_reservation_trigger_check(a, True, reservations, 2) # 触发条件日志应被调用 overview_calls = [ c for c in a._log_kv.call_args_list if len(c.args) >= 2 and "检查预约回退触发条件" in c.args[1] ] assert len(overview_calls) == 1 # 不应记录跳过日志 skip_calls = [ c for c in a._log_kv.call_args_list if len(c.args) >= 2 and ("预约功能未启用" in c.args[1] or "预约队列为空" in c.args[1]) ] assert len(skip_calls) == 0 def test_log_trigger_check_truncates_to_first_three(): """队列超过 3 项时,详情只记录前 3 项""" a = MagicMock() reservations = [ {"future_ts": 1700000000 + i * 100, "prize_value_yuan": float(i), "pos_seen": i} for i in range(5) ] fudai_run_blocks.log_reservation_trigger_check(a, True, reservations, 5) overview_call = next( c for c in a._log_kv.call_args_list if len(c.args) >= 2 and "检查预约回退触发条件" in c.args[1] ) detail = overview_call.kwargs.get("reservations_detail", []) assert len(detail) == 3 # ---- write_reservations_state_throttled ---- # def test_write_state_throttled_skips_within_1s(tmp_path): a = MagicMock() state_path = tmp_path / "state.json" a._reservations_state_path = str(state_path) a._reservations_state_last_write_ts = time.time() - 0.5 # 0.5s 前刚写过 a.reservations = [{"future_ts": 100}] fudai_run_blocks.write_reservations_state_throttled(a) # 节流,文件不应被写 assert not state_path.exists() def test_write_state_writes_when_throttle_passed(tmp_path): a = MagicMock() state_path = tmp_path / "state.json" a._reservations_state_path = str(state_path) a._reservations_state_last_write_ts = time.time() - 5 # 5s 前 a.reservations = [ { "future_ts": 1700000000.0, "prize_value_yuan": 5.0, "content": "test", "pos_seen": 3, "room_title": "房间A", "room_title_raw": "房间A原始", "created_ts": 1699999999, } ] a.current_room_title = "当前" a.current_room_title_raw = "当前原始" a.room_pos = 5 fudai_run_blocks.write_reservations_state_throttled(a) import json as _json assert state_path.exists() data = _json.loads(state_path.read_text(encoding="utf-8")) assert data["reason"] == "process_reservation" assert data["room_pos"] == 5 assert len(data["reservations"]) == 1 assert data["reservations"][0]["prize_value_yuan"] == 5.0 def test_write_state_swallows_io_error(): """state_path 不可写时不应抛错""" a = MagicMock() # Windows: 用一个明确无效的路径(包含非法字符) a._reservations_state_path = "Z:\\nonexistent\\path\\with\x00null\\state.json" a._reservations_state_last_write_ts = 0.0 a.reservations = [] a.current_room_title = "" a.current_room_title_raw = "" a.room_pos = 0 # 不应抛错 fudai_run_blocks.write_reservations_state_throttled(a) # 应记录失败日志 failure = [ c for c in a._log_kv.call_args_list if len(c.args) >= 2 and "写入预约队列状态文件失败" in c.args[1] ] assert len(failure) == 1 # ---- handle_all_reservations_completed_reset ---- # def test_completed_reset_no_queue_full_returns_false(): a = MagicMock() a.queue_full_waiting_at_earliest = False a.reservations = [] swipe = MagicMock() assert fudai_run_blocks.handle_all_reservations_completed_reset(a, swipe) is False swipe.assert_not_called() def test_completed_reset_with_pending_reservations_returns_false(): a = MagicMock() a.queue_full_waiting_at_earliest = True a.reservations = [{"future_ts": 100}] # 有未完成 swipe = MagicMock() assert fudai_run_blocks.handle_all_reservations_completed_reset(a, swipe) is False swipe.assert_not_called() def test_completed_reset_clears_focus_and_swipes_back(): a = MagicMock() a.queue_full_waiting_at_earliest = True a.reservations = [] a.reservation_focus_until_ts = 12345.0 a.room_pos = 5 a._swipe_times = 99 swipe = MagicMock() assert fudai_run_blocks.handle_all_reservations_completed_reset(a, swipe) is True assert a.queue_full_waiting_at_earliest is False assert a.reservation_focus_until_ts == 0.0 assert a.room_pos == 0 assert a._swipe_times == 0 # 应回退 5 次 assert swipe.call_count == 5 def test_completed_reset_caps_back_times_at_100(): """room_pos > 100 时被钳到 100""" a = MagicMock() a.queue_full_waiting_at_earliest = True a.reservations = [] a.room_pos = 500 swipe = MagicMock() fudai_run_blocks.handle_all_reservations_completed_reset(a, swipe) assert swipe.call_count == 100 def test_completed_reset_zero_room_pos_no_swipes(): a = MagicMock() a.queue_full_waiting_at_earliest = True a.reservations = [] a.room_pos = 0 swipe = MagicMock() assert fudai_run_blocks.handle_all_reservations_completed_reset(a, swipe) is True swipe.assert_not_called() # ---- log_needswitch_check_details ---- # def test_log_needswitch_with_reservation_logs_first_detail(): a = MagicMock() a.reservations = [ { "future_ts": time.time() + 100, "prize_value_yuan": 5.0, "pos_seen": 3, } ] a.room_pos = 7 fudai_run_blocks.log_needswitch_check_details(a, True) call = next( c for c in a._log_kv.call_args_list if len(c.args) >= 2 and "检查预约回退条件" in c.args[1] ) assert call.kwargs["needswitch_cfg"] is True assert call.kwargs["reservations_count"] == 1 info = call.kwargs["first_reservation"] assert info["pos_seen"] == 3 assert info["current_room_pos"] == 7 assert info["value"] == 5.0 def test_log_needswitch_empty_queue_logs_zero_count(): a = MagicMock() a.reservations = [] fudai_run_blocks.log_needswitch_check_details(a, False) call = next( c for c in a._log_kv.call_args_list if len(c.args) >= 2 and "检查预约回退条件" in c.args[1] ) assert call.kwargs["needswitch_cfg"] is False assert call.kwargs["reservations_count"] == 0 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("循环", "收到中断信号,退出循环") # ---- handle_queue_full_wait_at_earliest ---- # def test_queue_full_below_max_returns_false(): a = _make_analyser() a.high_value_fudai_max_reservations = 5 a.reservations = [{"future_ts": 100}] # 远小于 max a.queue_full_waiting_at_earliest = False assert ( fudai_run_blocks.handle_queue_full_wait_at_earliest( a, start_time=time.time(), focus_ref=[0.0], swipe_down_back_callback=MagicMock(), seek_reservation_room_callback=MagicMock(), sort_reservations_callback=MagicMock(), write_state_callback=MagicMock(), ) is False ) def test_queue_full_already_waiting_returns_false(): a = _make_analyser() a.high_value_fudai_max_reservations = 1 a.reservations = [{"future_ts": 100}, {"future_ts": 200}] a.queue_full_waiting_at_earliest = True # 已在等待 assert ( fudai_run_blocks.handle_queue_full_wait_at_earliest( a, start_time=time.time(), focus_ref=[0.0], swipe_down_back_callback=MagicMock(), seek_reservation_room_callback=MagicMock(), sort_reservations_callback=MagicMock(), write_state_callback=MagicMock(), ) is False ) def test_queue_full_triggers_wait_returns_true(): a = _make_analyser() a.high_value_fudai_max_reservations = 2 a.reservations = [{"future_ts": 100}, {"future_ts": 200}] a.queue_full_waiting_at_earliest = False a.reservation_back_swipe_delay = 0.6 from douyin.reservation import douyin_reservation_logic as drl with patch.object( drl, "handle_queue_full_wait_at_earliest", return_value=True ): result = fudai_run_blocks.handle_queue_full_wait_at_earliest( a, start_time=time.time(), focus_ref=[123.0], swipe_down_back_callback=MagicMock(), seek_reservation_room_callback=MagicMock(), sort_reservations_callback=MagicMock(), write_state_callback=MagicMock(), ) assert result is True assert a.queue_full_waiting_at_earliest is True assert a.reservation_focus_until_ts == 123.0 def test_queue_full_callback_returns_false_no_state_change(): """底层回调返回 False(无法等待)→ 不改 queue_full_waiting""" a = _make_analyser() a.high_value_fudai_max_reservations = 2 a.reservations = [{"future_ts": 100}, {"future_ts": 200}] a.queue_full_waiting_at_earliest = False a.reservation_back_swipe_delay = 0.6 from douyin.reservation import douyin_reservation_logic as drl with patch.object( drl, "handle_queue_full_wait_at_earliest", return_value=False ): result = fudai_run_blocks.handle_queue_full_wait_at_earliest( a, start_time=time.time(), focus_ref=[0.0], swipe_down_back_callback=MagicMock(), seek_reservation_room_callback=MagicMock(), sort_reservations_callback=MagicMock(), write_state_callback=MagicMock(), ) assert result is False assert a.queue_full_waiting_at_earliest is False # ---- log_skip_reservation_check_for_state ---- # def test_log_skip_when_waiting_for_lottery(): a = _make_analyser() a._waiting_for_lottery_result = True fudai_run_blocks.log_skip_reservation_check_for_state(a) msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2] assert any("正在等待开奖,跳过预约回退检查" in m for m in msgs) def test_log_skip_when_attending_reservation(): a = _make_analyser() a._waiting_for_lottery_result = False a._current_attending_reservation_fudai = True fudai_run_blocks.log_skip_reservation_check_for_state(a) msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2] assert any("正在参与预约福袋" in m for m in msgs) def test_log_skip_normal_state_no_log(): a = _make_analyser() a._waiting_for_lottery_result = False a._current_attending_reservation_fudai = False fudai_run_blocks.log_skip_reservation_check_for_state(a) a._log_kv.assert_not_called() # ---- diagnose_stage_with_logging ---- # def test_diagnose_stage_logs_and_caches_result(): a = _make_analyser() a._diagnose_stage_from_current_screen = MagicMock( return_value=("IN_LIVE_ROOM", "seen_text") ) stage, seen = fudai_run_blocks.diagnose_stage_with_logging( a, time.time(), screenshot_elapsed=0.5 ) assert stage == "IN_LIVE_ROOM" assert seen == "seen_text" assert a._last_diag_stage == "IN_LIVE_ROOM" assert a._last_diag_seen == "seen_text" assert a._last_diag_ts > 0 def test_diagnose_stage_swallows_log_exceptions(): a = _make_analyser() a._diagnose_stage_from_current_screen = MagicMock( return_value=("LIVE_CLOSED", "") ) a._log_kv.side_effect = RuntimeError("boom") stage, seen = fudai_run_blocks.diagnose_stage_with_logging( a, time.time(), screenshot_elapsed=0.1 ) assert stage == "LIVE_CLOSED" # ---- dispatch_stage ---- # def test_dispatch_coupon_popup_returns_true(): a = _make_analyser() result = fudai_run_blocks.dispatch_stage(a, "COUPON_POPUP", "", time.time()) assert result is True def test_dispatch_shopping_redpacket_returns_true(): a = _make_analyser() a.resolution_ratio_x = 1080 a.resolution_ratio_y = 2400 result = fudai_run_blocks.dispatch_stage( a, "SHOPPING_REDPACKET_POPUP", "", time.time() ) assert result is True def test_dispatch_fudai_detail_calls_handler_returns_false(): a = _make_analyser() a._handle_in_fudai_detail = MagicMock() result = fudai_run_blocks.dispatch_stage(a, "FUDai_DETAIL", "", time.time()) assert result is False a._handle_in_fudai_detail.assert_called_once() def test_dispatch_in_live_room_returns_false(): a = _make_analyser() a._just_switched_room = False a._handle_live_room_has_or_not_fudai = MagicMock() result = fudai_run_blocks.dispatch_stage(a, "IN_LIVE_ROOM", "", time.time()) assert result is False def test_dispatch_recommend_page_returns_false(): a = _make_analyser() a.resolution_ratio_x = 1080 a.resolution_ratio_y = 2400 a.FOLLOW_TAB_CLICK_DELAY = 0.5 a.ENTER_LIVE_CLICK_DELAY = 0.6 a.ENTER_LIVE_FINAL_DELAY = 1.0 a.RETURN_STEP_DELAY_SECONDS = 0.8 result = fudai_run_blocks.dispatch_stage(a, "RECOMMEND_PAGE", "", time.time()) assert result is False def test_dispatch_follow_list_calls_reflash_returns_false(): a = _make_analyser() from douyin.other import douyin_live_room with patch.object(douyin_live_room, "reflash_zhibo") as fake: result = fudai_run_blocks.dispatch_stage(a, "FOLLOW_LIST", "", time.time()) assert result is False fake.assert_called_once_with(a) def test_dispatch_lottery_result_returns_true(): a = _make_analyser() a._check_lottery_result_by_ocr.return_value = None result = fudai_run_blocks.dispatch_stage(a, "FUDai_RESULT", "", time.time()) assert result is True def test_dispatch_live_closed_returns_false(): a = _make_analyser() result = fudai_run_blocks.dispatch_stage(a, "LIVE_CLOSED", "", time.time()) assert result is False def test_dispatch_unknown_stage_logs_and_returns_false(): a = _make_analyser() result = fudai_run_blocks.dispatch_stage(a, "UNKNOWN_X", "", time.time()) assert result is False msgs = [c.args[1] for c in a._log_kv.call_args_list if len(c.args) >= 2] assert any("未匹配到特定阶段" in m for m in msgs) # ---- process_high_value_reservation_check ---- # def test_process_high_value_disabled_returns_false(): a = _make_analyser() assert ( fudai_run_blocks.process_high_value_reservation_check( a, time.time(), False, [{"future_ts": 100}] ) is False ) def test_process_high_value_no_reservations_returns_false(): a = _make_analyser() assert ( fudai_run_blocks.process_high_value_reservation_check( a, time.time(), True, [] ) is False ) def test_process_high_value_queue_full_triggers_return(): """队列已满时 process 返回 True 让主流程 return""" a = _make_analyser() a.reservations = [{"future_ts": 100}, {"future_ts": 200}, {"future_ts": 300}] a.high_value_fudai_max_reservations = 2 a.queue_full_waiting_at_earliest = False a.reservation_focus_until_ts = 0.0 a.reservation_back_swipe_delay = 0.6 a.reservation_after_action_pending = False a._seek_reservation_room = MagicMock(return_value=True) a.swipe_down_back_from_live = MagicMock() from douyin.reservation import douyin_reservation_logic as drl with patch.object(drl, "handle_queue_full_wait_at_earliest", return_value=True): result = fudai_run_blocks.process_high_value_reservation_check( a, time.time(), True, a.reservations ) assert result is True def test_process_high_value_queue_not_full_runs_normal_path(): """队列未满 → 进入 attend/cleanup 调度,返回 False""" a = _make_analyser() a.reservations = [{"future_ts": time.time() + 100}] a.high_value_fudai_max_reservations = 5 a.queue_full_waiting_at_earliest = False a.reservation_focus_until_ts = 0.0 a.reservation_back_swipe_delay = 0.6 a.reservation_after_action_pending = False a._seek_reservation_room = MagicMock(return_value=True) a.swipe_down_back_from_live = MagicMock() a._waiting_for_lottery_result = False a._current_attending_reservation_fudai = False a.needswitch = False # 走单间模式 cleanup 路径,避免触发外部依赖 from douyin.reservation import douyin_reservation_logic as drl with patch.object(drl, "cleanup_expired_reservations") as fake_cleanup: result = fudai_run_blocks.process_high_value_reservation_check( a, time.time(), True, a.reservations ) assert result is False fake_cleanup.assert_called_once() # ---- execute_reservation_attend_or_cleanup ---- # def _make_reservation_analyser(): a = MagicMock() a._log_kv = MagicMock() a.reservations = [{"future_ts": time.time() + 100, "prize_value_yuan": 5.0}] a.room_pos = 5 a.reservation_back_swipe_delay = 0.6 a.reservation_focus_until_ts = 0.0 a.reservation_after_action_pending = False a._current_attending_reservation_fudai = False return a def test_execute_reservation_multi_room_calls_attend_window(): """needswitch=True 时调用 process_reservation_attend_window""" a = _make_reservation_analyser() from douyin.reservation import douyin_reservation_logic as drl with patch.object( drl, "process_reservation_attend_window", return_value=True ) as fake_attend: fudai_run_blocks.execute_reservation_attend_or_cleanup( a, needswitch_cfg=True, focus_ref=[123.0], after_action_ref=[True], swipe_down_back_callback=MagicMock(), seek_reservation_room_callback=MagicMock(), sort_reservations_callback=MagicMock(), write_state_callback=MagicMock(), ) fake_attend.assert_called_once() # ref 值同步回写 assert a.reservation_focus_until_ts == 123.0 assert a.reservation_after_action_pending is True # preempted=True 时设置标志 assert a._current_attending_reservation_fudai is True def test_execute_reservation_single_room_calls_cleanup(): """needswitch=False 时只调用 cleanup_expired_reservations""" a = _make_reservation_analyser() from douyin.reservation import douyin_reservation_logic as drl write_cb = MagicMock() with patch.object(drl, "cleanup_expired_reservations") as fake_cleanup, patch.object( drl, "process_reservation_attend_window" ) as fake_attend: fudai_run_blocks.execute_reservation_attend_or_cleanup( a, needswitch_cfg=False, focus_ref=[0.0], after_action_ref=[False], swipe_down_back_callback=MagicMock(), seek_reservation_room_callback=MagicMock(), sort_reservations_callback=MagicMock(), write_state_callback=write_cb, ) fake_cleanup.assert_called_once_with(a, a.reservations, write_cb) fake_attend.assert_not_called() def test_execute_reservation_preempted_false_does_not_set_flag(): """preempted=False 时不应设置 _current_attending_reservation_fudai=True""" a = _make_reservation_analyser() from douyin.reservation import douyin_reservation_logic as drl with patch.object(drl, "process_reservation_attend_window", return_value=False): fudai_run_blocks.execute_reservation_attend_or_cleanup( a, needswitch_cfg=True, focus_ref=[0.0], after_action_ref=[False], swipe_down_back_callback=MagicMock(), seek_reservation_room_callback=MagicMock(), sort_reservations_callback=MagicMock(), write_state_callback=MagicMock(), ) assert a._current_attending_reservation_fudai is False def test_execute_reservation_single_room_swallows_cleanup_exception(): """单间模式 cleanup 抛错也不应崩""" a = _make_reservation_analyser() from douyin.reservation import douyin_reservation_logic as drl with patch.object( drl, "cleanup_expired_reservations", side_effect=RuntimeError("boom") ): fudai_run_blocks.execute_reservation_attend_or_cleanup( a, needswitch_cfg=False, focus_ref=[0.0], after_action_ref=[False], swipe_down_back_callback=MagicMock(), seek_reservation_room_callback=MagicMock(), sort_reservations_callback=MagicMock(), write_state_callback=MagicMock(), ) # 应记录失败日志 failure = [ c for c in a._log_kv.call_args_list if len(c.args) >= 2 and "单间模式下清理过期预约时出错" in c.args[1] ] assert len(failure) == 1