Files
douyin_guaji-main/tests/test_ocr_tasks.py
T
CodexandClaude Opus 4.7 f38b373636 refactor(fudai_core): 抽 7 个并行 OCR 闭包到 ocr_tasks 模块 (1659 → 1328)
get_fudai_contain L222-553 有 7 个 ocr_* 闭包:task_list / content /
countdown_mm / countdown_ss / value / button / live_room_title。每个都遵循
同样的模板(计时 + analyse_pic_word/digits + perf 字典 + 异常日志),共 330 行。

抽到 douyin_fudai_core_pkg/ocr_tasks.py 的 OcrTaskRunner 类:
- 7 个方法对应 7 个并行任务
- 共享耗时 dict + lock 在构造器传入
- _record_duration / _log_warn 提取出共有的 finally + except 模板
- _BUTTON_KEYWORDS 关键词常量化(原本是闭包里硬编码 tuple)
- _safe_preprocess 顶层 helper

主流程从 7 个闭包定义 + 配置开关重复读取(330 行)变成 22 行 runner 实例化 +
方法绑定,并保留 ocr_task_list / ocr_content / ... 名字给后续 executor.submit
当作 Callable 传入,行为完全不变。

新增 22 个单元测试覆盖:
- _safe_preprocess 兜底
- 7 个方法的成功 / disable 跳过 / 异常 / 边界
- ocr_button 关键词短路 + 重试逻辑
- 所有方法都正确记录耗时到 perf_durations

1294 passed (+22)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:52:22 +08:00

