refactor(gui): 抽 refresh_stats 字符串格式化到 stats_formatter (6339 → 5634)
gui_app.py 的 refresh_stats 闭包是 705 行纯字符串构建:把 runner.get_stats() 的字典格式化成多个分段(基本信息/快速汇总/核心统计/跳过/OCR/详情/福袋查找/ 性能/粉丝团/切换/预约/错误/价值/最近福袋/中奖记录)。 抽到 gui/components/stats_formatter.py: - format_stats(stats: Dict) -> List[str] 主入口 - 14 个 _append_* 子段构建器(每段一个,按需追加) - _section_lines(title, body) 标题包装 闭包改为 16 行委托:调 format_stats + 写入 ScrolledText。 新增 32 个单元测试覆盖: - 空 dict / 缺字段时的兜底 - 基本运行状态(uptime / pid / exit_code 各种格式) - 各分段的"有数据 / 无数据"条件 - 关键率计算(打开成功率/点击率/参与成功率/中奖率/跳过率/错误频率) - 边界情况(attend_ok > clicks 检测到已参与,结果未开奖警告,wins 截断到 10 条) 1393 passed (+32)。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
a864f6e23a
commit
230c0d4049
3 files changed
+932
-693
No files matched your search
@@ -0,0 +1,570 @@
|
||||
"""gui/components/stats_formatter - 把 runner.get_stats() 字典格式化成可显示的字符串列表
|
||||
|
||||
从 gui_app.py 的 refresh_stats 闭包抽出来的纯字符串构建逻辑。原本 695 行嵌在
|
||||
main() 里,依赖 stats dict + datetime;这里改成纯函数 format_stats(stats) -> list[str],
|
||||
caller 自己负责往 ScrolledText 写。
|
||||
|
||||
入口:format_stats(stats: dict) -> list[str]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def format_stats(stats: Dict[str, Any]) -> List[str]:
|
||||
"""把 runner.get_stats() 的字典格式化成可显示的多行字符串。"""
|
||||
lines: List[str] = []
|
||||
|
||||
# ===== 基本信息 =====
|
||||
_append_basic_info(lines, stats)
|
||||
counters = stats.get("counters", {}) or {}
|
||||
uptime_seconds = stats.get("uptime_seconds", 0) or 0
|
||||
|
||||
# ===== 快速汇总 =====
|
||||
fudai_seen_unique = counters.get("fudai_seen_unique", 0)
|
||||
fudai_attend_ok_unique = counters.get("fudai_attend_ok_unique", 0)
|
||||
fudai_result_win = counters.get("fudai_result_win", 0)
|
||||
fudai_order_success = counters.get("fudai_order_success", 0)
|
||||
if fudai_seen_unique > 0 or fudai_attend_ok_unique > 0 or fudai_result_win > 0:
|
||||
_append_quick_summary(
|
||||
lines,
|
||||
fudai_seen_unique,
|
||||
fudai_attend_ok_unique,
|
||||
fudai_result_win,
|
||||
fudai_order_success,
|
||||
uptime_seconds,
|
||||
)
|
||||
|
||||
# ===== 核心统计 =====
|
||||
_append_core_stats(lines, counters, uptime_seconds, fudai_seen_unique, fudai_attend_ok_unique)
|
||||
|
||||
# ===== 跳过原因 =====
|
||||
_append_skip_stats(lines, counters, fudai_seen_unique)
|
||||
|
||||
# ===== 高价值预约 / 等待开奖 =====
|
||||
if counters.get("fudai_reserved_high_value", 0) > 0:
|
||||
lines.extend(_section_lines("高价值预约统计", [
|
||||
f"倒计时大于阈值但价值达到高价值阈值,记录预约: {counters['fudai_reserved_high_value']}",
|
||||
]))
|
||||
if counters.get("fudai_waiting_lottery", 0) > 0:
|
||||
lines.extend(_section_lines("等待开奖统计", [
|
||||
f"等待开奖次数: {counters['fudai_waiting_lottery']}",
|
||||
]))
|
||||
|
||||
# ===== 阶段诊断 =====
|
||||
_append_stage_diag_stats(lines, counters)
|
||||
|
||||
# ===== OCR / 详情识别 / 福袋查找 =====
|
||||
_append_ocr_stats(lines, counters)
|
||||
_append_detail_read_stats(lines, counters)
|
||||
_append_fudai_find_stats(lines, counters)
|
||||
_append_perf_stats(lines, counters)
|
||||
|
||||
# ===== 粉丝团 / 直播间切换 =====
|
||||
_append_fansclub_stats(lines, counters)
|
||||
_append_switch_stats(lines, counters, uptime_seconds)
|
||||
|
||||
# ===== 预约相关(详细版)=====
|
||||
_append_reservation_stats(lines, counters)
|
||||
|
||||
# ===== 错误统计(详细版)=====
|
||||
_append_error_stats(lines, counters, uptime_seconds)
|
||||
|
||||
# ===== 价值统计 =====
|
||||
_append_value_stats(lines, stats.get("events", []) or [], fudai_seen_unique)
|
||||
|
||||
# ===== 最近一次福袋信息 =====
|
||||
_append_fudai_last(lines, stats.get("fudai_last", {}) or {})
|
||||
|
||||
# ===== 中奖记录 =====
|
||||
_append_wins(lines, stats.get("wins", []) or [])
|
||||
|
||||
# 兜底:从来没数据时给个占位
|
||||
if not lines:
|
||||
lines.extend(["=" * 60, "统计信息", "=" * 60, "暂无统计数据", "", "提示:请先运行程序以收集统计数据"])
|
||||
|
||||
return lines
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 子段构建器
|
||||
# ============================================================
|
||||
|
||||
def _section_lines(title: str, body: List[str]) -> List[str]:
|
||||
out = ["=" * 60, title, "=" * 60]
|
||||
out.extend(body)
|
||||
out.append("")
|
||||
return out
|
||||
|
||||
|
||||
def _append_basic_info(lines: List[str], stats: Dict[str, Any]) -> None:
|
||||
lines.extend(["=" * 60, "运行状态信息", "=" * 60])
|
||||
lines.append(f"运行状态: {'运行中' if stats.get('running') else '未运行'}")
|
||||
lines.append(f"PID: {stats.get('pid') or '-'}")
|
||||
|
||||
uptime_seconds = stats.get("uptime_seconds", 0) or 0
|
||||
if uptime_seconds > 0:
|
||||
h = uptime_seconds // 3600
|
||||
m = (uptime_seconds % 3600) // 60
|
||||
s = uptime_seconds % 60
|
||||
lines.append(f"运行时长: {h:02d}:{m:02d}:{s:02d}")
|
||||
else:
|
||||
lines.append("运行时长: -")
|
||||
|
||||
last_log_ts = stats.get("last_log_ts")
|
||||
if last_log_ts:
|
||||
lines.append("最近日志时间: " + datetime.fromtimestamp(last_log_ts).strftime("%Y-%m-%d %H:%M:%S"))
|
||||
else:
|
||||
lines.append("最近日志时间: -")
|
||||
|
||||
exit_code = stats.get("exit_code")
|
||||
lines.append(f"退出码: {exit_code if exit_code is not None else '-'}")
|
||||
lines.append("")
|
||||
|
||||
|
||||
def _append_quick_summary(
|
||||
lines: List[str],
|
||||
fudai_seen_unique: int,
|
||||
fudai_attend_ok_unique: int,
|
||||
fudai_result_win: int,
|
||||
fudai_order_success: int,
|
||||
uptime_seconds: int,
|
||||
) -> None:
|
||||
lines.extend(["=" * 60, "快速汇总", "=" * 60])
|
||||
lines.append(f"识别福袋: {fudai_seen_unique} 个")
|
||||
lines.append(f"参与成功: {fudai_attend_ok_unique} 次")
|
||||
lines.append(f"中奖次数: {fudai_result_win} 次")
|
||||
lines.append(f"下单成功: {fudai_order_success} 次")
|
||||
if uptime_seconds > 0:
|
||||
hours = uptime_seconds / 3600.0
|
||||
if hours > 0:
|
||||
lines.append(f"运行效率: {fudai_attend_ok_unique / hours:.1f} 次参与/小时")
|
||||
lines.append("")
|
||||
|
||||
|
||||
def _append_core_stats(
|
||||
lines: List[str],
|
||||
counters: Dict[str, Any],
|
||||
uptime_seconds: int,
|
||||
fudai_seen_unique: int,
|
||||
fudai_attend_ok_unique: int,
|
||||
) -> None:
|
||||
lines.extend(["=" * 60, "核心统计", "=" * 60])
|
||||
|
||||
fudai_open_detail_unique = counters.get("fudai_open_detail_unique", 0)
|
||||
fudai_click_attend_unique = counters.get("fudai_click_attend_unique", 0)
|
||||
fudai_attend_fail = counters.get("fudai_attend_fail", 0)
|
||||
fudai_result_win = counters.get("fudai_result_win", 0)
|
||||
fudai_result_no_win = counters.get("fudai_result_no_win", 0)
|
||||
fudai_order_success = counters.get("fudai_order_success", 0)
|
||||
|
||||
lines.append(f"福袋识别次数: {fudai_seen_unique}")
|
||||
lines.append(f"打开详情: {fudai_open_detail_unique}")
|
||||
if fudai_seen_unique > 0:
|
||||
open_rate = (fudai_open_detail_unique / fudai_seen_unique) * 100
|
||||
lines.append(f" 打开成功率: {open_rate:.1f}%")
|
||||
|
||||
lines.append(f"点击参与: {fudai_click_attend_unique}")
|
||||
if fudai_open_detail_unique > 0:
|
||||
click_rate = (fudai_click_attend_unique / fudai_open_detail_unique) * 100
|
||||
lines.append(f" 点击率: {click_rate:.1f}%")
|
||||
|
||||
lines.append(f"参与成功: {fudai_attend_ok_unique}")
|
||||
lines.append(f"参与失败: {fudai_attend_fail}")
|
||||
if fudai_click_attend_unique > 0:
|
||||
click_attend_success = min(fudai_attend_ok_unique, fudai_click_attend_unique)
|
||||
success_rate = (click_attend_success / fudai_click_attend_unique) * 100
|
||||
lines.append(f" 参与成功率: {success_rate:.1f}%")
|
||||
if fudai_attend_ok_unique > fudai_click_attend_unique:
|
||||
detected_already = fudai_attend_ok_unique - fudai_click_attend_unique
|
||||
lines.append(f" (其中 {detected_already} 次为检测到已参与状态)")
|
||||
elif fudai_attend_ok_unique > 0 or fudai_attend_fail > 0:
|
||||
total_attend = fudai_attend_ok_unique + fudai_attend_fail
|
||||
if total_attend > 0:
|
||||
success_rate = (fudai_attend_ok_unique / total_attend) * 100
|
||||
lines.append(f" 参与成功率: {success_rate:.1f}%")
|
||||
|
||||
lines.append(f"中奖次数: {fudai_result_win}")
|
||||
lines.append(f"未中奖次数: {fudai_result_no_win}")
|
||||
total_results = fudai_result_win + fudai_result_no_win
|
||||
if fudai_attend_ok_unique > 0 and total_results < fudai_attend_ok_unique:
|
||||
pending = fudai_attend_ok_unique - total_results
|
||||
lines.append(f" 注意: 有 {pending} 次参与成功尚未开奖(或开奖结果未识别)")
|
||||
if total_results > 0:
|
||||
win_rate = (fudai_result_win / total_results) * 100
|
||||
lines.append(f" 中奖率: {win_rate:.1f}%")
|
||||
lines.append(f"下单成功: {fudai_order_success}")
|
||||
|
||||
if uptime_seconds > 0:
|
||||
hours = uptime_seconds / 3600.0
|
||||
if hours > 0:
|
||||
lines.append("")
|
||||
lines.append("效率统计(每小时):")
|
||||
if fudai_seen_unique > 0:
|
||||
lines.append(f" 识别福袋: {fudai_seen_unique / hours:.1f} 个/小时")
|
||||
if fudai_attend_ok_unique > 0:
|
||||
lines.append(f" 参与成功: {fudai_attend_ok_unique / hours:.1f} 次/小时")
|
||||
if total_results > 0:
|
||||
lines.append(f" 开奖次数: {total_results / hours:.1f} 次/小时")
|
||||
if fudai_result_win > 0:
|
||||
lines.append(f" 中奖次数: {fudai_result_win / hours:.2f} 次/小时")
|
||||
lines.append("")
|
||||
|
||||
|
||||
def _append_skip_stats(lines: List[str], counters: Dict[str, Any], fudai_seen_unique: int) -> None:
|
||||
skip_stats = [
|
||||
("fudai_skip_value_low", "跳过-价值过低"),
|
||||
("fudai_skip_participants_low", "跳过-人数过少"),
|
||||
("fudai_skip_participants_high", "跳过-人数过多"),
|
||||
("fudai_skip_content", "跳过-内容不理想"),
|
||||
("fudai_skip_countdown_short", "跳过-倒计时太短"),
|
||||
("fudai_skip_countdown_long", "跳过-倒计时太长"),
|
||||
("fudai_skip_watch_required", "跳过-需要看播"),
|
||||
]
|
||||
skip_total = sum(counters.get(k, 0) for k, _ in skip_stats)
|
||||
if skip_total <= 0:
|
||||
return
|
||||
body: List[str] = [f"总跳过次数: {skip_total}"]
|
||||
if fudai_seen_unique > 0:
|
||||
body.append(f"跳过率: {(skip_total / fudai_seen_unique) * 100:.1f}%")
|
||||
body.append("")
|
||||
for key, label in skip_stats:
|
||||
v = counters.get(key, 0)
|
||||
if v > 0:
|
||||
pct = (v / skip_total) * 100 if skip_total > 0 else 0
|
||||
body.append(f" {label}: {v} ({pct:.1f}%)")
|
||||
lines.extend(_section_lines("跳过原因统计", body))
|
||||
|
||||
|
||||
def _append_stage_diag_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||||
complete = counters.get("stage_diagnosis_complete", 0)
|
||||
failed = counters.get("stage_diagnosis_failed", 0)
|
||||
if complete <= 0 and failed <= 0:
|
||||
return
|
||||
body = [f"诊断完成: {complete}", f"诊断失败: {failed}"]
|
||||
if complete > 0:
|
||||
success_rate = (complete / (complete + failed)) * 100
|
||||
body.append(f"成功率: {success_rate:.1f}%")
|
||||
lines.extend(_section_lines("阶段诊断统计", body))
|
||||
|
||||
|
||||
def _append_ocr_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||||
attempt = counters.get("ocr_attempt", 0)
|
||||
success = counters.get("ocr_success", 0)
|
||||
failed = counters.get("ocr_failed", 0)
|
||||
if attempt <= 0:
|
||||
return
|
||||
body = [f"OCR尝试次数: {attempt}", f"OCR成功次数: {success}", f"OCR失败次数: {failed}"]
|
||||
total_results = success + failed
|
||||
if total_results < attempt:
|
||||
body.append(f" 注意: 有 {attempt - total_results} 次尝试未记录结果(可能日志格式不匹配)")
|
||||
body.append(f"OCR成功率: {(success / attempt) * 100:.1f}%")
|
||||
lines.extend(_section_lines("OCR识别统计", body))
|
||||
|
||||
|
||||
def _append_detail_read_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||||
attempt = counters.get("fudai_detail_read_attempt", 0)
|
||||
if attempt <= 0:
|
||||
return
|
||||
success = counters.get("fudai_detail_read_success", 0)
|
||||
failed = counters.get("fudai_detail_read_failed", 0)
|
||||
body = [f"详情识别尝试: {attempt}", f"详情识别成功: {success}", f"详情识别失败: {failed}"]
|
||||
total = success + failed
|
||||
if total < attempt:
|
||||
body.append(f" 注意: 有 {attempt - total} 次尝试未记录结果(可能日志格式不匹配)")
|
||||
body.append(f"详情识别成功率: {(success / attempt) * 100:.1f}%")
|
||||
lines.extend(_section_lines("详情识别统计", body))
|
||||
|
||||
|
||||
def _append_fudai_find_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||||
success = counters.get("fudai_find_success", 0)
|
||||
not_found = counters.get("fudai_find_not_found", 0)
|
||||
timeout = counters.get("fudai_find_timeout", 0)
|
||||
if success <= 0 and not_found <= 0 and timeout <= 0:
|
||||
return
|
||||
body = [f"查找成功: {success}", f"未找到: {not_found}", f"等待超时: {timeout}"]
|
||||
lines.extend(_section_lines("福袋查找统计", body))
|
||||
|
||||
|
||||
def _append_perf_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||||
slow = counters.get("slow_operation", 0)
|
||||
if slow > 0:
|
||||
lines.extend(_section_lines("性能统计", [f"慢操作(>5秒)次数: {slow}"]))
|
||||
|
||||
|
||||
def _append_fansclub_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||||
items = [
|
||||
("fansclub_required", "需要粉丝团"),
|
||||
("fansclub_manual_needed", "需手动加入"),
|
||||
("fansclub_unresolved", "未解决"),
|
||||
]
|
||||
total = sum(counters.get(k, 0) for k, _ in items)
|
||||
if total <= 0:
|
||||
return
|
||||
body: List[str] = []
|
||||
for key, label in items:
|
||||
v = counters.get(key, 0)
|
||||
if v > 0:
|
||||
pct = (v / total) * 100 if total > 0 else 0
|
||||
body.append(f" {label}: {v} ({pct:.1f}%)")
|
||||
lines.extend(_section_lines("粉丝团相关统计", body))
|
||||
|
||||
|
||||
def _append_switch_stats(lines: List[str], counters: Dict[str, Any], uptime_seconds: int) -> None:
|
||||
total = counters.get("switch_room", 0)
|
||||
if total <= 0:
|
||||
return
|
||||
body = [f"总切换次数: {total}"]
|
||||
if uptime_seconds > 0:
|
||||
hours = uptime_seconds / 3600.0
|
||||
if hours > 0:
|
||||
body.append(f"切换频率: {total / hours:.1f} 次/小时")
|
||||
body.append("")
|
||||
reasons = [
|
||||
("switch_room_no_fudai", "无福袋"),
|
||||
("switch_room_participants", "人数不符合"),
|
||||
("switch_room_value", "价值不符合"),
|
||||
("switch_room_content", "内容不符合"),
|
||||
("switch_room_countdown", "倒计时不符合"),
|
||||
("switch_room_attend_fail", "参与失败"),
|
||||
]
|
||||
for key, label in reasons:
|
||||
v = counters.get(key, 0)
|
||||
if v > 0:
|
||||
pct = (v / total) * 100 if total > 0 else 0
|
||||
body.append(f" {label}: {v} ({pct:.1f}%)")
|
||||
lines.extend(_section_lines("直播间切换统计", body))
|
||||
|
||||
|
||||
def _append_reservation_stats(lines: List[str], counters: Dict[str, Any]) -> None:
|
||||
keys = [
|
||||
"reservation_recorded",
|
||||
"reservation_window_entered",
|
||||
"reservation_back_success",
|
||||
"reservation_back_verify_ok",
|
||||
"reservation_back_verify_fail",
|
||||
"reservation_window_not_reached",
|
||||
"reservation_expired",
|
||||
"reservation_queue_empty",
|
||||
"reservation_locked",
|
||||
"reservation_back_to_first",
|
||||
"reservation_queue_full_wait",
|
||||
"reservation_drop_low_value",
|
||||
"reservation_clear",
|
||||
"reservation_back_direct_attend",
|
||||
"reservation_queue_full_back_attend",
|
||||
"reservation_duplicate_detected",
|
||||
"reservation_back_operation",
|
||||
]
|
||||
values = {k: counters.get(k, 0) for k in keys}
|
||||
total = sum(values.values())
|
||||
if total <= 0 and values["reservation_recorded"] <= 0:
|
||||
return
|
||||
|
||||
body: List[str] = []
|
||||
if values["reservation_recorded"] > 0:
|
||||
body.append(f"记录预约总数: {values['reservation_recorded']}")
|
||||
if values["reservation_back_success"] > 0:
|
||||
body.append(f"成功回退到预约直播间: {values['reservation_back_success']}")
|
||||
|
||||
verify_total = values["reservation_back_verify_ok"] + values["reservation_back_verify_fail"]
|
||||
if verify_total > 0:
|
||||
verify_rate = (values["reservation_back_verify_ok"] / verify_total) * 100
|
||||
body.append(
|
||||
f"回退校验: {values['reservation_back_verify_ok']} 成功 / "
|
||||
f"{values['reservation_back_verify_fail']} 失败 (成功率: {verify_rate:.1f}%)"
|
||||
)
|
||||
|
||||
if values["reservation_window_entered"] > 0:
|
||||
body.append(f"进入预约参与窗口: {values['reservation_window_entered']}")
|
||||
if values["reservation_window_not_reached"] > 0:
|
||||
body.append(f"时间窗口未到(跳过): {values['reservation_window_not_reached']}")
|
||||
if values["reservation_expired"] > 0:
|
||||
body.append(f"过期预约(已清理): {values['reservation_expired']}")
|
||||
if values["reservation_locked"] > 0:
|
||||
body.append(f"锁定期未结束(跳过): {values['reservation_locked']}")
|
||||
if values["reservation_queue_empty"] > 0:
|
||||
body.append(f"预约队列为空(检查次数): {values['reservation_queue_empty']}")
|
||||
if values["reservation_queue_full_wait"] > 0:
|
||||
body.append(f"队列已满等待: {values['reservation_queue_full_wait']}")
|
||||
if values["reservation_back_to_first"] > 0:
|
||||
body.append(f"回退到第一个直播间: {values['reservation_back_to_first']}")
|
||||
if values["reservation_drop_low_value"] > 0:
|
||||
body.append(f"丢弃低价值预约: {values['reservation_drop_low_value']}")
|
||||
if values["reservation_clear"] > 0:
|
||||
body.append(f"清空预约队列: {values['reservation_clear']}")
|
||||
if values["reservation_duplicate_detected"] > 0:
|
||||
body.append(f"检测到重复预约: {values['reservation_duplicate_detected']}")
|
||||
if values["reservation_back_direct_attend"] > 0:
|
||||
body.append(f"回退后直接参与: {values['reservation_back_direct_attend']}")
|
||||
if values["reservation_queue_full_back_attend"] > 0:
|
||||
body.append(f"队列满回退后参与: {values['reservation_queue_full_back_attend']}")
|
||||
if values["reservation_back_operation"] > 0:
|
||||
body.append(f"回退操作次数: {values['reservation_back_operation']}")
|
||||
|
||||
if values["reservation_recorded"] > 0 and values["reservation_back_success"] > 0:
|
||||
back_rate = (values["reservation_back_success"] / values["reservation_recorded"]) * 100
|
||||
body.append(
|
||||
f"预约回退成功率: {back_rate:.1f}% "
|
||||
f"({values['reservation_back_success']}/{values['reservation_recorded']})"
|
||||
)
|
||||
|
||||
lines.extend(_section_lines("预约相关统计(详细)", body))
|
||||
|
||||
|
||||
def _append_error_stats(lines: List[str], counters: Dict[str, Any], uptime_seconds: int) -> None:
|
||||
keys = [
|
||||
"error_total", "error_unbound_local", "error_attribute", "error_key",
|
||||
"error_value", "error_type", "error_timeout", "error_connection",
|
||||
"error_ocr", "error_screenshot", "error_detection", "error_stage_diagnosis",
|
||||
"error_read_detail", "error_config_load", "error_state_file",
|
||||
"error_live_room_detect", "error_fudai_find", "fudai_open_error",
|
||||
"fudai_open_error_too_many",
|
||||
]
|
||||
v = {k: counters.get(k, 0) for k in keys}
|
||||
total_all = sum(v.values())
|
||||
if total_all <= 0:
|
||||
return
|
||||
|
||||
body: List[str] = []
|
||||
if v["error_total"] > 0:
|
||||
body.append(f"总错误数: {v['error_total']}")
|
||||
|
||||
fudai_errors = v["fudai_open_error"] + v["fudai_open_error_too_many"]
|
||||
if fudai_errors > 0:
|
||||
body.extend(["", "福袋相关错误:"])
|
||||
if v["fudai_open_error"] > 0:
|
||||
body.append(f" 打开福袋异常: {v['fudai_open_error']}")
|
||||
if v["fudai_open_error_too_many"] > 0:
|
||||
body.append(f" 打开失败次数过多: {v['fudai_open_error_too_many']}")
|
||||
|
||||
python_errors = v["error_unbound_local"] + v["error_attribute"] + v["error_key"] + v["error_value"] + v["error_type"]
|
||||
if python_errors > 0:
|
||||
body.extend(["", "Python异常类型:"])
|
||||
if v["error_unbound_local"] > 0:
|
||||
body.append(f" UnboundLocalError: {v['error_unbound_local']}")
|
||||
if v["error_attribute"] > 0:
|
||||
body.append(f" AttributeError: {v['error_attribute']}")
|
||||
if v["error_key"] > 0:
|
||||
body.append(f" KeyError: {v['error_key']}")
|
||||
if v["error_value"] > 0:
|
||||
body.append(f" ValueError: {v['error_value']}")
|
||||
if v["error_type"] > 0:
|
||||
body.append(f" TypeError: {v['error_type']}")
|
||||
|
||||
module_errors = (
|
||||
v["error_ocr"] + v["error_screenshot"] + v["error_detection"]
|
||||
+ v["error_stage_diagnosis"] + v["error_read_detail"] + v["error_config_load"]
|
||||
+ v["error_state_file"] + v["error_live_room_detect"] + v["error_fudai_find"]
|
||||
)
|
||||
if module_errors > 0:
|
||||
body.extend(["", "功能模块错误:"])
|
||||
for key, label in [
|
||||
("error_ocr", "OCR识别错误"),
|
||||
("error_screenshot", "截图错误"),
|
||||
("error_detection", "识别错误"),
|
||||
("error_stage_diagnosis", "阶段诊断错误"),
|
||||
("error_read_detail", "读取详情错误"),
|
||||
("error_config_load", "配置加载错误"),
|
||||
("error_state_file", "状态文件错误"),
|
||||
("error_live_room_detect", "直播间检测错误"),
|
||||
("error_fudai_find", "福袋查找错误"),
|
||||
]:
|
||||
if v[key] > 0:
|
||||
body.append(f" {label}: {v[key]}")
|
||||
|
||||
network_errors = v["error_timeout"] + v["error_connection"]
|
||||
if network_errors > 0:
|
||||
body.extend(["", "网络和超时错误:"])
|
||||
if v["error_timeout"] > 0:
|
||||
body.append(f" 超时错误: {v['error_timeout']}")
|
||||
if v["error_connection"] > 0:
|
||||
body.append(f" 连接错误: {v['error_connection']}")
|
||||
|
||||
if uptime_seconds > 0 and total_all > 0:
|
||||
hours = uptime_seconds / 3600.0
|
||||
if hours > 0:
|
||||
body.extend(["", f"错误频率: {total_all / hours:.2f} 次/小时"])
|
||||
|
||||
lines.extend(_section_lines("错误统计(详细)", body))
|
||||
|
||||
|
||||
def _append_value_stats(lines: List[str], events: List[Dict[str, Any]], fudai_seen_unique: int) -> None:
|
||||
prize_values: List[float] = []
|
||||
for event in events:
|
||||
meta = event.get("meta", {}) or {}
|
||||
if "prize_value_yuan" in meta and meta["prize_value_yuan"] is not None:
|
||||
try:
|
||||
prize_values.append(float(meta["prize_value_yuan"]))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if not prize_values:
|
||||
return
|
||||
|
||||
total_value = sum(prize_values)
|
||||
avg_value = total_value / len(prize_values)
|
||||
body = [f"识别到的福袋总数: {len(prize_values)}"]
|
||||
if fudai_seen_unique > len(prize_values):
|
||||
body.append(
|
||||
f" (总识别次数: {fudai_seen_unique},其中 {len(prize_values)} 个成功识别到价值)"
|
||||
)
|
||||
body.extend([
|
||||
f"总价值: {total_value:.2f} 元",
|
||||
f"平均价值: {avg_value:.2f} 元",
|
||||
f"最高价值: {max(prize_values):.2f} 元",
|
||||
f"最低价值: {min(prize_values):.2f} 元",
|
||||
"",
|
||||
"价值分布:",
|
||||
])
|
||||
high = sum(1 for x in prize_values if x >= 500)
|
||||
mid = sum(1 for x in prize_values if 100 <= x < 500)
|
||||
low = sum(1 for x in prize_values if x < 100)
|
||||
body.append(f" 高价值(≥500元): {high} ({high/len(prize_values)*100:.1f}%)")
|
||||
body.append(f" 中价值(100-500元): {mid} ({mid/len(prize_values)*100:.1f}%)")
|
||||
body.append(f" 低价值(<100元): {low} ({low/len(prize_values)*100:.1f}%)")
|
||||
lines.extend(_section_lines("价值统计", body))
|
||||
|
||||
|
||||
def _append_fudai_last(lines: List[str], fudai_last: Dict[str, Any]) -> None:
|
||||
if not (fudai_last.get("content") or fudai_last.get("countdown")):
|
||||
return
|
||||
body = [
|
||||
f"内容: {fudai_last.get('content') or '-'}",
|
||||
f"倒计时: {fudai_last.get('countdown') or '-'}",
|
||||
]
|
||||
participants = fudai_last.get("participants")
|
||||
copies = fudai_last.get("copies")
|
||||
if participants is not None and copies is not None:
|
||||
body.append(f"参与人数/份数: {participants} / {copies}")
|
||||
if participants > 0 and copies > 0:
|
||||
ratio = participants / copies
|
||||
body.append(f" 中奖概率: {1/ratio*100:.2f}% (1/{ratio:.1f})")
|
||||
prize_value = fudai_last.get("prize_value_yuan")
|
||||
if prize_value is not None:
|
||||
body.append(f"奖品价值: {prize_value} 元")
|
||||
updated_ts = fudai_last.get("updated_ts")
|
||||
if updated_ts:
|
||||
body.append("更新时间: " + datetime.fromtimestamp(updated_ts).strftime("%Y-%m-%d %H:%M:%S"))
|
||||
lines.extend(_section_lines("最近一次福袋信息", body))
|
||||
|
||||
|
||||
def _append_wins(lines: List[str], wins: List[Dict[str, Any]]) -> None:
|
||||
if not wins:
|
||||
return
|
||||
body: List[str] = []
|
||||
for i, win in enumerate(wins[-10:], 1):
|
||||
ts = win.get("ts", 0) or 0
|
||||
dt_str = datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") if ts else "-"
|
||||
body.append(f"\n[{i}] 时间: {dt_str}")
|
||||
if win.get("content"):
|
||||
body.append(f" 内容: {win.get('content')}")
|
||||
if win.get("prize_value_yuan"):
|
||||
body.append(f" 价值: {win.get('prize_value_yuan')} 元")
|
||||
if win.get("participants") and win.get("copies"):
|
||||
body.append(f" 人数/份数: {win.get('participants')} / {win.get('copies')}")
|
||||
lines.extend([
|
||||
"=" * 60,
|
||||
f"最近中奖记录(显示最近 {len(wins)} 条)",
|
||||
"=" * 60,
|
||||
] + body)
|
||||
+3
-693
@@ -4721,702 +4721,12 @@ def main():
|
||||
pass
|
||||
|
||||
def refresh_stats():
|
||||
"""委托给 gui/components/stats_formatter.format_stats(纯字符串构建)。"""
|
||||
try:
|
||||
from gui.components.stats_formatter import format_stats
|
||||
stats = runner.get_stats()
|
||||
lines = []
|
||||
|
||||
# 基本信息
|
||||
lines.append("=" * 60)
|
||||
lines.append("运行状态信息")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"运行状态: {'运行中' if stats.get('running') else '未运行'}")
|
||||
lines.append(f"PID: {stats.get('pid') or '-'}")
|
||||
|
||||
uptime_seconds = stats.get("uptime_seconds", 0)
|
||||
if uptime_seconds > 0:
|
||||
hours = uptime_seconds // 3600
|
||||
minutes = (uptime_seconds % 3600) // 60
|
||||
seconds = uptime_seconds % 60
|
||||
lines.append(f"运行时长: {hours:02d}:{minutes:02d}:{seconds:02d}")
|
||||
else:
|
||||
lines.append("运行时长: -")
|
||||
|
||||
last_log_ts = stats.get("last_log_ts")
|
||||
if last_log_ts:
|
||||
dt = datetime.fromtimestamp(last_log_ts)
|
||||
lines.append("最近日志时间: " + dt.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
else:
|
||||
lines.append("最近日志时间: -")
|
||||
|
||||
exit_code = stats.get("exit_code")
|
||||
lines.append(f"退出码: {exit_code if exit_code is not None else '-'}")
|
||||
lines.append("")
|
||||
|
||||
# 计数器统计
|
||||
counters = stats.get("counters", {})
|
||||
|
||||
# 快速汇总(关键指标)
|
||||
fudai_seen = counters.get("fudai_seen", 0)
|
||||
fudai_seen_unique = counters.get("fudai_seen_unique", 0)
|
||||
fudai_attend_ok = counters.get("fudai_attend_ok", 0)
|
||||
fudai_attend_ok_unique = counters.get("fudai_attend_ok_unique", 0)
|
||||
fudai_result_win = counters.get("fudai_result_win", 0)
|
||||
fudai_order_success = counters.get("fudai_order_success", 0)
|
||||
|
||||
if (
|
||||
fudai_seen_unique > 0
|
||||
or fudai_attend_ok_unique > 0
|
||||
or fudai_result_win > 0
|
||||
):
|
||||
lines.append("=" * 60)
|
||||
lines.append("快速汇总")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"识别福袋: {fudai_seen_unique} 个")
|
||||
lines.append(f"参与成功: {fudai_attend_ok_unique} 次")
|
||||
lines.append(f"中奖次数: {fudai_result_win} 次")
|
||||
lines.append(f"下单成功: {fudai_order_success} 次")
|
||||
if uptime_seconds > 0:
|
||||
hours = uptime_seconds / 3600.0
|
||||
if hours > 0:
|
||||
lines.append(
|
||||
f"运行效率: {fudai_attend_ok_unique / hours:.1f} 次参与/小时"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
# 核心统计(总是显示,即使数据为0)
|
||||
lines.append("=" * 60)
|
||||
lines.append("核心统计")
|
||||
lines.append("=" * 60)
|
||||
|
||||
# 福袋相关核心指标(重新获取,避免重复定义)
|
||||
fudai_open_detail = counters.get("fudai_open_detail", 0)
|
||||
fudai_open_detail_unique = counters.get("fudai_open_detail_unique", 0)
|
||||
fudai_click_attend = counters.get("fudai_click_attend", 0)
|
||||
fudai_click_attend_unique = counters.get("fudai_click_attend_unique", 0)
|
||||
fudai_attend_ok = counters.get("fudai_attend_ok", 0)
|
||||
fudai_attend_fail = counters.get("fudai_attend_fail", 0)
|
||||
fudai_result_win = counters.get("fudai_result_win", 0)
|
||||
fudai_result_no_win = counters.get("fudai_result_no_win", 0)
|
||||
fudai_order_success = counters.get("fudai_order_success", 0)
|
||||
|
||||
lines.append(f"福袋识别次数: {fudai_seen_unique}")
|
||||
lines.append(f"打开详情: {fudai_open_detail_unique}")
|
||||
if fudai_seen_unique > 0:
|
||||
open_rate = (fudai_open_detail_unique / fudai_seen_unique) * 100
|
||||
lines.append(f" 打开成功率: {open_rate:.1f}%")
|
||||
|
||||
lines.append(f"点击参与: {fudai_click_attend_unique}")
|
||||
if fudai_open_detail_unique > 0:
|
||||
click_rate = (
|
||||
fudai_click_attend_unique / fudai_open_detail_unique
|
||||
) * 100
|
||||
lines.append(f" 点击率: {click_rate:.1f}%")
|
||||
|
||||
lines.append(f"参与成功: {fudai_attend_ok_unique}")
|
||||
lines.append(f"参与失败: {fudai_attend_fail}")
|
||||
# 参与成功率应该基于点击参与次数来计算
|
||||
# 因为参与成功可能包括"检测到已参与"的情况(没有点击)
|
||||
if fudai_click_attend_unique > 0:
|
||||
# 通过点击参与成功的次数(不超过点击参与次数)
|
||||
click_attend_success = min(
|
||||
fudai_attend_ok_unique, fudai_click_attend_unique
|
||||
)
|
||||
success_rate = (click_attend_success / fudai_click_attend_unique) * 100
|
||||
lines.append(f" 参与成功率: {success_rate:.1f}%")
|
||||
# 如果参与成功 > 点击参与,说明有检测到已参与的情况
|
||||
if fudai_attend_ok_unique > fudai_click_attend_unique:
|
||||
detected_already_attended = (
|
||||
fudai_attend_ok_unique - fudai_click_attend_unique
|
||||
)
|
||||
lines.append(
|
||||
f" (其中 {detected_already_attended} 次为检测到已参与状态)"
|
||||
)
|
||||
elif fudai_attend_ok_unique > 0 or fudai_attend_fail > 0:
|
||||
# 如果没有点击参与但有参与结果,使用原来的计算方式
|
||||
total_attend = fudai_attend_ok_unique + fudai_attend_fail
|
||||
if total_attend > 0:
|
||||
success_rate = (fudai_attend_ok_unique / total_attend) * 100
|
||||
lines.append(f" 参与成功率: {success_rate:.1f}%")
|
||||
|
||||
lines.append(f"中奖次数: {fudai_result_win}")
|
||||
lines.append(f"未中奖次数: {fudai_result_no_win}")
|
||||
total_results = fudai_result_win + fudai_result_no_win
|
||||
# 检查数据一致性:参与成功次数应该 >= 开奖结果次数
|
||||
if fudai_attend_ok_unique > 0 and total_results < fudai_attend_ok_unique:
|
||||
pending_results = fudai_attend_ok_unique - total_results
|
||||
lines.append(
|
||||
f" 注意: 有 {pending_results} 次参与成功尚未开奖(或开奖结果未识别)"
|
||||
)
|
||||
if total_results > 0:
|
||||
win_rate = (fudai_result_win / total_results) * 100
|
||||
lines.append(f" 中奖率: {win_rate:.1f}%")
|
||||
|
||||
lines.append(f"下单成功: {fudai_order_success}")
|
||||
|
||||
# 效率统计
|
||||
if uptime_seconds > 0:
|
||||
hours = uptime_seconds / 3600.0
|
||||
if hours > 0:
|
||||
lines.append("")
|
||||
lines.append("效率统计(每小时):")
|
||||
if fudai_seen_unique > 0:
|
||||
lines.append(
|
||||
f" 识别福袋: {fudai_seen_unique / hours:.1f} 个/小时"
|
||||
)
|
||||
if fudai_attend_ok_unique > 0:
|
||||
lines.append(
|
||||
f" 参与成功: {fudai_attend_ok_unique / hours:.1f} 次/小时"
|
||||
)
|
||||
if total_results > 0:
|
||||
lines.append(f" 开奖次数: {total_results / hours:.1f} 次/小时")
|
||||
if fudai_result_win > 0:
|
||||
lines.append(
|
||||
f" 中奖次数: {fudai_result_win / hours:.2f} 次/小时"
|
||||
)
|
||||
|
||||
lines.append("")
|
||||
|
||||
# 跳过原因统计
|
||||
skip_stats = [
|
||||
("fudai_skip_value_low", "跳过-价值过低"),
|
||||
("fudai_skip_participants_low", "跳过-人数过少"),
|
||||
("fudai_skip_participants_high", "跳过-人数过多"),
|
||||
("fudai_skip_content", "跳过-内容不理想"),
|
||||
("fudai_skip_countdown_short", "跳过-倒计时太短"),
|
||||
("fudai_skip_countdown_long", "跳过-倒计时太长"),
|
||||
("fudai_skip_watch_required", "跳过-需要看播"),
|
||||
]
|
||||
# 高价值预约统计
|
||||
fudai_reserved_high_value = counters.get("fudai_reserved_high_value", 0)
|
||||
if fudai_reserved_high_value > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("高价值预约统计")
|
||||
lines.append("=" * 60)
|
||||
lines.append(
|
||||
f"倒计时大于阈值但价值达到高价值阈值,记录预约: {fudai_reserved_high_value}"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
# 等待开奖统计
|
||||
fudai_waiting_lottery = counters.get("fudai_waiting_lottery", 0)
|
||||
if fudai_waiting_lottery > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("等待开奖统计")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"等待开奖次数: {fudai_waiting_lottery}")
|
||||
lines.append("")
|
||||
|
||||
# 阶段诊断统计
|
||||
stage_diagnosis_complete = counters.get("stage_diagnosis_complete", 0)
|
||||
stage_diagnosis_failed = counters.get("stage_diagnosis_failed", 0)
|
||||
if stage_diagnosis_complete > 0 or stage_diagnosis_failed > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("阶段诊断统计")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"诊断完成: {stage_diagnosis_complete}")
|
||||
lines.append(f"诊断失败: {stage_diagnosis_failed}")
|
||||
if stage_diagnosis_complete > 0:
|
||||
success_rate = (
|
||||
stage_diagnosis_complete
|
||||
/ (stage_diagnosis_complete + stage_diagnosis_failed)
|
||||
) * 100
|
||||
lines.append(f"成功率: {success_rate:.1f}%")
|
||||
lines.append("")
|
||||
|
||||
# OCR识别统计
|
||||
ocr_attempt = counters.get("ocr_attempt", 0)
|
||||
ocr_success = counters.get("ocr_success", 0)
|
||||
ocr_failed = counters.get("ocr_failed", 0)
|
||||
if ocr_attempt > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("OCR识别统计")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"OCR尝试次数: {ocr_attempt}")
|
||||
lines.append(f"OCR成功次数: {ocr_success}")
|
||||
lines.append(f"OCR失败次数: {ocr_failed}")
|
||||
total_ocr_results = ocr_success + ocr_failed
|
||||
if total_ocr_results < ocr_attempt:
|
||||
lines.append(
|
||||
f" 注意: 有 {ocr_attempt - total_ocr_results} 次尝试未记录结果(可能日志格式不匹配)"
|
||||
)
|
||||
if ocr_attempt > 0:
|
||||
ocr_rate = (ocr_success / ocr_attempt) * 100
|
||||
lines.append(f"OCR成功率: {ocr_rate:.1f}%")
|
||||
lines.append("")
|
||||
|
||||
# 详情识别统计
|
||||
fudai_detail_read_attempt = counters.get("fudai_detail_read_attempt", 0)
|
||||
fudai_detail_read_success = counters.get("fudai_detail_read_success", 0)
|
||||
fudai_detail_read_failed = counters.get("fudai_detail_read_failed", 0)
|
||||
if fudai_detail_read_attempt > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("详情识别统计")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"详情识别尝试: {fudai_detail_read_attempt}")
|
||||
lines.append(f"详情识别成功: {fudai_detail_read_success}")
|
||||
lines.append(f"详情识别失败: {fudai_detail_read_failed}")
|
||||
total_detail_results = (
|
||||
fudai_detail_read_success + fudai_detail_read_failed
|
||||
)
|
||||
if total_detail_results < fudai_detail_read_attempt:
|
||||
lines.append(
|
||||
f" 注意: 有 {fudai_detail_read_attempt - total_detail_results} 次尝试未记录结果(可能日志格式不匹配)"
|
||||
)
|
||||
if fudai_detail_read_attempt > 0:
|
||||
detail_rate = (
|
||||
fudai_detail_read_success / fudai_detail_read_attempt
|
||||
) * 100
|
||||
lines.append(f"详情识别成功率: {detail_rate:.1f}%")
|
||||
lines.append("")
|
||||
|
||||
# 福袋查找统计
|
||||
fudai_find_success = counters.get("fudai_find_success", 0)
|
||||
fudai_find_not_found = counters.get("fudai_find_not_found", 0)
|
||||
fudai_find_timeout = counters.get("fudai_find_timeout", 0)
|
||||
if (
|
||||
fudai_find_success > 0
|
||||
or fudai_find_not_found > 0
|
||||
or fudai_find_timeout > 0
|
||||
):
|
||||
lines.append("=" * 60)
|
||||
lines.append("福袋查找统计")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"查找成功: {fudai_find_success}")
|
||||
lines.append(f"未找到: {fudai_find_not_found}")
|
||||
lines.append(f"等待超时: {fudai_find_timeout}")
|
||||
lines.append("")
|
||||
|
||||
# 性能统计(慢操作)
|
||||
slow_operation = counters.get("slow_operation", 0)
|
||||
if slow_operation > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("性能统计")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"慢操作(>5秒)次数: {slow_operation}")
|
||||
lines.append("")
|
||||
skip_total = sum(counters.get(key, 0) for key, _ in skip_stats)
|
||||
if skip_total > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("跳过原因统计")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"总跳过次数: {skip_total}")
|
||||
if fudai_seen_unique > 0:
|
||||
skip_rate = (skip_total / fudai_seen_unique) * 100
|
||||
lines.append(f"跳过率: {skip_rate:.1f}%")
|
||||
lines.append("")
|
||||
for key, label in skip_stats:
|
||||
val = counters.get(key, 0)
|
||||
if val > 0:
|
||||
percentage = (val / skip_total) * 100 if skip_total > 0 else 0
|
||||
lines.append(f" {label}: {val} ({percentage:.1f}%)")
|
||||
lines.append("")
|
||||
|
||||
# 粉丝团统计
|
||||
fansclub_stats = [
|
||||
("fansclub_required", "需要粉丝团"),
|
||||
("fansclub_manual_needed", "需手动加入"),
|
||||
("fansclub_unresolved", "未解决"),
|
||||
]
|
||||
fansclub_total = sum(counters.get(key, 0) for key, _ in fansclub_stats)
|
||||
if fansclub_total > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("粉丝团相关统计")
|
||||
lines.append("=" * 60)
|
||||
for key, label in fansclub_stats:
|
||||
val = counters.get(key, 0)
|
||||
if val > 0:
|
||||
percentage = (
|
||||
(val / fansclub_total) * 100 if fansclub_total > 0 else 0
|
||||
)
|
||||
lines.append(f" {label}: {val} ({percentage:.1f}%)")
|
||||
lines.append("")
|
||||
|
||||
# 直播间切换统计
|
||||
switch_val = counters.get("switch_room", 0)
|
||||
if switch_val > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("直播间切换统计")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"总切换次数: {switch_val}")
|
||||
if uptime_seconds > 0:
|
||||
hours = uptime_seconds / 3600.0
|
||||
if hours > 0:
|
||||
lines.append(f"切换频率: {switch_val / hours:.1f} 次/小时")
|
||||
lines.append("")
|
||||
switch_reasons = [
|
||||
("switch_room_no_fudai", "无福袋"),
|
||||
("switch_room_participants", "人数不符合"),
|
||||
("switch_room_value", "价值不符合"),
|
||||
("switch_room_content", "内容不符合"),
|
||||
("switch_room_countdown", "倒计时不符合"),
|
||||
("switch_room_attend_fail", "参与失败"),
|
||||
]
|
||||
for key, label in switch_reasons:
|
||||
val = counters.get(key, 0)
|
||||
if val > 0:
|
||||
percentage = (val / switch_val) * 100 if switch_val > 0 else 0
|
||||
lines.append(f" {label}: {val} ({percentage:.1f}%)")
|
||||
lines.append("")
|
||||
|
||||
# 预约相关统计(详细版)
|
||||
reservation_recorded = counters.get("reservation_recorded", 0)
|
||||
reservation_window_entered = counters.get("reservation_window_entered", 0)
|
||||
reservation_back_success = counters.get("reservation_back_success", 0)
|
||||
reservation_back_verify_ok = counters.get("reservation_back_verify_ok", 0)
|
||||
reservation_back_verify_fail = counters.get(
|
||||
"reservation_back_verify_fail", 0
|
||||
)
|
||||
reservation_window_not_reached = counters.get(
|
||||
"reservation_window_not_reached", 0
|
||||
)
|
||||
reservation_expired = counters.get("reservation_expired", 0)
|
||||
reservation_queue_empty = counters.get("reservation_queue_empty", 0)
|
||||
reservation_locked = counters.get("reservation_locked", 0)
|
||||
reservation_back_to_first = counters.get("reservation_back_to_first", 0)
|
||||
reservation_queue_full_wait = counters.get("reservation_queue_full_wait", 0)
|
||||
reservation_drop_low_value = counters.get("reservation_drop_low_value", 0)
|
||||
reservation_clear = counters.get("reservation_clear", 0)
|
||||
reservation_back_direct_attend = counters.get(
|
||||
"reservation_back_direct_attend", 0
|
||||
)
|
||||
reservation_queue_full_back_attend = counters.get(
|
||||
"reservation_queue_full_back_attend", 0
|
||||
)
|
||||
reservation_duplicate_detected = counters.get(
|
||||
"reservation_duplicate_detected", 0
|
||||
)
|
||||
reservation_back_operation = counters.get("reservation_back_operation", 0)
|
||||
|
||||
reservation_total = (
|
||||
reservation_recorded
|
||||
+ reservation_window_entered
|
||||
+ reservation_back_success
|
||||
+ reservation_back_verify_ok
|
||||
+ reservation_back_verify_fail
|
||||
+ reservation_window_not_reached
|
||||
+ reservation_expired
|
||||
+ reservation_queue_empty
|
||||
+ reservation_locked
|
||||
+ reservation_back_to_first
|
||||
+ reservation_queue_full_wait
|
||||
+ reservation_drop_low_value
|
||||
+ reservation_clear
|
||||
+ reservation_back_direct_attend
|
||||
+ reservation_queue_full_back_attend
|
||||
+ reservation_duplicate_detected
|
||||
+ reservation_back_operation
|
||||
)
|
||||
|
||||
if reservation_total > 0 or reservation_recorded > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("预约相关统计(详细)")
|
||||
lines.append("=" * 60)
|
||||
|
||||
# 预约记录统计
|
||||
if reservation_recorded > 0:
|
||||
lines.append(f"记录预约总数: {reservation_recorded}")
|
||||
|
||||
# 预约回退统计
|
||||
if reservation_back_success > 0:
|
||||
lines.append(f"成功回退到预约直播间: {reservation_back_success}")
|
||||
|
||||
# 回退校验统计
|
||||
verify_total = reservation_back_verify_ok + reservation_back_verify_fail
|
||||
if verify_total > 0:
|
||||
verify_rate = (reservation_back_verify_ok / verify_total) * 100
|
||||
lines.append(
|
||||
f"回退校验: {reservation_back_verify_ok} 成功 / {reservation_back_verify_fail} 失败 (成功率: {verify_rate:.1f}%)"
|
||||
)
|
||||
|
||||
# 预约窗口统计
|
||||
if reservation_window_entered > 0:
|
||||
lines.append(f"进入预约参与窗口: {reservation_window_entered}")
|
||||
if reservation_window_not_reached > 0:
|
||||
lines.append(
|
||||
f"时间窗口未到(跳过): {reservation_window_not_reached}"
|
||||
)
|
||||
|
||||
# 预约状态统计
|
||||
if reservation_expired > 0:
|
||||
lines.append(f"过期预约(已清理): {reservation_expired}")
|
||||
if reservation_locked > 0:
|
||||
lines.append(f"锁定期未结束(跳过): {reservation_locked}")
|
||||
if reservation_queue_empty > 0:
|
||||
lines.append(f"预约队列为空(检查次数): {reservation_queue_empty}")
|
||||
if reservation_queue_full_wait > 0:
|
||||
lines.append(f"队列已满等待: {reservation_queue_full_wait}")
|
||||
if reservation_back_to_first > 0:
|
||||
lines.append(f"回退到第一个直播间: {reservation_back_to_first}")
|
||||
|
||||
# 预约管理统计
|
||||
if reservation_drop_low_value > 0:
|
||||
lines.append(f"丢弃低价值预约: {reservation_drop_low_value}")
|
||||
if reservation_clear > 0:
|
||||
lines.append(f"清空预约队列: {reservation_clear}")
|
||||
if reservation_duplicate_detected > 0:
|
||||
lines.append(f"检测到重复预约: {reservation_duplicate_detected}")
|
||||
|
||||
# 回退后直接参与统计
|
||||
if reservation_back_direct_attend > 0:
|
||||
lines.append(f"回退后直接参与: {reservation_back_direct_attend}")
|
||||
if reservation_queue_full_back_attend > 0:
|
||||
lines.append(
|
||||
f"队列满回退后参与: {reservation_queue_full_back_attend}"
|
||||
)
|
||||
if reservation_back_operation > 0:
|
||||
lines.append(f"回退操作次数: {reservation_back_operation}")
|
||||
|
||||
# 预约成功率
|
||||
if reservation_recorded > 0 and reservation_back_success > 0:
|
||||
back_rate = (reservation_back_success / reservation_recorded) * 100
|
||||
lines.append(
|
||||
f"预约回退成功率: {back_rate:.1f}% ({reservation_back_success}/{reservation_recorded})"
|
||||
)
|
||||
|
||||
lines.append("")
|
||||
|
||||
# 错误统计(详细版)
|
||||
error_total = counters.get("error_total", 0)
|
||||
error_unbound_local = counters.get("error_unbound_local", 0)
|
||||
error_attribute = counters.get("error_attribute", 0)
|
||||
error_key = counters.get("error_key", 0)
|
||||
error_value = counters.get("error_value", 0)
|
||||
error_type = counters.get("error_type", 0)
|
||||
error_timeout = counters.get("error_timeout", 0)
|
||||
error_connection = counters.get("error_connection", 0)
|
||||
error_ocr = counters.get("error_ocr", 0)
|
||||
error_screenshot = counters.get("error_screenshot", 0)
|
||||
error_detection = counters.get("error_detection", 0)
|
||||
error_stage_diagnosis = counters.get("error_stage_diagnosis", 0)
|
||||
error_read_detail = counters.get("error_read_detail", 0)
|
||||
error_config_load = counters.get("error_config_load", 0)
|
||||
error_state_file = counters.get("error_state_file", 0)
|
||||
error_live_room_detect = counters.get("error_live_room_detect", 0)
|
||||
error_fudai_find = counters.get("error_fudai_find", 0)
|
||||
fudai_open_error = counters.get("fudai_open_error", 0)
|
||||
fudai_open_error_too_many = counters.get("fudai_open_error_too_many", 0)
|
||||
|
||||
error_all = (
|
||||
error_total
|
||||
+ error_unbound_local
|
||||
+ error_attribute
|
||||
+ error_key
|
||||
+ error_value
|
||||
+ error_type
|
||||
+ error_timeout
|
||||
+ error_connection
|
||||
+ error_ocr
|
||||
+ error_screenshot
|
||||
+ error_detection
|
||||
+ error_stage_diagnosis
|
||||
+ error_read_detail
|
||||
+ error_config_load
|
||||
+ error_state_file
|
||||
+ error_live_room_detect
|
||||
+ error_fudai_find
|
||||
+ fudai_open_error
|
||||
+ fudai_open_error_too_many
|
||||
)
|
||||
|
||||
if error_all > 0:
|
||||
lines.append("=" * 60)
|
||||
lines.append("错误统计(详细)")
|
||||
lines.append("=" * 60)
|
||||
|
||||
# 总错误数
|
||||
if error_total > 0:
|
||||
lines.append(f"总错误数: {error_total}")
|
||||
|
||||
# 福袋相关错误
|
||||
fudai_errors = fudai_open_error + fudai_open_error_too_many
|
||||
if fudai_errors > 0:
|
||||
lines.append("")
|
||||
lines.append("福袋相关错误:")
|
||||
if fudai_open_error > 0:
|
||||
lines.append(f" 打开福袋异常: {fudai_open_error}")
|
||||
if fudai_open_error_too_many > 0:
|
||||
lines.append(f" 打开失败次数过多: {fudai_open_error_too_many}")
|
||||
|
||||
# Python异常类型
|
||||
python_errors = (
|
||||
error_unbound_local
|
||||
+ error_attribute
|
||||
+ error_key
|
||||
+ error_value
|
||||
+ error_type
|
||||
)
|
||||
if python_errors > 0:
|
||||
lines.append("")
|
||||
lines.append("Python异常类型:")
|
||||
if error_unbound_local > 0:
|
||||
lines.append(f" UnboundLocalError: {error_unbound_local}")
|
||||
if error_attribute > 0:
|
||||
lines.append(f" AttributeError: {error_attribute}")
|
||||
if error_key > 0:
|
||||
lines.append(f" KeyError: {error_key}")
|
||||
if error_value > 0:
|
||||
lines.append(f" ValueError: {error_value}")
|
||||
if error_type > 0:
|
||||
lines.append(f" TypeError: {error_type}")
|
||||
|
||||
# 功能模块错误
|
||||
module_errors = (
|
||||
error_ocr
|
||||
+ error_screenshot
|
||||
+ error_detection
|
||||
+ error_stage_diagnosis
|
||||
+ error_read_detail
|
||||
+ error_config_load
|
||||
+ error_state_file
|
||||
+ error_live_room_detect
|
||||
+ error_fudai_find
|
||||
)
|
||||
if module_errors > 0:
|
||||
lines.append("")
|
||||
lines.append("功能模块错误:")
|
||||
if error_ocr > 0:
|
||||
lines.append(f" OCR识别错误: {error_ocr}")
|
||||
if error_screenshot > 0:
|
||||
lines.append(f" 截图错误: {error_screenshot}")
|
||||
if error_detection > 0:
|
||||
lines.append(f" 识别错误: {error_detection}")
|
||||
if error_stage_diagnosis > 0:
|
||||
lines.append(f" 阶段诊断错误: {error_stage_diagnosis}")
|
||||
if error_read_detail > 0:
|
||||
lines.append(f" 读取详情错误: {error_read_detail}")
|
||||
if error_config_load > 0:
|
||||
lines.append(f" 配置加载错误: {error_config_load}")
|
||||
if error_state_file > 0:
|
||||
lines.append(f" 状态文件错误: {error_state_file}")
|
||||
if error_live_room_detect > 0:
|
||||
lines.append(f" 直播间检测错误: {error_live_room_detect}")
|
||||
if error_fudai_find > 0:
|
||||
lines.append(f" 福袋查找错误: {error_fudai_find}")
|
||||
|
||||
# 网络和超时错误
|
||||
network_errors = error_timeout + error_connection
|
||||
if network_errors > 0:
|
||||
lines.append("")
|
||||
lines.append("网络和超时错误:")
|
||||
if error_timeout > 0:
|
||||
lines.append(f" 超时错误: {error_timeout}")
|
||||
if error_connection > 0:
|
||||
lines.append(f" 连接错误: {error_connection}")
|
||||
|
||||
# 错误率统计
|
||||
if uptime_seconds > 0 and error_all > 0:
|
||||
hours = uptime_seconds / 3600.0
|
||||
if hours > 0:
|
||||
lines.append("")
|
||||
lines.append(f"错误频率: {error_all / hours:.2f} 次/小时")
|
||||
|
||||
lines.append("")
|
||||
|
||||
# 价值统计(从事件中提取)
|
||||
events = stats.get("events", [])
|
||||
prize_values = []
|
||||
for event in events:
|
||||
meta = event.get("meta", {})
|
||||
if "prize_value_yuan" in meta and meta["prize_value_yuan"] is not None:
|
||||
try:
|
||||
prize_values.append(float(meta["prize_value_yuan"]))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
if prize_values:
|
||||
lines.append("=" * 60)
|
||||
lines.append("价值统计")
|
||||
lines.append("=" * 60)
|
||||
total_value = sum(prize_values)
|
||||
avg_value = total_value / len(prize_values)
|
||||
max_value = max(prize_values)
|
||||
min_value = min(prize_values)
|
||||
lines.append(f"识别到的福袋总数: {len(prize_values)}")
|
||||
# 说明:价值统计只统计了成功识别到价值的福袋,可能少于总识别次数
|
||||
if fudai_seen_unique > len(prize_values):
|
||||
lines.append(
|
||||
f" (总识别次数: {fudai_seen_unique},其中 {len(prize_values)} 个成功识别到价值)"
|
||||
)
|
||||
lines.append(f"总价值: {total_value:.2f} 元")
|
||||
lines.append(f"平均价值: {avg_value:.2f} 元")
|
||||
lines.append(f"最高价值: {max_value:.2f} 元")
|
||||
lines.append(f"最低价值: {min_value:.2f} 元")
|
||||
|
||||
# 价值分布
|
||||
high_value_count = sum(1 for v in prize_values if v >= 500)
|
||||
medium_value_count = sum(1 for v in prize_values if 100 <= v < 500)
|
||||
low_value_count = sum(1 for v in prize_values if v < 100)
|
||||
lines.append("")
|
||||
lines.append("价值分布:")
|
||||
lines.append(
|
||||
f" 高价值(≥500元): {high_value_count} ({high_value_count/len(prize_values)*100:.1f}%)"
|
||||
)
|
||||
lines.append(
|
||||
f" 中价值(100-500元): {medium_value_count} ({medium_value_count/len(prize_values)*100:.1f}%)"
|
||||
)
|
||||
lines.append(
|
||||
f" 低价值(<100元): {low_value_count} ({low_value_count/len(prize_values)*100:.1f}%)"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
# 最近一次福袋信息
|
||||
fudai_last = stats.get("fudai_last", {})
|
||||
if fudai_last.get("content") or fudai_last.get("countdown"):
|
||||
lines.append("=" * 60)
|
||||
lines.append("最近一次福袋信息")
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"内容: {fudai_last.get('content') or '-'}")
|
||||
lines.append(f"倒计时: {fudai_last.get('countdown') or '-'}")
|
||||
participants = fudai_last.get("participants")
|
||||
copies = fudai_last.get("copies")
|
||||
if participants is not None and copies is not None:
|
||||
lines.append(f"参与人数/份数: {participants} / {copies}")
|
||||
if participants > 0 and copies > 0:
|
||||
ratio = participants / copies
|
||||
lines.append(f" 中奖概率: {1/ratio*100:.2f}% (1/{ratio:.1f})")
|
||||
prize_value = fudai_last.get("prize_value_yuan")
|
||||
if prize_value is not None:
|
||||
lines.append(f"奖品价值: {prize_value} 元")
|
||||
updated_ts = fudai_last.get("updated_ts")
|
||||
if updated_ts:
|
||||
dt = datetime.fromtimestamp(updated_ts)
|
||||
lines.append("更新时间: " + dt.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
lines.append("")
|
||||
|
||||
# 中奖记录
|
||||
wins = stats.get("wins", [])
|
||||
if wins:
|
||||
lines.append("=" * 60)
|
||||
lines.append(f"最近中奖记录(显示最近 {len(wins)} 条)")
|
||||
lines.append("=" * 60)
|
||||
for i, win in enumerate(wins[-10:], 1): # 只显示最近10条
|
||||
ts = win.get("ts", 0)
|
||||
dt_str = (
|
||||
datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
|
||||
if ts
|
||||
else "-"
|
||||
)
|
||||
lines.append(f"\n[{i}] 时间: {dt_str}")
|
||||
if win.get("content"):
|
||||
lines.append(f" 内容: {win.get('content')}")
|
||||
if win.get("prize_value_yuan"):
|
||||
lines.append(f" 价值: {win.get('prize_value_yuan')} 元")
|
||||
if win.get("participants") and win.get("copies"):
|
||||
lines.append(
|
||||
f" 人数/份数: {win.get('participants')} / {win.get('copies')}"
|
||||
)
|
||||
|
||||
# 确保至少显示基本信息
|
||||
if not lines:
|
||||
lines.append("=" * 60)
|
||||
lines.append("统计信息")
|
||||
lines.append("=" * 60)
|
||||
lines.append("暂无统计数据")
|
||||
lines.append("")
|
||||
lines.append("提示:请先运行程序以收集统计数据")
|
||||
|
||||
stats_text.delete("1.0", "end")
|
||||
stats_text.insert("1.0", "\n".join(lines))
|
||||
stats_text.insert("1.0", "\n".join(format_stats(stats)))
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
"""gui/components/stats_formatter 单元测试。
|
||||
|
||||
format_stats 是纯函数:dict → list[str]。覆盖:
|
||||
- 空 stats / 缺少字段:兜底输出占位
|
||||
- 基本运行状态格式化
|
||||
- 各分段(核心/跳过/OCR/详情/福袋查找/粉丝团/切换/预约/错误/价值/最近福袋/中奖)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from gui.components.stats_formatter import format_stats
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 边界
|
||||
# ============================================================
|
||||
|
||||
class TestEmptyStats:
|
||||
def test_empty_dict_returns_basic_info(self):
|
||||
lines = format_stats({})
|
||||
# 至少有"运行状态信息"标题
|
||||
joined = "\n".join(lines)
|
||||
assert "运行状态信息" in joined
|
||||
assert "未运行" in joined # running 缺失等价于 False
|
||||
|
||||
def test_no_counters_no_extra_sections(self):
|
||||
lines = format_stats({"running": False, "counters": {}})
|
||||
joined = "\n".join(lines)
|
||||
assert "暂无统计数据" not in joined # 至少有运行状态段
|
||||
# 不应出现具体业务统计标题
|
||||
assert "OCR识别统计" not in joined
|
||||
assert "粉丝团相关统计" not in joined
|
||||
|
||||
|
||||
class TestBasicInfo:
|
||||
def test_running_true(self):
|
||||
lines = format_stats({"running": True, "pid": 1234})
|
||||
joined = "\n".join(lines)
|
||||
assert "运行中" in joined
|
||||
assert "PID: 1234" in joined
|
||||
|
||||
def test_uptime_format(self):
|
||||
# 1 小时 23 分 45 秒 = 5025 秒
|
||||
lines = format_stats({"uptime_seconds": 5025})
|
||||
joined = "\n".join(lines)
|
||||
assert "运行时长: 01:23:45" in joined
|
||||
|
||||
def test_uptime_zero(self):
|
||||
lines = format_stats({"uptime_seconds": 0})
|
||||
assert any("运行时长: -" == line for line in lines)
|
||||
|
||||
def test_exit_code_present(self):
|
||||
lines = format_stats({"exit_code": 137})
|
||||
assert any("退出码: 137" in line for line in lines)
|
||||
|
||||
def test_exit_code_none(self):
|
||||
lines = format_stats({})
|
||||
assert any("退出码: -" == line for line in lines)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 快速汇总段
|
||||
# ============================================================
|
||||
|
||||
class TestQuickSummary:
|
||||
def test_quick_summary_appears_with_data(self):
|
||||
lines = format_stats({
|
||||
"uptime_seconds": 7200, # 2 小时
|
||||
"counters": {
|
||||
"fudai_seen_unique": 10,
|
||||
"fudai_attend_ok_unique": 5,
|
||||
"fudai_result_win": 1,
|
||||
"fudai_order_success": 1,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "快速汇总" in joined
|
||||
assert "识别福袋: 10 个" in joined
|
||||
assert "运行效率: 2.5 次参与/小时" in joined # 5/2 hours
|
||||
|
||||
def test_quick_summary_skipped_when_all_zero(self):
|
||||
lines = format_stats({"counters": {}})
|
||||
joined = "\n".join(lines)
|
||||
assert "快速汇总" not in joined
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 核心统计段
|
||||
# ============================================================
|
||||
|
||||
class TestCoreStats:
|
||||
def test_open_rate_calculated(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"fudai_seen_unique": 100,
|
||||
"fudai_open_detail_unique": 80,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "打开成功率: 80.0%" in joined
|
||||
|
||||
def test_click_rate_calculated(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"fudai_open_detail_unique": 50,
|
||||
"fudai_click_attend_unique": 25,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "点击率: 50.0%" in joined
|
||||
|
||||
def test_attend_success_rate_via_clicks(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"fudai_click_attend_unique": 10,
|
||||
"fudai_attend_ok_unique": 8,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "参与成功率: 80.0%" in joined
|
||||
|
||||
def test_attend_ok_exceeds_clicks_shows_detected(self):
|
||||
"""attend_ok > click_attend → 显示"检测到已参与"提示。"""
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"fudai_click_attend_unique": 5,
|
||||
"fudai_attend_ok_unique": 8,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "其中 3 次为检测到已参与" in joined
|
||||
|
||||
def test_pending_results_warning(self):
|
||||
"""attend_ok > result_win + result_no_win → 显示"未开奖"提示。"""
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"fudai_attend_ok_unique": 10,
|
||||
"fudai_result_win": 3,
|
||||
"fudai_result_no_win": 5,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "有 2 次参与成功尚未开奖" in joined
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 各业务分段
|
||||
# ============================================================
|
||||
|
||||
class TestSkipStats:
|
||||
def test_skip_stats_with_data(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"fudai_seen_unique": 100,
|
||||
"fudai_skip_value_low": 30,
|
||||
"fudai_skip_content": 20,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "跳过原因统计" in joined
|
||||
assert "总跳过次数: 50" in joined
|
||||
assert "跳过率: 50.0%" in joined
|
||||
|
||||
def test_skip_stats_skipped_when_no_data(self):
|
||||
lines = format_stats({"counters": {}})
|
||||
joined = "\n".join(lines)
|
||||
assert "跳过原因统计" not in joined
|
||||
|
||||
|
||||
class TestStageDiagStats:
|
||||
def test_appears_with_data(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"stage_diagnosis_complete": 90,
|
||||
"stage_diagnosis_failed": 10,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "阶段诊断统计" in joined
|
||||
assert "成功率: 90.0%" in joined
|
||||
|
||||
|
||||
class TestOcrStats:
|
||||
def test_appears_with_data(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"ocr_attempt": 100,
|
||||
"ocr_success": 75,
|
||||
"ocr_failed": 20,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "OCR识别统计" in joined
|
||||
assert "OCR成功率: 75.0%" in joined
|
||||
# 100 - (75+20) = 5 → 显示"未记录结果"
|
||||
assert "5 次尝试未记录结果" in joined
|
||||
|
||||
|
||||
class TestFansclubStats:
|
||||
def test_appears_with_data(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"fansclub_required": 5,
|
||||
"fansclub_manual_needed": 2,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "粉丝团相关统计" in joined
|
||||
# 总数 7,required 5 → 71.4%
|
||||
assert "需要粉丝团: 5" in joined
|
||||
|
||||
|
||||
class TestSwitchStats:
|
||||
def test_with_uptime_shows_frequency(self):
|
||||
lines = format_stats({
|
||||
"uptime_seconds": 3600, # 1 小时
|
||||
"counters": {
|
||||
"switch_room": 30,
|
||||
"switch_room_no_fudai": 20,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "直播间切换统计" in joined
|
||||
assert "切换频率: 30.0 次/小时" in joined
|
||||
|
||||
|
||||
class TestReservationStats:
|
||||
def test_recorded_only(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"reservation_recorded": 5,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "预约相关统计(详细)" in joined
|
||||
assert "记录预约总数: 5" in joined
|
||||
|
||||
def test_back_rate_calculated(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"reservation_recorded": 10,
|
||||
"reservation_back_success": 8,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "预约回退成功率: 80.0%" in joined
|
||||
|
||||
|
||||
class TestErrorStats:
|
||||
def test_error_total(self):
|
||||
lines = format_stats({
|
||||
"counters": {"error_total": 15},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "错误统计(详细)" in joined
|
||||
assert "总错误数: 15" in joined
|
||||
|
||||
def test_python_errors_grouped(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"error_unbound_local": 1,
|
||||
"error_attribute": 2,
|
||||
"error_key": 3,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "Python异常类型:" in joined
|
||||
assert "AttributeError: 2" in joined
|
||||
|
||||
def test_module_errors_grouped(self):
|
||||
lines = format_stats({
|
||||
"counters": {
|
||||
"error_ocr": 5,
|
||||
"error_screenshot": 3,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "功能模块错误:" in joined
|
||||
assert "OCR识别错误: 5" in joined
|
||||
|
||||
def test_error_rate_per_hour(self):
|
||||
lines = format_stats({
|
||||
"uptime_seconds": 3600,
|
||||
"counters": {"error_total": 10},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "错误频率: 10.00 次/小时" in joined
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 价值统计 + 最近福袋 + 中奖记录
|
||||
# ============================================================
|
||||
|
||||
class TestValueStats:
|
||||
def test_appears_with_events(self):
|
||||
lines = format_stats({
|
||||
"events": [
|
||||
{"meta": {"prize_value_yuan": 600}},
|
||||
{"meta": {"prize_value_yuan": 200}},
|
||||
{"meta": {"prize_value_yuan": 50}},
|
||||
],
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "价值统计" in joined
|
||||
assert "总价值: 850.00 元" in joined
|
||||
# 高/中/低各 1 个 = 33.3%
|
||||
assert "高价值(≥500元): 1 (33.3%)" in joined
|
||||
|
||||
def test_skipped_when_no_events(self):
|
||||
lines = format_stats({"events": []})
|
||||
joined = "\n".join(lines)
|
||||
assert "价值统计" not in joined
|
||||
|
||||
|
||||
class TestFudaiLast:
|
||||
def test_appears_with_content(self):
|
||||
lines = format_stats({
|
||||
"fudai_last": {
|
||||
"content": "iPhone 15",
|
||||
"countdown": "05:30",
|
||||
"participants": 1000,
|
||||
"copies": 10,
|
||||
},
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "最近一次福袋信息" in joined
|
||||
assert "内容: iPhone 15" in joined
|
||||
assert "倒计时: 05:30" in joined
|
||||
# 1000/10 = 100,中奖概率 = 1/100 = 1.00%
|
||||
assert "中奖概率: 1.00%" in joined
|
||||
|
||||
def test_skipped_when_no_content_no_countdown(self):
|
||||
lines = format_stats({"fudai_last": {}})
|
||||
joined = "\n".join(lines)
|
||||
assert "最近一次福袋信息" not in joined
|
||||
|
||||
|
||||
class TestWins:
|
||||
def test_appears_with_data(self):
|
||||
lines = format_stats({
|
||||
"wins": [
|
||||
{"ts": 1700000000, "content": "iPhone 15", "prize_value_yuan": 5999},
|
||||
],
|
||||
})
|
||||
joined = "\n".join(lines)
|
||||
assert "最近中奖记录" in joined
|
||||
assert "iPhone 15" in joined
|
||||
assert "5999" in joined
|
||||
|
||||
def test_truncates_to_10(self):
|
||||
wins = [{"ts": 1700000000 + i, "content": f"奖品{i}"} for i in range(20)]
|
||||
lines = format_stats({"wins": wins})
|
||||
joined = "\n".join(lines)
|
||||
# 最后 10 条应该是 10..19
|
||||
assert "奖品10" in joined
|
||||
assert "奖品19" in joined
|
||||
# 前 10 条不该出现
|
||||
assert "奖品0\n" not in joined # tricky, but 奖品0 不该作为单独条目
|
||||
Reference in new issue
Block a user