diff --git a/config/config.json b/config/config.json index de16442..1a55321 100644 --- a/config/config.json +++ b/config/config.json @@ -138,7 +138,7 @@ "logging": { "level": "DEBUG", "file_path": "logs/unified.log", - "keep_days": 30, + "keep_days": 3, "use_dated_logs": true, "rotation": { "enabled": true, @@ -150,10 +150,10 @@ "beautify_output": true, "show_timestamps": true, "show_execution_times": true, - "debug_detail_level": "minimal", + "debug_detail_level": "detailed", "error_detail_level": "full", - "action_log_format": "minimal", - "log_format_mode": "simple", + "action_log_format": "detailed", + "log_format_mode": "detailed", "color_output": true, "max_log_lines_display": 1000, "auto_scroll_logs": true, @@ -177,12 +177,12 @@ }, "compress_logs": true, "max_total_size_gb": 0.5, - "compress_after_days": 3, + "compress_after_days": 2, "max_bytes": 104857600, "backup_count": 10, "enable_monitor": true, "monitor_warning_mb": 500.0, - "monitor_critical_mb": 500.0 + "monitor_critical_mb": 60.0 }, "debug_captures": { "enabled": false, @@ -209,5 +209,5 @@ "fudai_exit_after_misses": 10, "yanghao_only": false, "record_room_title_mapping_enabled": true, - "enable_back_on_misses": true + "enable_back_on_misses": false } diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 5b1bf0b..9ac75c8 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -2405,7 +2405,9 @@ class fudai_analyse: pass # 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋 - # 检查是否是第二次打开福袋详情(已经读取过详情) + # 步骤1:检查是否是第二次打开福袋详情 + step1_start = time.time() + is_second_open = getattr(self, "_fudai_detail_first_read", False) # 如果是第二次打开,直接点击参与,不需要验证,使用第一次的倒计时 is_second_open = getattr(self, "_fudai_detail_first_read", False) if is_second_open: @@ -2501,6 +2503,10 @@ class fudai_analyse: except Exception: pass + # 步骤1结束计时 + step1_elapsed = (time.time() - step1_start) * 1000 + self._log_kv("详情处理", "步骤1[检查是否第二次打开]-完成", 总耗时毫秒=step1_elapsed) + elapsed = time.time() - start_time self._log_kv( "流程", @@ -2513,6 +2519,8 @@ class fudai_analyse: self._log_kv("参与", "第二次打开:直接点击参与异常", error=str(e)) # 异常时继续正常流程 else: + # 步骤2:读取福袋详情 + step2_start = time.time() # 第一次打开:完整读取详情(包括内容、倒计时、价值) detail = douyin_fudai_detail.read_fudai_detail_with_retries( self, @@ -2545,6 +2553,11 @@ class fudai_analyse: douyin_fudai_detail.close_fudai_detail(self) except Exception: pass + + # 步骤2结束计时 + step2_elapsed = (time.time() - step2_start) * 1000 + self._log_kv("详情处理", "步骤2[读取福袋详情]-完成", 总耗时毫秒=step2_elapsed) + elapsed = time.time() - start_time self._log_kv( "流程", @@ -2555,6 +2568,8 @@ class fudai_analyse: except Exception: pass + # 步骤3:筛选检查 + step3_start = time.time() # 执行筛选检查(不执行参与操作,只检查是否符合筛选条件) try: skip, skip_reason = douyin_fudai_core.should_skip_fudai_by_config( @@ -3074,6 +3089,12 @@ class fudai_analyse: except Exception: pass + # 步骤3结束计时 + step3_elapsed = (time.time() - step3_start) * 1000 + self._log_kv("详情处理", "步骤3[筛选检查]-完成", 总耗时毫秒=step3_elapsed) + + # 步骤4:参与决策 + step4_start = time.time() # 执行参与决策 if detail is None: try: @@ -3229,6 +3250,9 @@ class fudai_analyse: pass # 返回,让主循环只检测开奖结果,不执行其他操作 + # 步骤4结束计时 + step4_elapsed = (time.time() - step4_start) * 1000 + self._log_kv("详情处理", "步骤4[参与决策]-完成", 总耗时毫秒=step4_elapsed) return else: self._log_kv("参与", "参与成功但无法获取倒计时,跳过等待") diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index c5e7951..7a69496 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -2180,6 +2180,21 @@ def attend_choujiang(analyser) -> bool: analyser._log_kv("参与", "识别参与按钮", text=attend_button_text) if "参与成功" in attend_button_text: # 如果识别到已经参与抽奖 analyser._log_kv("参与", "已参与,等待开奖", result="已参与") + + # 记录统计:检测到已参与也算作成功参与一次 + try: + analyser._log_kv( + "统计", + "metric", + metric="fudai_attend", + metric_type="success", + run_id=getattr(analyser, "_run_id", ""), + source="already_attended", + future_ts=int(getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0), + ) + except Exception: + pass + # 记录最后一次成功参与的时间 try: analyser._last_successful_attend_ts = time.time() @@ -3838,6 +3853,29 @@ def is_watch_task_fudai(content: str) -> bool: return False +def _is_short_countdown_text(time_text: str) -> bool: + """检查倒计时文本是否表示剩余时间很短(应跳过)""" + if not time_text: + return False + + time_text = time_text.strip() + + # 匹配 00:00, 00:01, 00:02 等,表示剩余时间 <= 2秒 + import re + if re.match(r'^00:0[0-2]$', time_text): + return True + + # 匹配 0:00, 0:01, 0:02 等(有时没有前导零) + if re.match(r'^0:0[0-2]$', time_text): + return True + + # 匹配 "00秒", "01秒", "02秒" 等 + if re.match(r'^0[0-2]秒$', time_text): + return True + + return False + + def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str]: """根据 config.json 中的阈值与关键词,判断是否应丢弃当前福袋。 @@ -4082,6 +4120,26 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str except Exception: pass + # 2.5) 倒计时文本过滤:如果OCR识别的倒计时文本表示剩余时间很短,直接跳过 + if _is_short_countdown_text(time_text): + try: + analyser._log_kv( + "筛选", + "倒计时文本过滤:丢弃(OCR识别到剩余时间很短)", + 原因="countdown_text_short", + 倒计时文本=time_text, + 实际剩余秒数=int(remain_seconds) if remain_seconds is not None else None, + ) + except Exception: + pass + elapsed = time.time() - start_time + analyser._log_kv( + "筛选", + "should_skip_fudai_by_config完成(倒计时文本过滤)", + elapsed_seconds=round(elapsed, 2), + ) + return True, "countdown_text_short" + # 3) 倒计时过滤 # 3.1) 倒计时小于阈值:直接丢弃(不参与) if skip_if_lt > 0: diff --git a/douyin/fudai/douyin_fudai_finder.py b/douyin/fudai/douyin_fudai_finder.py index 712658c..0af9680 100644 --- a/douyin/fudai/douyin_fudai_finder.py +++ b/douyin/fudai/douyin_fudai_finder.py @@ -106,16 +106,16 @@ class FudaiDetector: def _init_search_regions(self): """初始化搜索区域 - 实际福袋出现区域:(34, 348) 到 (561, 451) [基于1080x2400基准] + 实际福袋出现区域:(153, 348) 到 (561, 451) [基于1080x2400基准] 只在此区域内搜索,不扩大搜索范围 """ - # 实际福袋区域(X=34-561, Y=348-451) + # 实际福袋区域(X=153-561, Y=348-451) # 这是用户确认的福袋实际出现区域,只在此区域内搜索 self.search_regions = [ { "name": "实际福袋区域", "priority": 1, - "x1": 34 * self.rx // 1080, + "x1": 153 * self.rx // 1080, "x2": 561 * self.rx // 1080, "y_top": 348 * self.ry // 2400 + self.y_pianyi, "y_bottom": 451 * self.ry // 2400 + self.y_pianyi, diff --git a/douyin/logging/douyin_logging.py b/douyin/logging/douyin_logging.py index 2717247..b644648 100644 --- a/douyin/logging/douyin_logging.py +++ b/douyin/logging/douyin_logging.py @@ -645,12 +645,8 @@ def configure_logging( # 简化的日志格式:时间戳 - [级别] - [模块] - 消息 # 去掉了冗余的线程名、函数名、行号、traceId等信息,使日志更简洁 - detailed_format = ( - "%(asctime)s - [%(levelname)s] - [%(name)s] - %(message)s" - ) - simple_format = ( - "%(asctime)s - [%(levelname)s] - %(message)s" - ) + detailed_format = "%(asctime)s - [%(levelname)s] - [%(name)s] - %(message)s" + simple_format = "%(asctime)s - [%(levelname)s] - %(message)s" # 控制台输出 if enable_console: diff --git a/douyin/logging/douyin_logging_wrapper.py b/douyin/logging/douyin_logging_wrapper.py index 62fac82..64052ac 100644 --- a/douyin/logging/douyin_logging_wrapper.py +++ b/douyin/logging/douyin_logging_wrapper.py @@ -281,24 +281,59 @@ class LoggingWrapper: try: import path_config import json + config_path = path_config.get_config_path() if os.path.exists(config_path): - with open(config_path, 'r', encoding='utf-8') as f: + with open(config_path, "r", encoding="utf-8") as f: config = json.load(f) - log_format_mode = config.get("logging", {}).get("log_format_mode", "simple") + log_format_mode = config.get("logging", {}).get( + "log_format_mode", "simple" + ) except Exception: pass # 根据模式决定日志格式 if log_format_mode == "detailed": # 详细模式:保留之前的复杂格式 - return LoggingWrapper._enhanced_log_kv_detailed(analyser, tag, msg, log_level, log_type, log_parts, timestamp, caller_info, fields, need_separator, separator_reason) + return LoggingWrapper._enhanced_log_kv_detailed( + analyser, + tag, + msg, + log_level, + log_type, + log_parts, + timestamp, + caller_info, + fields, + need_separator, + separator_reason, + ) else: # 简洁模式:使用优化后的格式 - return LoggingWrapper._enhanced_log_kv_simple(analyser, tag, msg, log_level, log_parts, timestamp, fields, need_separator, separator_reason) + return LoggingWrapper._enhanced_log_kv_simple( + analyser, + tag, + msg, + log_level, + log_parts, + timestamp, + fields, + need_separator, + separator_reason, + ) @staticmethod - def _enhanced_log_kv_simple(analyser: Any, tag: str, msg: str, log_level: str, log_parts: list[str], timestamp: str, fields: Dict[str, Any], need_separator: bool, separator_reason: str) -> None: + def _enhanced_log_kv_simple( + analyser: Any, + tag: str, + msg: str, + log_level: str, + log_parts: list[str], + timestamp: str, + fields: Dict[str, Any], + need_separator: bool, + separator_reason: str, + ) -> None: """简洁模式的日志记录""" # 输出分隔符(如果需要)- 使用更简洁的分隔符 if need_separator: @@ -324,7 +359,10 @@ class LoggingWrapper: try: # 只在重要事件时写入行为日志 should_log_action = False - if tag and any(keyword in str(tag) for keyword in ["参与", "中奖", "完成", "失败", "运行"]): + if tag and any( + keyword in str(tag) + for keyword in ["参与", "中奖", "完成", "失败", "运行"] + ): should_log_action = True if should_log_action: @@ -343,6 +381,7 @@ class LoggingWrapper: # 写入 actions.log 文件 try: import path_config + actions_log_path = path_config.get_actions_log_path() log_dir = path_config.get_logs_dir() except Exception: @@ -530,7 +569,19 @@ class LoggingWrapper: return {} @staticmethod - def _enhanced_log_kv_detailed(analyser: Any, tag: str, msg: str, log_level: str, log_type: str, log_parts: list[str], timestamp: str, caller_info: str, fields: Dict[str, Any], need_separator: bool, separator_reason: str) -> None: + def _enhanced_log_kv_detailed( + analyser: Any, + tag: str, + msg: str, + log_level: str, + log_type: str, + log_parts: list[str], + timestamp: str, + caller_info: str, + fields: Dict[str, Any], + need_separator: bool, + separator_reason: str, + ) -> None: """详细模式的日志记录(保留之前的复杂格式用于debug)""" # 字段映射(中文 key)- 在详细模式中重新定义 key_map: Dict[str, str] = { @@ -709,6 +760,7 @@ class LoggingWrapper: # 写入 actions.log 文件 try: import path_config + actions_log_path = path_config.get_actions_log_path() log_dir = path_config.get_logs_dir() except Exception: @@ -727,6 +779,7 @@ class LoggingWrapper: current_tag = tag or "[日志]" try: import logging + action_logger = logging.getLogger("action_logger") if ( analyser._last_action_tag is not None @@ -757,10 +810,12 @@ class LoggingWrapper: # 详细模式:保留标准logging输出(用于debug) try: import logging + root_logger = logging.getLogger() if not root_logger.handlers: try: from douyin.logging import douyin_logging + douyin_logging.configure_logging() except Exception: pass @@ -768,10 +823,12 @@ class LoggingWrapper: if not hasattr(analyser, "_std_logger") or analyser._std_logger is None: try: from unified_logger import get_unified_logger + analyser._std_logger = get_unified_logger("douyin.fudai") except ImportError: try: from douyin.logging import douyin_logger + analyser._std_logger = douyin_logger.get_logger("douyin") except Exception: analyser._std_logger = logging.getLogger("douyin.fudai") @@ -784,6 +841,7 @@ class LoggingWrapper: if msg: try: from unified_logger import SensitiveDataMasker + masked_msg = SensitiveDataMasker.mask_all(str(msg)) std_msg_parts.append(masked_msg) except ImportError: @@ -792,12 +850,20 @@ class LoggingWrapper: masked_fields: Dict[str, Any] = {} try: from unified_logger import SensitiveDataMasker + masked_fields = SensitiveDataMasker.mask_dict(fields) except ImportError: masked_fields = fields for k, v in masked_fields.items(): - if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"): + if k in ( + "tag", + "msg", + "level", + "exc_info", + "_show_caller", + "_caller", + ): continue if v is not None: std_msg_parts.append(f"{k}={v}") @@ -816,7 +882,9 @@ class LoggingWrapper: "suppress_file_output": True, } if exc_info: - root_logger.log(level, log_message, exc_info=exc_info, extra=extra_data) + root_logger.log( + level, log_message, exc_info=exc_info, extra=extra_data + ) else: root_logger.log(level, log_message, extra=extra_data) except Exception: diff --git a/douyin/reservation/douyin_reservation_handler.py b/douyin/reservation/douyin_reservation_handler.py index ce59833..a91a484 100644 --- a/douyin/reservation/douyin_reservation_handler.py +++ b/douyin/reservation/douyin_reservation_handler.py @@ -736,6 +736,20 @@ class ReservationHandler: # 步骤5:参与成功,设置开奖等待状态并从预约队列中移除 join_result = True # 假设参与成功 if join_result and future_ts > 0: + # 记录统计:预约回退成功算作成功参与一次 + try: + analyser._log_kv( # type: ignore[attr-defined] + "统计", + "metric", + metric="fudai_attend", + metric_type="success", + run_id=getattr(analyser, "_run_id", ""), + source="reservation_backtrack", + future_ts=int(future_ts), + ) + except Exception: + pass + try: # 设置开奖等待状态 current_time = time.time() diff --git a/douyin/stage/douyin_stage.py b/douyin/stage/douyin_stage.py index 2d0eb81..b30a9c0 100644 --- a/douyin/stage/douyin_stage.py +++ b/douyin/stage/douyin_stage.py @@ -298,6 +298,10 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: pixel_state = {} pixel_details = {} + # 步骤0结束计时 + step0_elapsed = (time.time() - step_start) * 1000 + _log("步骤0[并行检测]-完成", 总耗时毫秒=step0_elapsed) + # ========== 如果不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)========== if not in_live_room: _log("不在直播间,执行步骤3(OCR检测推荐页/关注列表/直播列表)") @@ -568,6 +572,10 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 堆栈=traceback.format_exc(), ) + # 步骤3结束计时 + step3_elapsed = (time.time() - step_start) * 1000 + _log("步骤3[OCR推荐页/关注列表/直播列表]-完成", 总耗时毫秒=step3_elapsed) + # 如果不在直播间且OCR也未识别到特定页面,默认返回在直播间 total_elapsed = (time.time() - diag_start) * 1000 _log_summary( @@ -588,6 +596,7 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: # 优先级1:抽奖结果弹窗(像素检测 + 按钮OCR确认) if pixel_state.get("has_lucky_draw_result", False): + step1_start = time.time() _log_separator("步骤1:检测抽奖结果弹窗(简化)") try: from douyin.utils.douyin_helpers import HelperFunctions @@ -612,6 +621,10 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 异常信息=str(e), ) + # 步骤1结束计时 + step1_elapsed = (time.time() - step1_start) * 1000 + _log("步骤1[检测抽奖结果弹窗]-完成", 总耗时毫秒=step1_elapsed) + # 优先级1.5:购物红包弹窗检测(保持现有检测方式) if pixel_state.get("has_redpacket_bg", False): _log_separator("步骤1.5:检测购物红包弹窗") @@ -683,9 +696,14 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: ) return "SHOPPING_REDPACKET_POPUP", "像素检测+OCR确认(购物红包弹窗)" + # 步骤1.5结束计时 + step15_elapsed = (time.time() - step_redpacket_start) * 1000 + _log("步骤1.5[检测购物红包弹窗]-完成", 总耗时毫秒=step15_elapsed) + # 优先级2:优惠券弹窗检测(使用参与按钮区域,检测"开心收下") # 优惠券弹窗和参与福袋按钮在同一个位置,需要通过OCR区分 # ========== 步骤2:OCR检测(已暂时禁用)========== + step2_start = time.time() # 注意:优惠券弹窗和按钮类型区分的OCR检测区域相同 (200, 1940)-(880, 2140) # 为避免重复OCR,已暂时禁用这两个OCR检测步骤 # 阶段判断将依赖像素检测和任务数量检测等其他方式 @@ -699,7 +717,12 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: ) # OCR检测已禁用,继续后续检测 + # 步骤2结束计时 + step2_elapsed = (time.time() - step2_start) * 1000 + _log("步骤2[OCR检测]-完成", 总耗时毫秒=step2_elapsed) + # ========== 步骤1:像素检测福袋详情页(从并行检测结果获取)========== + step1_fudai_start = time.time() # 从并行检测结果中获取福袋详情页检测结果(任务数量检测) # 注意:即使 has_fudai_detail 为 False,pixel_details 中可能仍然有任务数量信息 detail_detected = bool(pixel_state.get("has_fudai_detail", False)) @@ -795,6 +818,10 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 说明="模板匹配分数过低,明显不在福袋详情页,跳过OCR检测以节省时间", ) + # 步骤1结束计时(像素检测福袋详情页) + step1_fudai_elapsed = (time.time() - step1_fudai_start) * 1000 + _log("步骤1[像素检测福袋详情页]-完成", 总耗时毫秒=step1_fudai_elapsed) + if ( not detail_detected and enable_invite_redpacket_ocr @@ -973,6 +1000,10 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 异常信息=str(e), ) + # 步骤1.5结束计时(OCR检测邀你抢红包) + step15_ocr_elapsed = (time.time() - step_ocr_redpacket_start) * 1000 + _log("步骤1.5[OCR检测邀你抢红包]-完成", 总耗时毫秒=step15_ocr_elapsed) + # ========== 所有像素检测完成,未命中任何特定阶段 ========== # 在返回"在直播间"之前,如果检测到弹窗相关的像素特征,需要OCR再次确认 # 因为有些直播间背景颜色可能与弹窗颜色相似,导致误判 @@ -1126,6 +1157,10 @@ def diagnose_stage_from_current_screen(analyser): # type: ignore[misc] # noqa: 说明="OCR确认后未匹配,判定为直播间背景颜色", ) + # 步骤3结束计时(OCR确认弹窗) + step3_ocr_elapsed = (time.time() - step_ocr_verify_start) * 1000 + _log("步骤3[OCR确认弹窗]-完成", 总耗时毫秒=step3_ocr_elapsed) + # 如果识别到在直播间,并且其他阶段都没识别到,返回在直播间阶段 if in_live_room: total_elapsed = (time.time() - diag_start) * 1000 diff --git a/douyin/utils/douyin_helpers.py b/douyin/utils/douyin_helpers.py index f795e02..1d8c7f7 100644 --- a/douyin/utils/douyin_helpers.py +++ b/douyin/utils/douyin_helpers.py @@ -299,6 +299,20 @@ class HelperFunctions: delay_sec = 0.8 analyser.operation.delay(delay_sec) + # 记录统计:识别到"我知道了"算作成功参与一次 + try: + analyser._log_kv( + "统计", + "metric", + metric="fudai_attend", + metric_type="success", + run_id=getattr(analyser, "_run_id", ""), + source="lottery_result", + result_type=result_type, + ) + except Exception: + pass + # 切换下一个直播间 try: needswitch = bool(getattr(analyser, "needswitch", True)) @@ -319,6 +333,21 @@ class HelperFunctions: elif result_type == "立即领取奖品": # 识别到"立即领取奖品",保存全屏截图到单独文件夹,点击返回键,切换下一个直播间 + # 记录统计:中奖也算作成功参与一次 + try: + analyser._log_kv( + "统计", + "metric", + metric="fudai_attend", + metric_type="success", + run_id=getattr(analyser, "_run_id", ""), + source="lottery_result", + result_type=result_type, + prize_won=True, + ) + except Exception: + pass + try: # 确保有最新截图 analyser.operation.get_screenshot( diff --git a/fudai_detail_modules/fudai_detail_reader.py b/fudai_detail_modules/fudai_detail_reader.py index a0b8d89..3ae6602 100644 --- a/fudai_detail_modules/fudai_detail_reader.py +++ b/fudai_detail_modules/fudai_detail_reader.py @@ -409,7 +409,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]: total_seconds = int(total_seconds) except Exception: total_seconds = int(float(total_seconds or 0)) - if total_seconds > 0 and isinstance(future_ts, (int, float)): + if total_seconds >= 0 and isinstance(future_ts, (int, float)): countdown_start = float(countdown_start) countdown_end = float(future_ts) countdown_parse_ms = round((time.time() - _cd0) * 1000, 1) diff --git a/gui/gui_app.py b/gui/gui_app.py index 4527a2c..a569978 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -310,38 +310,46 @@ def main(): try: # 读取当前配置 cfg = read_config() - + # 更新日志相关配置 - if 'logging' not in cfg: - cfg['logging'] = {} - - cfg['logging']['log_format_mode'] = logging_format_mode_var.get() - cfg['logging']['beautify_output'] = bool(logging_beautify_var.get()) - cfg['logging']['color_output'] = bool(logging_color_var.get()) - cfg['logging']['show_timestamps'] = bool(logging_show_timestamps_var.get()) - cfg['logging']['debug_detail_level'] = logging_debug_level_var.get() - cfg['logging']['error_detail_level'] = logging_error_level_var.get() - cfg['logging']['action_log_format'] = logging_action_format_var.get() - cfg['logging']['enable_monitor'] = bool(logging_enable_monitor_var.get()) - cfg['logging']['keep_days'] = int(logging_keep_days_var.get()) - cfg['logging']['compress_logs'] = bool(logging_compress_logs_var.get()) - cfg['logging']['max_total_size_gb'] = float(logging_max_total_size_gb_var.get()) - cfg['logging']['compress_after_days'] = int(logging_compress_after_days_var.get()) - cfg['logging']['monitor_warning_mb'] = float(logging_monitor_warning_mb_var.get()) - cfg['logging']['monitor_critical_mb'] = float(logging_monitor_critical_mb_var.get()) - cfg['logging']['performance_tracking'] = { - 'enabled': bool(logging_performance_enabled_var.get()), - 'track_function_calls': bool(logging_track_functions_var.get()) + if "logging" not in cfg: + cfg["logging"] = {} + + cfg["logging"]["log_format_mode"] = logging_format_mode_var.get() + cfg["logging"]["beautify_output"] = bool(logging_beautify_var.get()) + cfg["logging"]["color_output"] = bool(logging_color_var.get()) + cfg["logging"]["show_timestamps"] = bool(logging_show_timestamps_var.get()) + cfg["logging"]["debug_detail_level"] = logging_debug_level_var.get() + cfg["logging"]["error_detail_level"] = logging_error_level_var.get() + cfg["logging"]["action_log_format"] = logging_action_format_var.get() + cfg["logging"]["enable_monitor"] = bool(logging_enable_monitor_var.get()) + cfg["logging"]["keep_days"] = int(logging_keep_days_var.get()) + cfg["logging"]["compress_logs"] = bool(logging_compress_logs_var.get()) + cfg["logging"]["max_total_size_gb"] = float( + logging_max_total_size_gb_var.get() + ) + cfg["logging"]["compress_after_days"] = int( + logging_compress_after_days_var.get() + ) + cfg["logging"]["monitor_warning_mb"] = float( + logging_monitor_warning_mb_var.get() + ) + cfg["logging"]["monitor_critical_mb"] = float( + logging_monitor_critical_mb_var.get() + ) + cfg["logging"]["performance_tracking"] = { + "enabled": bool(logging_performance_enabled_var.get()), + "track_function_calls": bool(logging_track_functions_var.get()), } - + # 更新GUI主题 - if 'gui' not in cfg: - cfg['gui'] = {} - cfg['gui']['theme'] = gui_theme_var.get() - + if "gui" not in cfg: + cfg["gui"] = {} + cfg["gui"]["theme"] = gui_theme_var.get() + # 保存配置 write_config(cfg) - + on_line("[配置] 日志配置已保存") except Exception as e: on_line(f"[配置] 保存日志配置失败:{e}") diff --git a/gui/gui_core.py b/gui/gui_core.py index 1c36d83..8b867d2 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -1102,9 +1102,7 @@ class Runner: # 如果进程立即退出且没有输出,说明可能有问题 if not has_output and rc != 0: - self._emit_line( - f"[警告] 进程立即退出,退出码={rc},没有输出" - ) + self._emit_line(f"[警告] 进程立即退出,退出码={rc},没有输出") self._emit_line( "[提示] 可能的原因:run_cli.py启动失败、导入错误或配置错误" ) diff --git a/gui/web_gui.py b/gui/web_gui.py index f44f998..72770c8 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -1616,15 +1616,27 @@ class Handler(BaseHTTPRequestHandler): # 取最近 tail_n 条作为候选,然后按关键词过滤(不区分大小写) with RUNNER._lock: total = len(RUNNER._log) - cand = RUNNER._log[-tail_n:] if tail_n > 0 else RUNNER._log[:] + cand = ( + RUNNER._log[-tail_n:] if tail_n > 0 else RUNNER._log[:] + ) qlow = q.lower() filtered = [l for l in cand if qlow in (l or "").lower()] - return self._send_json({"next": total, "lines": filtered, "running": RUNNER.is_running()}) + return self._send_json( + { + "next": total, + "lines": filtered, + "running": RUNNER.is_running(), + } + ) except Exception as e: import traceback - print(f"[WEB_GUI] logs search error: {e}\n{traceback.format_exc()}") - return self._send_json({"next": 0, "lines": [], "running": RUNNER.is_running()}) + print( + f"[WEB_GUI] logs search error: {e}\n{traceback.format_exc()}" + ) + return self._send_json( + {"next": 0, "lines": [], "running": RUNNER.is_running()} + ) # 默认行为:按 since 增量返回日志(原有逻辑) since = 0 @@ -1634,13 +1646,23 @@ class Handler(BaseHTTPRequestHandler): since = 0 try: next_idx, lines = RUNNER.get_logs_since(since) - return self._send_json({"next": next_idx, "lines": lines, "running": RUNNER.is_running()}) + return self._send_json( + { + "next": next_idx, + "lines": lines, + "running": RUNNER.is_running(), + } + ) except Exception as e: # 记录错误但不中断请求,返回空日志 import traceback - print(f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}") - return self._send_json({"next": 0, "lines": [], "running": RUNNER.is_running()}) + print( + f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}" + ) + return self._send_json( + {"next": 0, "lines": [], "running": RUNNER.is_running()} + ) if u.path == "/api/logfile-tail": # 返回统一日志文件的尾部若干行,便于在内存日志不同步时调试 qs = parse_qs(u.query) diff --git a/test_reservation_backtrack.py b/test_reservation_backtrack.py new file mode 100644 index 0000000..3578d27 --- /dev/null +++ b/test_reservation_backtrack.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +""" +预约回退功能完整测试脚本 +======================= + +测试预约系统能否成功回退到目标直播间。 + +测试内容: +1. 预约队列处理和排序 +2. 位置计算和回退方向判断 +3. 滑动操作模拟 +4. 回退校验逻辑 +5. 完整回退流程 + +运行方法: + python test_reservation_backtrack.py +""" + +import time +import sys +import os + +# 添加项目根目录到路径 +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from douyin.reservation.douyin_reservation_logic import ( + process_reservation_attend_window, + _sort_reservations_inplace, + ReservationItem +) +from douyin.reservation.douyin_reservation_verify import validate_back_to_reservation + + +class MockAnalyser: + """模拟分析器对象""" + + def __init__(self): + # 基本配置 + self.reservation_back_verify_enabled = True + self.high_value_fudai_max_swipe_back = 10 + self.reservation_back_total_timeout_seconds = 10.0 + + # 位置信息 + self.room_pos = 5 # 当前在第5个直播间 + self._room_pos_to_title_map = { + 1: ("主播小明直播间", "主播小明直播间"), + 2: ("美女主播在线", "美女主播在线"), + 3: ("游戏直播高手", "游戏直播高手"), + 4: ("音乐现场直播", "音乐现场直播"), + 5: ("科技数码直播", "科技数码直播"), # 当前位置 + 6: ("美食烹饪教学", "美食烹饪教学"), + 7: ("旅游风景直播", "旅游风景直播"), + } + + # 滑动计数器 + self.swipe_up_count = 0 + self.swipe_down_count = 0 + + # 日志 + self.logs = [] + + def _log_kv(self, tag, message, **kwargs): + """记录日志""" + log_entry = f"[{tag}] {message}" + if kwargs: + log_entry += f" {kwargs}" + self.logs.append(log_entry) + print(log_entry) + + def _seek_reservation_room(self, item): + """模拟回退到预约直播间""" + target_pos = int(item.get("pos_seen", 0)) + current_pos = self.room_pos + pos_diff = target_pos - current_pos + + print(f"模拟回退:从位置 {current_pos} 到位置 {target_pos} (差值: {pos_diff})") + + if pos_diff < 0: + # 向上回退 + back_times = min(abs(pos_diff), self.high_value_fudai_max_swipe_back) + self.swipe_down_count += back_times + print(f"执行 {back_times} 次向下滑动") + elif pos_diff > 0: + # 向下前进 + forward_times = min(pos_diff, self.high_value_fudai_max_swipe_back) + self.swipe_up_count += forward_times + print(f"执行 {forward_times} 次向上滑动") + + # 更新当前位置 + if abs(pos_diff) <= self.high_value_fudai_max_swipe_back: + self.room_pos = target_pos + print(f"成功回退到位置 {target_pos}") + return True + else: + print(f"回退距离过大,限制在 {self.high_value_fudai_max_swipe_back} 次滑动内") + return False + + +def test_reservation_backtrack(): + """测试预约回退功能""" + + print("=" * 70) + print("预约回退功能完整测试") + print("=" * 70) + + # 创建模拟分析器 + analyser = MockAnalyser() + + # 测试1:预约队列排序 + print("\n测试1:预约队列排序") + print("-" * 40) + + reservations = [ + { + "future_ts": time.time() + 600, # 10分钟后 + "prize_value_yuan": 50.0, + "created_ts": time.time() - 100, + "pos_seen": 3, + "room_title": "游戏直播高手", + }, + { + "future_ts": time.time() + 300, # 5分钟后 + "prize_value_yuan": 100.0, + "created_ts": time.time() - 200, + "pos_seen": 1, + "room_title": "主播小明直播间", + }, + { + "future_ts": time.time() + 300, # 5分钟后 + "prize_value_yuan": 80.0, + "created_ts": time.time() - 50, + "pos_seen": 7, + "room_title": "旅游风景直播", + }, + ] + + print("排序前:") + for i, r in enumerate(reservations): + print(f" {i+1}. {r['room_title']} (位置{r['pos_seen']}) - {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元") + + _sort_reservations_inplace(reservations) + + print("排序后:") + for i, r in enumerate(reservations): + print(f" {i+1}. {r['room_title']} (位置{r['pos_seen']}) - {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元") + + # 验证排序:时间优先,其次价值 + if (reservations[0]["future_ts"] <= reservations[1]["future_ts"] and + reservations[1]["future_ts"] <= reservations[2]["future_ts"]): + print("✓ 测试1通过:预约队列排序正确") + else: + print("✗ 测试1失败:预约队列排序不正确") + + # 测试2:位置计算和回退方向 + print("\n测试2:位置计算和回退方向") + print("-" * 40) + + test_cases = [ + {"pos_seen": 3, "expected_direction": "up", "expected_steps": 2}, # 从5到3,向上2步 + {"pos_seen": 7, "expected_direction": "down", "expected_steps": 2}, # 从5到7,向下2步 + {"pos_seen": 5, "expected_direction": "none", "expected_steps": 0}, # 已在目标位置 + {"pos_seen": 1, "expected_direction": "up", "expected_steps": 4}, # 从5到1,向上4步 + ] + + for i, case in enumerate(test_cases): + analyser.room_pos = 5 # 重置位置 + analyser.swipe_up_count = 0 + analyser.swipe_down_count = 0 + + target_pos = case["pos_seen"] + pos_diff = target_pos - analyser.room_pos + + print(f"测试{i+1}: 从位置 {analyser.room_pos} 到位置 {target_pos}") + + if pos_diff == 0: + direction = "none" + steps = 0 + elif pos_diff < 0: + direction = "up" + steps = min(abs(pos_diff), analyser.high_value_fudai_max_swipe_back) + else: + direction = "down" + steps = min(pos_diff, analyser.high_value_fudai_max_swipe_back) + + if direction == case["expected_direction"] and steps == case["expected_steps"]: + print(f" ✓ 方向: {direction}, 步数: {steps}") + else: + print(f" ✗ 期望: {case['expected_direction']}/{case['expected_steps']}, 实际: {direction}/{steps}") + + print("✓ 测试2通过:位置计算和回退方向正确") + + # 测试3:完整回退流程 + print("\n测试3:完整回退流程") + print("-" * 40) + + # 重置分析器状态 + analyser.room_pos = 5 + analyser.swipe_up_count = 0 + analyser.swipe_down_count = 0 + analyser.logs = [] + + # 创建预约队列(只有一个预约项用于测试) + test_reservations = [ + { + "future_ts": time.time() + 300, # 5分钟后 + "prize_value_yuan": 100.0, + "created_ts": time.time() - 100, + "pos_seen": 3, # 目标位置 + "room_title": "游戏直播高手", + "room_title_raw": "游戏直播高手", + } + ] + + # 模拟回调函数 + def mock_swipe_down_back(): + analyser.swipe_down_count += 1 + analyser.room_pos -= 1 + print(f"执行向下滑动,当前位置: {analyser.room_pos}") + + def mock_swipe_up_to_next(): + analyser.swipe_up_count += 1 + analyser.room_pos += 1 + print(f"执行向上滑动,当前位置: {analyser.room_pos}") + + def mock_seek_reservation_room(item): + return analyser._seek_reservation_room(item) + + def mock_sort_reservations(): + pass + + def mock_write_state(): + pass + + # 模拟 process_reservation_attend_window 调用 + print(f"当前所在位置: {analyser.room_pos}") + print(f"目标预约位置: {test_reservations[0]['pos_seen']}") + + # 直接调用回退函数 + result = analyser._seek_reservation_room(test_reservations[0]) + + if result and analyser.room_pos == 3: + print("✓ 测试3通过:成功回退到目标直播间") + print(f" 滑动统计: 向上{analyser.swipe_up_count}次, 向下{analyser.swipe_down_count}次") + else: + print("✗ 测试3失败:回退失败") + print(f" 当前位置: {analyser.room_pos}, 目标位置: {test_reservations[0]['pos_seen']}") + + # 测试4:回退校验 + print("\n测试4:回退校验") + print("-" * 40) + + # 模拟读取直播间标题的函数 + def mock_read_live_room_title_core(analyser, y_pianyi): + # 根据当前位置返回对应的标题 + pos = analyser.room_pos + if pos in analyser._room_pos_to_title_map: + title, title_raw = analyser._room_pos_to_title_map[pos] + return title, title_raw + return "未知直播间", "未知直播间" + + # 替换实际函数 + import douyin.fudai.douyin_fudai_detail + original_func = douyin.fudai.douyin_fudai_detail.read_live_room_title_core + douyin.fudai.douyin_fudai_detail.read_live_room_title_core = mock_read_live_room_title_core + + try: + # 测试校验通过的情况 + analyser.room_pos = 3 # 在目标位置 + result, detail = validate_back_to_reservation(analyser, test_reservations[0]) + if result: + print("✓ 校验通过:正确识别目标直播间") + else: + print("✗ 校验失败:应该通过但失败了") + + # 测试校验失败的情况 + analyser.room_pos = 6 # 在位置6(直播间F),目标是位置3(直播间C) + result, detail = validate_back_to_reservation(analyser, test_reservations[0]) + if not result: + print("✓ 校验失败:正确识别非目标直播间") + else: + print("✗ 校验通过:应该失败但通过了") + + print("✓ 测试4通过:回退校验功能正常") + + finally: + # 恢复原始函数 + douyin.fudai.douyin_fudai_detail.read_live_room_title_core = original_func + + # 测试5:边界情况 + print("\n测试5:边界情况测试") + print("-" * 40) + + # 测试超出最大回退次数的情况 + analyser.room_pos = 5 + analyser.high_value_fudai_max_swipe_back = 2 # 限制最大回退2次 + + far_reservation = { + "future_ts": time.time() + 300, + "prize_value_yuan": 100.0, + "created_ts": time.time() - 100, + "pos_seen": 1, # 距离5个位置 + "room_title": "直播间A", + "room_title_raw": "直播间A", + } + + result = analyser._seek_reservation_room(far_reservation) + if not result or analyser.room_pos != 1: + print("✓ 边界情况处理正确:超出最大回退次数限制") + else: + print("✗ 边界情况处理错误:不应该回退超过限制") + + print("✓ 测试5通过:边界情况处理正确") + + print("\n" + "=" * 70) + print("所有测试完成") + print("=" * 70) + + +if __name__ == "__main__": + test_reservation_backtrack() \ No newline at end of file diff --git a/test_reservation_error_scenarios.py b/test_reservation_error_scenarios.py new file mode 100644 index 0000000..3f21dc9 --- /dev/null +++ b/test_reservation_error_scenarios.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +""" +预约回退错误场景测试脚本 +======================= + +特意制造各种差错,测试预约系统能否正确回退。 + +测试内容: +1. 滑动操作失败:模拟ADB命令执行失败 +2. 位置计算错误:模拟room_pos更新异常 +3. 校验失败重试:模拟校验失败后的重试逻辑 +4. 回退超时:模拟回退操作超时 +5. 映射表不一致:模拟运行时映射表与预约记录不匹配 +6. 最大回退次数限制:测试超出限制后的处理 + +运行方法: + python test_reservation_error_scenarios.py + +预期结果: + 系统能在各种错误情况下正确处理并成功回退 +""" + +import time +import sys +import os +import random + +# 添加项目根目录到路径 +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from douyin.reservation.douyin_reservation_verify import validate_back_to_reservation + + +class MockOperation: + """模拟操作对象""" + + def __init__(self): + self.mock_ocr_result = "美女主播在线" # 默认OCR结果 + + def get_screenshot(self, device_id): + """模拟截图""" + pass + + def analyse_pic_word(self, cut_name, change_color): + """模拟OCR识别""" + return self.mock_ocr_result + + +class MockAnalyser: + """模拟分析器对象,支持各种错误场景""" + + def __init__(self, error_scenario=None): + # 基本配置 + self.reservation_back_verify_enabled = True + self.high_value_fudai_max_swipe_back = 5 # 较小的限制便于测试 + self.reservation_back_total_timeout_seconds = 5.0 + + # 位置信息 + self.room_pos = 5 # 当前在第5个直播间 + self._room_pos_to_title_map = { + 1: ("主播小明直播间", "主播小明直播间"), + 2: ("美女主播在线", "美女主播在线"), + 3: ("游戏直播高手", "游戏直播高手"), + 4: ("音乐现场直播", "音乐现场直播"), + 5: ("科技数码直播", "科技数码直播"), # 当前位置 + 6: ("美食烹饪教学", "美食烹饪教学"), + 7: ("旅游风景直播", "旅游风景直播"), + } + + # 滑动计数器和错误控制 + self.swipe_up_count = 0 + self.swipe_down_count = 0 + self.swipe_failures = 0 + self.position_update_failures = 0 + + # 错误场景控制 + self.error_scenario = error_scenario + self.retry_count = 0 + self.max_retries = 3 + + # 日志 + self.logs = [] + + # Mock operation对象 + self.operation = MockOperation() + self.device_id = "mock_device" + + def _log_kv(self, tag, message, **kwargs): + """记录日志""" + log_entry = f"[{tag}] {message}" + if kwargs: + log_entry += f" {kwargs}" + self.logs.append(log_entry) + print(log_entry) + + def cut_pic(self, x1, y1, x2, y2, filename, desc, y_pianyi=0): + """模拟截图裁剪""" + pass + + def _simulate_swipe_error(self): + """模拟滑动错误""" + if self.error_scenario == "swipe_failure" and random.random() < 0.3: + self.swipe_failures += 1 + print(f"模拟滑动失败 #{self.swipe_failures}") + return False + return True + + def _simulate_position_error(self): + """模拟位置更新错误""" + if self.error_scenario == "position_update_failure" and random.random() < 0.2: + self.position_update_failures += 1 + print(f"模拟位置更新失败 #{self.position_update_failures}") + return False + return True + + def _seek_reservation_room_with_errors(self, item): + """带错误模拟的回退函数""" + target_pos = int(item.get("pos_seen", 0)) + current_pos = self.room_pos + pos_diff = target_pos - current_pos + + print(f"模拟回退:从位置 {current_pos} 到位置 {target_pos} (差值: {pos_diff})") + + if pos_diff == 0: + print("已在目标位置") + return True + + # 计算需要滑动的次数 + if pos_diff < 0: + # 向上回退 + max_steps = min(abs(pos_diff), self.high_value_fudai_max_swipe_back) + direction = "down" + else: + # 向下前进 + max_steps = min(pos_diff, self.high_value_fudai_max_swipe_back) + direction = "up" + + print(f"需要执行 {max_steps} 次向{direction}滑动") + + # 模拟滑动过程,包含错误 + actual_steps = 0 + for i in range(max_steps): + if not self._simulate_swipe_error(): + print(f"滑动失败,停止在步骤 {i+1}") + break + + # 执行滑动 + if direction == "down": + self.swipe_down_count += 1 + if self._simulate_position_error(): + self.room_pos -= 1 + else: + self.swipe_up_count += 1 + if self._simulate_position_error(): + self.room_pos += 1 + + actual_steps += 1 + print(f"步骤 {i+1}: 滑动成功,当前位置 {self.room_pos}") + + # 检查是否到达目标 + if self.room_pos == target_pos: + print(f"成功到达目标位置 {target_pos}") + return True + + # 检查最终位置 + if self.room_pos == target_pos: + print("最终成功到达目标位置") + return True + else: + print(f"回退未完成:当前位置 {self.room_pos}, 目标位置 {target_pos}") + return False + + +def test_error_scenarios(): + """测试各种错误场景""" + + print("=" * 80) + print("预约回退错误场景测试") + print("=" * 80) + + test_cases = [ + { + "name": "正常情况", + "scenario": None, + "description": "无错误情况下的正常回退" + }, + { + "name": "滑动失败", + "scenario": "swipe_failure", + "description": "模拟滑动操作随机失败" + }, + { + "name": "位置更新失败", + "scenario": "position_update_failure", + "description": "模拟位置更新随机失败" + }, + { + "name": "组合错误", + "scenario": "combined_errors", + "description": "同时模拟滑动和位置更新错误" + } + ] + + # 测试预约项 + test_reservation = { + "future_ts": time.time() + 300, # 5分钟后 + "prize_value_yuan": 100.0, + "created_ts": time.time() - 100, + "pos_seen": 2, # 目标位置(距离较远,便于测试错误) + "room_title": "美女主播在线", + "room_title_raw": "美女主播在线", + } + + for i, test_case in enumerate(test_cases, 1): + print(f"\n测试{i}:{test_case['name']}") + print("-" * 50) + print(f"描述:{test_case['description']}") + + # 创建分析器 + analyser = MockAnalyser(test_case["scenario"]) + + # 设置随机种子以便重现 + random.seed(42 + i) + + # 重置状态 + analyser.room_pos = 5 + analyser.swipe_up_count = 0 + analyser.swipe_down_count = 0 + analyser.swipe_failures = 0 + analyser.position_update_failures = 0 + + print(f"初始位置: {analyser.room_pos}") + print(f"目标位置: {test_reservation['pos_seen']}") + + # 执行回退 + start_time = time.time() + result = analyser._seek_reservation_room_with_errors(test_reservation) + end_time = time.time() + + # 输出结果 + print(f"回退结果: {'成功' if result else '失败'}") + print(f"最终位置: {analyser.room_pos}") + print(f"滑动统计: 向上{analyser.swipe_up_count}次, 向下{analyser.swipe_down_count}次") + print(f"错误统计: 滑动失败{analyser.swipe_failures}次, 位置更新失败{analyser.position_update_failures}次") + print(f"执行时间: {end_time - start_time:.2f}秒") + # 验证结果 + if result and analyser.room_pos == test_reservation["pos_seen"]: + print("✓ 测试通过:成功回退到目标位置") + elif not result and analyser.room_pos != test_reservation["pos_seen"]: + print("✓ 测试通过:正确处理了错误情况") + else: + print("✗ 测试失败:结果不符合预期") + + # 测试校验失败重试逻辑 + print("\n测试5:校验失败重试逻辑") + print("-" * 50) + + analyser = MockAnalyser() + analyser.room_pos = 5 # 故意设置错误位置 + + # 模拟校验失败后的重试 + max_retry_attempts = 3 + for attempt in range(max_retry_attempts): + print(f"重试次数 {attempt + 1}/{max_retry_attempts}") + + # 模拟回退操作 + analyser.room_pos = 5 # 重置到错误位置 + analyser._seek_reservation_room_with_errors(test_reservation) + + # 执行校验 + result, detail = validate_back_to_reservation(analyser, test_reservation) + + if result: + print(f"✓ 第{attempt + 1}次重试成功") + break + else: + print(f"✗ 第{attempt + 1}次校验失败,继续重试") + # 在实际系统中,这里会再次尝试回退 + analyser.room_pos = 5 # 模拟重新开始 + + if not result: + print("✗ 重试逻辑测试失败:多次重试后仍未成功") + + # 测试超时情况 + print("\n测试6:超时情况") + print("-" * 50) + + analyser = MockAnalyser() + analyser.reservation_back_total_timeout_seconds = 0.1 # 很短的超时时间 + + start_time = time.time() + # 模拟耗时操作 + time.sleep(0.2) # 超过超时时间 + end_time = time.time() + + if end_time - start_time > analyser.reservation_back_total_timeout_seconds: + print("✓ 超时检测正确:操作时间超过限制") + else: + print("✗ 超时检测失败") + + # 测试映射表不一致 + print("\n测试7:映射表不一致") + print("-" * 50) + + analyser = MockAnalyser() + analyser.room_pos = 2 # 在目标位置 + + # 修改映射表,使当前位置的标题与预约记录不一致 + analyser._room_pos_to_title_map[2] = ("错误的直播间", "错误的直播间") + + # 设置OCR识别结果为错误的标题 + analyser.operation.mock_ocr_result = "错误的直播间" + + result, detail = validate_back_to_reservation(analyser, test_reservation) + + if not result: + print("✓ 映射表不一致检测正确:校验失败") + else: + print("✗ 映射表不一致检测失败:校验错误通过") + + print("\n" + "=" * 80) + print("错误场景测试完成") + print("=" * 80) + + +if __name__ == "__main__": + test_error_scenarios() \ No newline at end of file diff --git a/test_reservation_verify.py b/test_reservation_verify.py new file mode 100644 index 0000000..1a968b0 --- /dev/null +++ b/test_reservation_verify.py @@ -0,0 +1,265 @@ +#!/usr/bin/env python3 +""" +预约回退校验测试脚本 +=================== + +测试预约校验是否能正确回退直播间。 + +测试内容: +1. 基本校验通过:直播间标题匹配时校验通过 +2. 标题不匹配:直播间标题不匹配时校验失败 +3. 校验禁用:当校验开关关闭时直接通过 +4. 福袋详情匹配:预约项与实际福袋详情匹配 +5. 福袋详情不匹配:预约项与实际福袋详情不匹配 +6. 观看任务检测:自动检测并跳过观看任务类型的福袋 +7. 预约队列排序:验证预约队列按时间和价值正确排序 + +运行方法: + python test_reservation_verify.py + +预期结果: + 所有测试用例都应该通过(显示 ✓ 标记) +""" + +import time +import sys +import os + +# 添加项目根目录到路径 +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from douyin.reservation.douyin_reservation_verify import validate_back_to_reservation, match_reservation +from douyin.reservation.douyin_reservation_logic import ReservationItem + + +class MockAnalyser: + """模拟分析器对象""" + + def __init__(self): + self.reservation_back_verify_enabled = True + self._room_pos_to_title_map = {} + self.y_pianyi = 0 + self.logs = [] + + def _log_kv(self, tag, message, **kwargs): + """记录日志""" + log_entry = f"[{tag}] {message}" + if kwargs: + log_entry += f" {kwargs}" + self.logs.append(log_entry) + print(log_entry) + + def get_screenshot(self, device_id, use_service=False): + """模拟截图""" + pass + + +def mock_read_live_room_title_core(analyser, y_pianyi): + """模拟读取直播间标题""" + # 模拟当前在目标直播间 + return "测试直播间", "测试直播间" + + +def test_reservation_verify(): + """测试预约回退校验""" + + print("=" * 60) + print("预约回退校验测试") + print("=" * 60) + + # 创建模拟分析器 + analyser = MockAnalyser() + + # 模拟替换实际的读取函数 + import douyin.fudai.douyin_fudai_detail + original_func = douyin.fudai.douyin_fudai_detail.read_live_room_title_core + douyin.fudai.douyin_fudai_detail.read_live_room_title_core = mock_read_live_room_title_core + + try: + # 测试1:基本校验通过 + print("\n测试1:基本校验通过") + print("-" * 30) + + reservation_item = { + "room_title": "测试直播间", + "room_title_raw": "测试直播间", + "pos_seen": 1, + "content": "测试福袋", + "prize_value_yuan": 100.0, + "future_ts": time.time() + 300, # 5分钟后 + } + + # 设置运行时映射表 + analyser._room_pos_to_title_map = { + 1: ("测试直播间", "测试直播间") + } + + result, detail = validate_back_to_reservation(analyser, reservation_item) + print(f"校验结果: {result}") + print(f"详情: {detail}") + + if result: + print("✓ 测试1通过:校验正确通过") + else: + print("✗ 测试1失败:校验应该通过但失败了") + + # 测试2:标题不匹配 + print("\n测试2:标题不匹配") + print("-" * 30) + + analyser.logs = [] # 清空日志 + + def mock_read_live_room_title_core_wrong(analyser, y_pianyi): + """模拟读取到错误的直播间标题""" + return "完全不同的直播间名称", "完全不同的直播间名称" + + douyin.fudai.douyin_fudai_detail.read_live_room_title_core = mock_read_live_room_title_core_wrong + + result, detail = validate_back_to_reservation(analyser, reservation_item) + print(f"校验结果: {result}") + print(f"详情: {detail}") + + if not result: + print("✓ 测试2通过:校验正确失败") + else: + print("✗ 测试2失败:校验应该失败但通过了") + + # 测试3:校验禁用 + print("\n测试3:校验禁用") + print("-" * 30) + + analyser.logs = [] # 清空日志 + analyser.reservation_back_verify_enabled = False + + result, detail = validate_back_to_reservation(analyser, reservation_item) + print(f"校验结果: {result}") + print(f"详情: {detail}") + + if result: + print("✓ 测试3通过:校验禁用时直接通过") + else: + print("✗ 测试3失败:校验禁用时应该直接通过") + + # 测试4:福袋详情匹配 + print("\n测试4:福袋详情匹配") + print("-" * 30) + + analyser.reservation_back_verify_enabled = True + analyser.logs = [] # 清空日志 + + # 模拟福袋详情 + detail_tuple = ( + "测试福袋", # content + "05:00", # time_text + 100, # participants + 10, # copies + 100.0, # prize_value_yuan + (time.time(), time.time() + 300) # countdown_tuple + ) + + match_result, reason, debug_info = match_reservation(reservation_item, detail_tuple) + print(f"匹配结果: {match_result}") + print(f"原因: {reason}") + print(f"调试信息: {debug_info}") + + if match_result: + print("✓ 测试4通过:福袋详情匹配成功") + else: + print("✗ 测试4失败:福袋详情应该匹配") + + # 测试5:福袋详情不匹配 + print("\n测试5:福袋详情不匹配") + print("-" * 30) + + analyser.logs = [] # 清空日志 + + # 模拟不匹配的福袋详情 + detail_tuple_mismatch = ( + "不同的福袋", # content + "05:00", # time_text + 100, # participants + 10, # copies + 200.0, # prize_value_yuan (不匹配) + (time.time(), time.time() + 600) # countdown_tuple (时间不匹配) + ) + + match_result, reason, debug_info = match_reservation(reservation_item, detail_tuple_mismatch) + print(f"匹配结果: {match_result}") + print(f"原因: {reason}") + print(f"调试信息: {debug_info}") + + # 测试6:观看任务检测 + print("\n测试6:观看任务检测") + print("-" * 30) + + analyser.logs = [] # 清空日志 + + # 模拟观看任务的福袋详情 + watch_task_detail = ( + "观看5分钟领取福袋奖励", # content + "05:00", # time_text + 100, # participants + 10, # copies + 100.0, # prize_value_yuan + (time.time(), time.time() + 300) # countdown_tuple + ) + + match_result, reason, debug_info = match_reservation(reservation_item, watch_task_detail) + print(f"匹配结果: {match_result}") + print(f"原因: {reason}") + print(f"调试信息: {debug_info}") + + if not match_result and reason == "watch_task_detected": + print("✓ 测试6通过:观看任务正确被检测并跳过") + else: + print("✗ 测试6失败:观看任务应该被检测并跳过") + + # 测试7:预约队列排序 + print("\n测试7:预约队列排序") + print("-" * 30) + + from douyin.reservation.douyin_reservation_logic import _sort_reservations_inplace + + reservations = [ + { + "future_ts": time.time() + 600, # 10分钟后 + "prize_value_yuan": 50.0, + "created_ts": time.time() - 100, + }, + { + "future_ts": time.time() + 300, # 5分钟后 + "prize_value_yuan": 100.0, + "created_ts": time.time() - 200, + }, + { + "future_ts": time.time() + 300, # 5分钟后 + "prize_value_yuan": 80.0, + "created_ts": time.time() - 50, + }, + ] + + print("排序前:") + for i, r in enumerate(reservations): + print(f" {i+1}. 时间: {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元") + + _sort_reservations_inplace(reservations) + + print("排序后:") + for i, r in enumerate(reservations): + print(f" {i+1}. 时间: {int((r['future_ts'] - time.time())/60)}分钟后, 价值: {r['prize_value_yuan']}元") + + # 验证排序:时间优先,其次价值 + expected_order = [1, 2, 0] # 索引顺序 + if (reservations[0]["future_ts"] <= reservations[1]["future_ts"] and + reservations[1]["future_ts"] <= reservations[2]["future_ts"]): + print("✓ 测试7通过:预约队列排序正确") + else: + print("✗ 测试7失败:预约队列排序不正确") + + finally: + # 恢复原始函数 + douyin.fudai.douyin_fudai_detail.read_live_room_title_core = original_func + + +if __name__ == "__main__": + test_reservation_verify() \ No newline at end of file