298 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""douyin_fudai_core_pkg.ocr_tasks 单元测试。
覆盖 OcrTaskRunner 的 7 个方法 + 内部 helper:
- _safe_preprocess: 失败时回退原 name
- ocr_task_list / ocr_content: disable_flag 跳过 / 正常路径 / 异常
- ocr_countdown_mm / ocr_countdown_ss: digits 提取 / 异常
- ocr_value / ocr_button: 文本路径 / button 关键词短路 / 异常
- ocr_live_room_title: 委托到 _ocr_try_room_title
- 各方法的耗时 (ms) 都进 perf_durations
"""
from __future__ import annotations
import threading
from unittest.mock import MagicMock, patch
import pytest
from douyin.fudai.douyin_fudai_core_pkg.ocr_tasks import (
OcrTaskRunner,
_BUTTON_KEYWORDS,
_safe_preprocess,
)
def _mk_analyser():
a = MagicMock()
a._log_kv = MagicMock(return_value=None)
a.operation = MagicMock()
return a
def _mk_runner(analyser=None, *, disable_content=False):
if analyser is None:
analyser = _mk_analyser()
durations = {}
lock = threading.Lock()
runner = OcrTaskRunner(
analyser,
durations,
lock,
disable_content_recognition=disable_content,
)
return runner, durations
# ============================================================
# _safe_preprocess
# ============================================================
class TestSafePreprocess:
def test_success(self):
with patch(
"douyin.utils.ocr_preprocess.preprocess_for_ocr",
return_value="processed_name",
):
assert _safe_preprocess(MagicMock(), "X") == "processed_name"
def test_throws_returns_original_name(self):
with patch(
"douyin.utils.ocr_preprocess.preprocess_for_ocr",
side_effect=RuntimeError("preprocess fail"),
):
assert _safe_preprocess(MagicMock(), "原名") == "原名"
# ============================================================
# ocr_task_list
# ============================================================
class TestOcrTaskList:
def test_disabled_skips(self):
runner, durations = _mk_runner()
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=True,
):
assert runner.ocr_task_list() is None
# 跳过路径仍记录耗时
assert "ocr_task_list" in durations
def test_success(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
return_value="任务1\n任务2"
)
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
):
assert runner.ocr_task_list() == "任务1\n任务2"
assert durations["ocr_task_list"] >= 0
def test_exception(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
side_effect=RuntimeError("ocr fail")
)
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
):
assert runner.ocr_task_list() is None
# 异常仍写日志 + 耗时
assert "ocr_task_list" in durations
# ============================================================
# ocr_content
# ============================================================
class TestOcrContent:
def test_disabled_skips(self):
runner, durations = _mk_runner(disable_content=True)
runner.analyser.operation.analyse_pic_word = MagicMock()
assert runner.ocr_content() is None
# 不应调用 OCR
runner.analyser.operation.analyse_pic_word.assert_not_called()
assert "ocr_content" in durations
def test_success(self):
runner, durations = _mk_runner(disable_content=False)
runner.analyser.operation.analyse_pic_word = MagicMock(
return_value="福袋内容"
)
assert runner.ocr_content() == "福袋内容"
assert durations["ocr_content"] >= 0
# ============================================================
# ocr_countdown_mm / ocr_countdown_ss
# ============================================================
class TestOcrCountdown:
def test_mm_extracts_digits(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
return_value="abc23def"
)
assert runner.ocr_countdown_mm() == "23"
assert "ocr_countdown_mm" in durations
def test_ss_extracts_digits(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
return_value="45"
)
assert runner.ocr_countdown_ss() == "45"
def test_mm_empty(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
return_value=None
)
assert runner.ocr_countdown_mm() == ""
def test_mm_throws(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
side_effect=RuntimeError()
)
assert runner.ocr_countdown_mm() is None
# ============================================================
# ocr_value
# ============================================================
class TestOcrValue:
def test_success(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
return_value="¥500"
)
assert runner.ocr_value() == "¥500"
assert "ocr_value" in durations
def test_returns_empty_string_for_none(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(return_value=None)
# str(None or "") = ""
assert runner.ocr_value() == ""
def test_throws(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
side_effect=RuntimeError()
)
assert runner.ocr_value() is None
# ============================================================
# ocr_button
# ============================================================
class TestOcrButton:
def test_keyword_short_circuits(self):
"""识别到关键词应立即返回,不再二次 OCR。"""
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
return_value="参与抽奖"
)
assert runner.ocr_button() == "参与抽奖"
# 模式 0 一次就够
assert runner.analyser.operation.analyse_pic_word.call_count == 1
def test_no_keyword_returns_text_anyway(self):
"""识别到非关键词文本也会返回。"""
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
return_value="未知按钮文本"
)
# 不在关键词里 → 仍返回,但可能再尝试一次(保留旧逻辑)
result = runner.ocr_button()
assert result == "未知按钮文本"
def test_empty_first_then_retry(self):
"""模式 0 完全失败时再试一次。"""
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
side_effect=["", "重试得到的文本"]
)
assert runner.ocr_button() == "重试得到的文本"
assert runner.analyser.operation.analyse_pic_word.call_count == 2
def test_throws_returns_none(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_word = MagicMock(
side_effect=RuntimeError()
)
assert runner.ocr_button() is None
def test_button_keywords_constant(self):
"""关键词里至少含一些核心字串。"""
for k in ("参与抽奖", "等待开奖", "未达成"):
assert k in _BUTTON_KEYWORDS
# ============================================================
# ocr_live_room_title
# ============================================================
class TestOcrLiveRoomTitle:
def test_delegates_to_ocr_try_room_title(self):
runner, durations = _mk_runner()
with patch(
"douyin.fudai.core.fudai_detail_room_title._ocr_try_room_title",
return_value=("主播间标题", "raw text"),
):
title, raw = runner.ocr_live_room_title()
assert title == "主播间标题"
assert raw == "raw text"
assert "ocr_live_room_title" in durations
def test_throws_returns_empty_tuple(self):
runner, durations = _mk_runner()
with patch(
"douyin.fudai.core.fudai_detail_room_title._ocr_try_room_title",
side_effect=RuntimeError(),
):
assert runner.ocr_live_room_title() == ("", "")
# ============================================================
# 通用:所有方法都记录耗时到共享 dict
# ============================================================
class TestPerfDurations:
def test_all_keys_present_after_one_call_each(self):
runner, durations = _mk_runner()
# 让 OCR 都返回固定值
runner.analyser.operation.analyse_pic_word = MagicMock(return_value="x")
runner.analyser.operation.analyse_pic_digits = MagicMock(return_value="1")
with patch(
"douyin.fudai.douyin_fudai_core_pkg.heavy_ocr._read_disable_flag",
return_value=False,
), patch(
"douyin.fudai.core.fudai_detail_room_title._ocr_try_room_title",
return_value=("title", "raw"),
):
runner.ocr_task_list()
runner.ocr_content()
runner.ocr_countdown_mm()
runner.ocr_countdown_ss()
runner.ocr_value()
runner.ocr_live_room_title()
# ocr_button 不计耗时(保留原行为差异)
for k in (
"ocr_task_list",
"ocr_content",
"ocr_countdown_mm",
"ocr_countdown_ss",
"ocr_value",
"ocr_live_room_title",
):
assert k in durations, f"missing duration for {k}"
assert durations[k] >= 0