修复福袋详情OCR v2与调试日志
This commit is contained in:
1 parent
2c6f024a24
commit
1d37d57c90
119 files changed
+5582
-767
No files matched your search
@@ -32,6 +32,18 @@ class TestActionLoggerMethods:
|
||||
alog.log_operation("click", details="button_x", x=100, y=200)
|
||||
alog.log_operation("simple_op")
|
||||
|
||||
def test_log_operation_preserves_elapsed_seconds_kwarg(self, alog, caplog):
|
||||
with caplog.at_level(logging.INFO):
|
||||
alog.log_operation("click", details="button_x", elapsed_seconds=1.23)
|
||||
|
||||
assert any("耗时=1230.00ms" in r.getMessage() for r in caplog.records)
|
||||
|
||||
def test_log_operation_preserves_elapsed_kwarg(self, alog, caplog):
|
||||
with caplog.at_level(logging.INFO):
|
||||
alog.log_operation("click", details="button_x", elapsed=0.48)
|
||||
|
||||
assert any("耗时=480.00ms" in r.getMessage() for r in caplog.records)
|
||||
|
||||
def test_long_kwargs_does_not_raise(self, alog):
|
||||
# 大量 kwargs 不应导致格式化失败
|
||||
alog.log_operation("complex", **{f"k{i}": i for i in range(50)})
|
||||
|
||||
@@ -131,7 +131,8 @@ class TestReadCountdownSplit:
|
||||
read_countdown_split(a, (100, 200, 400, 250), save_debug_images=False)
|
||||
mock_save.assert_not_called()
|
||||
|
||||
def test_save_debug_images_enabled_calls_save(self):
|
||||
def test_save_debug_images_enabled_does_not_save_per_field(self):
|
||||
"""详情页 debug 统一由主流程保存一张综合标注图,不再保存倒计时分图。"""
|
||||
a = _mk_analyser()
|
||||
a.operation.analyse_pic_digits = MagicMock(side_effect=["23", "45"])
|
||||
|
||||
@@ -139,5 +140,4 @@ class TestReadCountdownSplit:
|
||||
"douyin.fudai.core.fudai_debug_utils._save_full_screenshot_with_ocr_region"
|
||||
) as mock_save:
|
||||
read_countdown_split(a, (100, 200, 400, 250), save_debug_images=True)
|
||||
# 调用 2 次(分钟 + 秒)
|
||||
assert mock_save.call_count == 2
|
||||
mock_save.assert_not_called()
|
||||
@@ -104,14 +104,14 @@ class TestCutDetailRegions:
|
||||
cut_detail_regions(a, renwu=2, save_debug_images=False)
|
||||
mock_save.assert_not_called()
|
||||
|
||||
def test_save_debug_images_enabled_calls_4_times(self):
|
||||
"""启用后每个区域都保存:内容 + 分钟 + 秒 + 价值 = 4 次。"""
|
||||
def test_save_debug_images_enabled_does_not_save_per_field(self):
|
||||
"""详情页 debug 已改为主流程统一保存一张综合标注图。"""
|
||||
a = _mk_analyser()
|
||||
with patch(
|
||||
"douyin.fudai.core.fudai_debug_utils._save_full_screenshot_with_ocr_region"
|
||||
) as mock_save:
|
||||
cut_detail_regions(a, renwu=2, save_debug_images=True)
|
||||
assert mock_save.call_count == 4
|
||||
mock_save.assert_not_called()
|
||||
|
||||
def test_renwu_1_uses_correct_box(self):
|
||||
a = _mk_analyser()
|
||||
|
||||
@@ -10,6 +10,9 @@ from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import pytest
|
||||
from types import SimpleNamespace
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
class TestPixelPopups:
|
||||
@@ -37,6 +40,68 @@ class TestPixelPopups:
|
||||
|
||||
assert callable(detect_lucky_draw_result_popup)
|
||||
|
||||
def test_detect_lucky_draw_result_white_confirm_button(self):
|
||||
from douyin.detection.pixel.popups import detect_lucky_draw_result_popup
|
||||
from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2
|
||||
|
||||
img = Image.new("RGB", (1080, 2400), (20, 20, 20))
|
||||
x1, y1, x2, y2 = LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2
|
||||
for y in range(y1, y2):
|
||||
for x in range(x1, x2):
|
||||
img.putpixel((x, y), (245, 245, 245))
|
||||
|
||||
detected, info = detect_lucky_draw_result_popup(
|
||||
img,
|
||||
return_info=True,
|
||||
analyser=SimpleNamespace(fudai_detail_ui_mode="v2_0"),
|
||||
)
|
||||
|
||||
assert detected is True
|
||||
assert info["white_ratio"] >= 0.8
|
||||
assert info["ui_version"] == "v2_0"
|
||||
assert info["pixel_style"] == "white"
|
||||
|
||||
def test_detect_lucky_draw_result_red_confirm_button_legacy(self):
|
||||
from douyin.detection.pixel.popups import detect_lucky_draw_result_popup
|
||||
from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1
|
||||
|
||||
img = Image.new("RGB", (1080, 2400), (20, 20, 20))
|
||||
x1, y1, x2, y2 = LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1
|
||||
for y in range(y1, y2):
|
||||
for x in range(x1, x2):
|
||||
img.putpixel((x, y), (255, 60, 100))
|
||||
|
||||
detected, info = detect_lucky_draw_result_popup(
|
||||
img,
|
||||
return_info=True,
|
||||
analyser=SimpleNamespace(fudai_detail_ui_mode="legacy"),
|
||||
)
|
||||
|
||||
assert detected is True
|
||||
assert info["red_ratio"] >= 0.8
|
||||
assert info["ui_version"] == "legacy"
|
||||
assert info["pixel_style"] == "red"
|
||||
|
||||
def test_detect_lucky_draw_result_legacy_does_not_accept_v2_white_button(self):
|
||||
from douyin.detection.pixel.popups import detect_lucky_draw_result_popup
|
||||
from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1
|
||||
|
||||
img = Image.new("RGB", (1080, 2400), (20, 20, 20))
|
||||
x1, y1, x2, y2 = LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1
|
||||
for y in range(y1, y2):
|
||||
for x in range(x1, x2):
|
||||
img.putpixel((x, y), (245, 245, 245))
|
||||
|
||||
detected, info = detect_lucky_draw_result_popup(
|
||||
img,
|
||||
return_info=True,
|
||||
analyser=SimpleNamespace(fudai_detail_ui_mode="legacy"),
|
||||
)
|
||||
|
||||
assert detected is False
|
||||
assert info["white_ratio"] >= 0.8
|
||||
assert info["pixel_style"] == "red"
|
||||
|
||||
|
||||
class TestPixelButtons:
|
||||
"""pixel/buttons 模块测试。"""
|
||||
@@ -84,6 +149,15 @@ class TestPixelStage:
|
||||
|
||||
assert callable(read_pixel_stage_state_from_screenshot)
|
||||
|
||||
def test_stage_module_imports_popup_helpers(self):
|
||||
import douyin.detection.pixel.stage as stage_mod
|
||||
|
||||
assert hasattr(stage_mod, "detect_coupon_popup_background")
|
||||
assert hasattr(stage_mod, "detect_redpacket_popup_background")
|
||||
assert hasattr(stage_mod, "detect_lucky_draw_result_popup")
|
||||
assert hasattr(stage_mod, "detect_attend_button_red_area")
|
||||
assert hasattr(stage_mod, "detect_fansclub_join_red_area")
|
||||
|
||||
|
||||
class TestPixelCommon:
|
||||
"""pixel/_common 模块测试。"""
|
||||
|
||||
@@ -31,6 +31,8 @@ class TestExtractPrizeValueYuan:
|
||||
("价值¥1,000", 1000.0),
|
||||
# 中文/纯数字描述("价值 100 元")
|
||||
("价值 100 元", 100.0),
|
||||
("¥2999 参考价值", 2999.0),
|
||||
("¥2999 参考价值", 2999.0),
|
||||
# OCR 字母 → 数字纠错(l→1, O→0)
|
||||
("¥l00", 100.0),
|
||||
],
|
||||
@@ -92,3 +94,19 @@ class TestNormalizeCountdownText:
|
||||
def test_two_digit_minute_preserved(self):
|
||||
# 双位分钟数应保留,不被误处理
|
||||
assert normalize_countdown_text("12:34") == "12:34"
|
||||
|
||||
|
||||
def test_extract_participants_supports_wan_unit_and_cleans_text():
|
||||
from douyin.fudai.douyin_fudai_core_pkg.contain_helpers import (
|
||||
extract_participants_and_clean,
|
||||
)
|
||||
|
||||
participants, copies, cleaned = extract_participants_and_clean(
|
||||
"小米Redmi Pad 2 SE 红米平板2SE 0.4万人已参与 共1份"
|
||||
)
|
||||
|
||||
assert participants == 4000
|
||||
assert copies == 1
|
||||
assert "0.4万人已参与" not in cleaned
|
||||
assert "共1份" not in cleaned
|
||||
assert "小米Redmi" in cleaned
|
||||
@@ -46,7 +46,7 @@ class MockAnalyser:
|
||||
|
||||
def _make_detail(
|
||||
content="现金红包",
|
||||
time_text="2分钟",
|
||||
time_text="02:00",
|
||||
participants=10,
|
||||
copies=1,
|
||||
prize_value_yuan=100.0,
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
|
||||
def test_main_finder_writes_back_last_fudai_x(monkeypatch):
|
||||
from douyin.detection.detection_pkg import finder as mod
|
||||
|
||||
class _Pic:
|
||||
size = (1080, 2400)
|
||||
def load(self): return None
|
||||
def convert(self, _mode): return self
|
||||
def close(self): return None
|
||||
|
||||
analyser = MagicMock()
|
||||
analyser.fudai_finder_optimized_enabled = False
|
||||
analyser.device_id = "MOCK"
|
||||
analyser.resolution_ratio_x = 1080
|
||||
analyser.resolution_ratio_y = 2400
|
||||
analyser.y_pianyi = 0
|
||||
analyser.last_fudai_x = 0
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.get_screenshot = MagicMock(return_value=True)
|
||||
analyser.operation.delay = MagicMock(return_value=None)
|
||||
analyser._log_kv = MagicMock(return_value=None)
|
||||
|
||||
pil_mod = ModuleType("PIL")
|
||||
pil_mod.Image = SimpleNamespace(open=lambda _p: _Pic())
|
||||
monkeypatch.setitem(sys.modules, "PIL", pil_mod)
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.path_config.get_screenshot_path", lambda: "fake.png")
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.exists", lambda _p: True)
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.getsize", lambda _p: 2048)
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_with_numpy", lambda *a, **k: (True, 233))
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_pixel_by_pixel", lambda *a, **k: (False, None))
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.match_template", lambda *a, **k: (False, None))
|
||||
|
||||
result = mod.check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
|
||||
|
||||
assert result == 233
|
||||
assert analyser.last_fudai_x == 233
|
||||
|
||||
|
||||
def test_main_finder_uses_scaled_history_on_non_1080_width(monkeypatch):
|
||||
from douyin.detection.detection_pkg import finder as mod
|
||||
|
||||
class _Pic:
|
||||
size = (720, 1600)
|
||||
def load(self): return None
|
||||
def convert(self, _mode): return self
|
||||
def close(self): return None
|
||||
|
||||
captured = {}
|
||||
|
||||
analyser = MagicMock()
|
||||
analyser.fudai_finder_optimized_enabled = False
|
||||
analyser.device_id = "MOCK"
|
||||
analyser.resolution_ratio_x = 720
|
||||
analyser.resolution_ratio_y = 1600
|
||||
analyser.y_pianyi = 0
|
||||
analyser.last_fudai_x = 233 # 1080 基准坐标
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.get_screenshot = MagicMock(return_value=True)
|
||||
analyser.operation.delay = MagicMock(return_value=None)
|
||||
analyser._log_kv = MagicMock(return_value=None)
|
||||
|
||||
pil_mod = ModuleType("PIL")
|
||||
pil_mod.Image = SimpleNamespace(open=lambda _p: _Pic())
|
||||
monkeypatch.setitem(sys.modules, "PIL", pil_mod)
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.path_config.get_screenshot_path", lambda: "fake.png")
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.exists", lambda _p: True)
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.getsize", lambda _p: 2048)
|
||||
|
||||
def fake_numpy(_analyser, _pic, rx, ry, y_pianyi_val, optimal_x_scaled): # noqa: ARG001
|
||||
captured["optimal_x_scaled"] = optimal_x_scaled
|
||||
return False, None
|
||||
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_with_numpy", fake_numpy)
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_pixel_by_pixel", lambda *a, **k: (False, None))
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.match_template", lambda *a, **k: (False, None))
|
||||
|
||||
result = mod.check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
|
||||
|
||||
assert result is False
|
||||
assert captured["optimal_x_scaled"] == 233 * 720 // 1080
|
||||
|
||||
|
||||
def test_main_finder_zero_wait_still_runs_one_detection(monkeypatch):
|
||||
from douyin.detection.detection_pkg import finder as mod
|
||||
|
||||
class _Pic:
|
||||
size = (1080, 2400)
|
||||
def load(self): return None
|
||||
def convert(self, _mode): return self
|
||||
def close(self): return None
|
||||
|
||||
analyser = MagicMock()
|
||||
analyser.fudai_finder_optimized_enabled = False
|
||||
analyser.device_id = "MOCK"
|
||||
analyser.resolution_ratio_x = 1080
|
||||
analyser.resolution_ratio_y = 2400
|
||||
analyser.y_pianyi = 0
|
||||
analyser.last_fudai_x = 0
|
||||
analyser.fudai_icon_max_wait_seconds = 0
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.get_screenshot = MagicMock(return_value=True)
|
||||
analyser.operation.delay = MagicMock(return_value=None)
|
||||
analyser._log_kv = MagicMock(return_value=None)
|
||||
|
||||
pil_mod = ModuleType("PIL")
|
||||
pil_mod.Image = SimpleNamespace(open=lambda _p: _Pic())
|
||||
monkeypatch.setitem(sys.modules, "PIL", pil_mod)
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.path_config.get_screenshot_path", lambda: "fake.png")
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.exists", lambda _p: True)
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.os.path.getsize", lambda _p: 2048)
|
||||
|
||||
calls = {"numpy": 0}
|
||||
|
||||
def fake_numpy(*args, **kwargs): # noqa: ARG001
|
||||
calls["numpy"] += 1
|
||||
return False, None
|
||||
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_with_numpy", fake_numpy)
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_pixel_by_pixel", lambda *a, **k: (False, None))
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.match_template", lambda *a, **k: (False, None))
|
||||
|
||||
result = mod.check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
|
||||
|
||||
assert result is False
|
||||
assert calls["numpy"] == 1
|
||||
@@ -160,6 +160,7 @@ class TestMatchTemplateHit:
|
||||
# x = (156 + 5 + 10) * 1080 / 1080 = 171
|
||||
assert x == 171
|
||||
assert a.last_find_fudai_time > 0
|
||||
assert a.last_fudai_x == 171
|
||||
|
||||
def test_low_match_score_returns_false(self, tmp_path, monkeypatch):
|
||||
"""max_val < threshold → 不命中。"""
|
||||
|
||||
+131
-12
@@ -1,7 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from douyin.fudai.core.coords import DETAIL_OUTSIDE_CLICK
|
||||
from douyin.fudai.core.fudai_attend import attend_choujiang
|
||||
|
||||
|
||||
@@ -9,17 +11,22 @@ def test_attend_choujiang_fallback_click_on_unknown_button_text() -> None:
|
||||
analyser = MagicMock()
|
||||
analyser._fudai_button_status = "未知状态"
|
||||
analyser._fudai_button_text = "按钮文案发生变化"
|
||||
analyser._fudai_button_ocr_time = 10**12
|
||||
analyser._fudai_button_ocr_time = 10_000.0
|
||||
analyser._fudai_button_room_pos = 0
|
||||
analyser.room_pos = 0
|
||||
analyser._run_id = "test-run"
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.click = MagicMock()
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.delay = MagicMock()
|
||||
analyser.last_attend_fail_reason = ""
|
||||
|
||||
ok = attend_choujiang(analyser)
|
||||
import time as _time
|
||||
|
||||
old_time = _time.time
|
||||
_time.time = lambda: 10_001.0
|
||||
try:
|
||||
ok = attend_choujiang(analyser)
|
||||
finally:
|
||||
_time.time = old_time
|
||||
|
||||
assert ok is True
|
||||
analyser.click.assert_called_once()
|
||||
@@ -29,19 +36,131 @@ def test_attend_choujiang_treat_notice_text_as_attended() -> None:
|
||||
analyser = MagicMock()
|
||||
analyser._fudai_button_status = "已参与"
|
||||
analyser._fudai_button_text = "直播间,否则会失去抽奖机会"
|
||||
analyser._fudai_button_ocr_time = 10**12
|
||||
analyser._fudai_button_ocr_time = 20_000.0
|
||||
analyser._fudai_button_room_pos = 0
|
||||
analyser.room_pos = 0
|
||||
analyser._run_id = "test-run"
|
||||
analyser._current_fudai_future_ts = 0.0
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.click = MagicMock()
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.delay = MagicMock()
|
||||
|
||||
import time as _time
|
||||
|
||||
old_time = _time.time
|
||||
_time.time = lambda: 20_001.0
|
||||
try:
|
||||
ok = attend_choujiang(analyser)
|
||||
finally:
|
||||
_time.time = old_time
|
||||
|
||||
assert ok is True
|
||||
analyser.click.assert_called_once_with(*DETAIL_OUTSIDE_CLICK)
|
||||
|
||||
|
||||
def test_attend_choujiang_does_not_reuse_fresh_button_cache_from_other_room() -> None:
|
||||
analyser = MagicMock()
|
||||
analyser._fudai_button_status = "可以参与"
|
||||
analyser._fudai_button_text = "参与抽奖"
|
||||
analyser._fudai_button_ocr_time = 30_000.0
|
||||
analyser._fudai_button_room_pos = 3
|
||||
analyser.room_pos = 8
|
||||
analyser.button_text_raw = None
|
||||
analyser._room_pos_to_title_map = {}
|
||||
analyser.click = MagicMock()
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.delay = MagicMock()
|
||||
|
||||
import time as _time
|
||||
|
||||
old_time = _time.time
|
||||
_time.time = lambda: 30_001.0
|
||||
try:
|
||||
ok = attend_choujiang(analyser)
|
||||
finally:
|
||||
_time.time = old_time
|
||||
|
||||
assert ok is False
|
||||
assert analyser.last_attend_fail_reason == "no_parallel_ocr_result"
|
||||
analyser.click.assert_called_once_with(*DETAIL_OUTSIDE_CLICK)
|
||||
|
||||
|
||||
def test_attend_choujiang_does_not_reuse_button_text_raw_from_other_room() -> None:
|
||||
analyser = MagicMock()
|
||||
analyser._fudai_button_status = None
|
||||
analyser._fudai_button_text = ""
|
||||
analyser._fudai_button_ocr_time = 0.0
|
||||
analyser._fudai_button_room_pos = 3
|
||||
analyser.room_pos = 8
|
||||
analyser.button_text_raw = "参与抽奖"
|
||||
analyser._room_pos_to_title_map = {}
|
||||
analyser.click = MagicMock()
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.delay = MagicMock()
|
||||
|
||||
ok = attend_choujiang(analyser)
|
||||
|
||||
assert ok is False
|
||||
assert analyser.last_attend_fail_reason == "no_parallel_ocr_result"
|
||||
analyser.click.assert_called_once_with(*DETAIL_OUTSIDE_CLICK)
|
||||
|
||||
|
||||
def test_attend_choujiang_can_recover_button_text_from_room_title_map() -> None:
|
||||
analyser = MagicMock()
|
||||
analyser._fudai_button_status = None
|
||||
analyser._fudai_button_text = ""
|
||||
analyser._fudai_button_ocr_time = 0.0
|
||||
analyser._fudai_button_room_pos = 0
|
||||
analyser.room_pos = 8
|
||||
analyser.current_room_title = "测试直播间"
|
||||
analyser.current_room_title_raw = "测试直播间原始"
|
||||
analyser.button_text_raw = None
|
||||
analyser._room_pos_to_title_map = {
|
||||
3: {
|
||||
"title": "测试直播间",
|
||||
"title_raw": "测试直播间原始",
|
||||
"fudai_detail": {"button_text": "参与抽奖"},
|
||||
}
|
||||
}
|
||||
analyser.click = MagicMock()
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.delay = MagicMock()
|
||||
analyser.last_attend_fail_reason = ""
|
||||
|
||||
ok = attend_choujiang(analyser)
|
||||
|
||||
assert ok is True
|
||||
# “已参与”路径会点击关闭详情
|
||||
analyser.click.assert_called_once()
|
||||
assert analyser._fudai_button_status == "可以参与"
|
||||
assert analyser._fudai_button_text == "参与抽奖"
|
||||
|
||||
|
||||
def test_attend_choujiang_debug_json_is_best_effort(monkeypatch, tmp_path: Path) -> None:
|
||||
analyser = MagicMock()
|
||||
analyser._fudai_button_status = "可以参与"
|
||||
analyser._fudai_button_text = "参与抽奖"
|
||||
analyser._fudai_button_ocr_time = 40_000.0
|
||||
analyser._fudai_button_room_pos = 0
|
||||
analyser.room_pos = 0
|
||||
analyser._current_fudai_future_ts = MagicMock()
|
||||
analyser.click = MagicMock()
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.delay = MagicMock()
|
||||
|
||||
debug_log = tmp_path / "debug.log"
|
||||
monkeypatch.setattr(
|
||||
"douyin.core.path_config.get_debug_log_path",
|
||||
lambda: str(debug_log),
|
||||
)
|
||||
|
||||
import time as _time
|
||||
|
||||
old_time = _time.time
|
||||
_time.time = lambda: 40_001.0
|
||||
try:
|
||||
ok = attend_choujiang(analyser)
|
||||
finally:
|
||||
_time.time = old_time
|
||||
|
||||
assert ok is True
|
||||
@@ -1,7 +1,33 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from douyin.fudai.douyin_fudai_core_pkg.button_state import decide_button_status
|
||||
from types import SimpleNamespace
|
||||
|
||||
from douyin.fudai.douyin_fudai_core_pkg.button_state import (
|
||||
apply_button_ocr_result,
|
||||
decide_button_status,
|
||||
)
|
||||
|
||||
|
||||
def test_decide_button_status_attended_for_notice_text() -> None:
|
||||
assert decide_button_status("直播间,否则会失去抽奖机会") == "已参与"
|
||||
|
||||
|
||||
def test_apply_button_ocr_result_records_room_pos_when_enabled() -> None:
|
||||
analyser = SimpleNamespace(room_pos=12)
|
||||
analyser._log_kv = lambda *args, **kwargs: None
|
||||
|
||||
apply_button_ocr_result(
|
||||
analyser,
|
||||
button_text_raw="参与抽奖",
|
||||
button_status="可以参与",
|
||||
fudai_content_raw="内容",
|
||||
task_list_raw="任务",
|
||||
countdown_mm_raw="01",
|
||||
countdown_ss_raw="30",
|
||||
value_raw="500",
|
||||
live_room_title_raw="直播间A",
|
||||
log_prefix="测试",
|
||||
record_room_pos=True,
|
||||
)
|
||||
|
||||
assert analyser._fudai_button_room_pos == 12
|
||||
@@ -0,0 +1,60 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def test_fudai_detail_debug_overview_saves_one_annotated_image(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.fudai.core import fudai_debug_utils
|
||||
|
||||
screenshot = tmp_path / "screenshot.png"
|
||||
Image.new("RGB", (1080, 2400), "white").save(screenshot)
|
||||
saved = []
|
||||
|
||||
def fake_save_debug_image(image, **kwargs):
|
||||
saved.append((image.copy(), kwargs))
|
||||
return str(tmp_path / "overview.png")
|
||||
|
||||
monkeypatch.setattr(path_config, "get_screenshot_path", lambda: str(screenshot))
|
||||
monkeypatch.setattr(
|
||||
"douyin.handlers.douyin_screenshot_manager.save_debug_image",
|
||||
fake_save_debug_image,
|
||||
)
|
||||
|
||||
analyser = SimpleNamespace(
|
||||
resolution_ratio_x=1080,
|
||||
resolution_ratio_y=2400,
|
||||
_log_kv=lambda *args, **kwargs: None,
|
||||
)
|
||||
|
||||
result = fudai_debug_utils.save_fudai_detail_debug_overview(
|
||||
analyser,
|
||||
[
|
||||
{
|
||||
"key": "content",
|
||||
"name": "内容",
|
||||
"coords": (300, 1400, 1030, 1515),
|
||||
"enabled": True,
|
||||
},
|
||||
{
|
||||
"key": "participants",
|
||||
"name": "人数",
|
||||
"coords": (520, 1325, 760, 1415),
|
||||
"enabled": False,
|
||||
},
|
||||
],
|
||||
ui_version="v2_0",
|
||||
ocr_enabled={"content"},
|
||||
task_count=1,
|
||||
task_count_source="v2_pixels",
|
||||
)
|
||||
|
||||
assert result
|
||||
assert len(saved) == 1
|
||||
_image, kwargs = saved[0]
|
||||
assert kwargs["picname"] == "福袋详情综合标注"
|
||||
assert kwargs["step"] == "detail_regions"
|
||||
assert kwargs["annotate"] is False
|
||||
assert kwargs["extra_info"]["ui_version"] == "v2_0"
|
||||
@@ -0,0 +1,241 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def test_v2_profile_keeps_legacy_and_adds_expected_regions():
|
||||
from douyin.fudai.core.coords import (
|
||||
DETAIL_UI_LEGACY,
|
||||
DETAIL_UI_V2_0,
|
||||
DETAIL_UI_V2_0_ONE_TASK,
|
||||
get_fudai_detail_profile,
|
||||
)
|
||||
|
||||
legacy = get_fudai_detail_profile("legacy")
|
||||
v2 = get_fudai_detail_profile("v2_0", task_count=2)
|
||||
auto = get_fudai_detail_profile("auto", task_count=2)
|
||||
one_task = get_fudai_detail_profile("v2_0", task_count=1)
|
||||
|
||||
assert legacy is DETAIL_UI_LEGACY
|
||||
assert v2 is DETAIL_UI_V2_0
|
||||
assert auto is DETAIL_UI_V2_0
|
||||
assert one_task is DETAIL_UI_V2_0_ONE_TASK
|
||||
assert DETAIL_UI_LEGACY["content"] == (389, 1273, 1000, 1534)
|
||||
assert DETAIL_UI_V2_0["content"] == (360, 1472, 1035, 1545)
|
||||
assert DETAIL_UI_V2_0["value"] == (300, 1585, 650, 1685)
|
||||
assert DETAIL_UI_V2_0["countdown_full"] == (760, 1355, 1035, 1455)
|
||||
assert DETAIL_UI_V2_0["task_list"] == (60, 1840, 1030, 2005)
|
||||
assert DETAIL_UI_V2_0["task_count"] == (860, 1770, 1035, 1875)
|
||||
assert DETAIL_UI_V2_0["participants"] == (520, 1325, 760, 1415)
|
||||
assert DETAIL_UI_V2_0["button"] == (70, 2020, 1010, 2165)
|
||||
assert DETAIL_UI_V2_0_ONE_TASK["content"] == (360, 1472, 1035, 1545)
|
||||
assert DETAIL_UI_V2_0_ONE_TASK["value"] == (340, 1680, 690, 1765)
|
||||
assert DETAIL_UI_V2_0_ONE_TASK["countdown_full"] == (760, 1355, 1035, 1455)
|
||||
assert DETAIL_UI_V2_0_ONE_TASK["task_list"] == (55, 1935, 900, 2055)
|
||||
assert DETAIL_UI_V2_0_ONE_TASK["task_count"] == (890, 1855, 1040, 1950)
|
||||
assert DETAIL_UI_V2_0_ONE_TASK["participants"] == (535, 1375, 760, 1475)
|
||||
assert DETAIL_UI_V2_0_ONE_TASK["button"] == (70, 2055, 1010, 2225)
|
||||
assert DETAIL_UI_V2_0_ONE_TASK["task_list"][1] > DETAIL_UI_V2_0["task_list"][1]
|
||||
assert DETAIL_UI_V2_0_ONE_TASK["button"][1] > DETAIL_UI_V2_0["button"][1]
|
||||
|
||||
|
||||
def test_ocr_switch_defaults_and_legacy_disable_compat():
|
||||
from douyin.fudai.douyin_fudai_core_pkg.ocr_switches import (
|
||||
FudaiDetailOcrSwitches,
|
||||
resolve_fudai_detail_ocr_switches,
|
||||
)
|
||||
|
||||
defaults = resolve_fudai_detail_ocr_switches({})
|
||||
assert defaults == FudaiDetailOcrSwitches(
|
||||
content=True,
|
||||
value=True,
|
||||
countdown=True,
|
||||
task=True,
|
||||
task_count=True,
|
||||
button=True,
|
||||
participants=False,
|
||||
live_title=True,
|
||||
)
|
||||
|
||||
legacy = resolve_fudai_detail_ocr_switches(
|
||||
{
|
||||
"fudai_disable_content_recognition": True,
|
||||
"fudai_disable_task_recognition": True,
|
||||
}
|
||||
)
|
||||
assert legacy.content is False
|
||||
assert legacy.task is False
|
||||
assert legacy.value is True
|
||||
|
||||
explicit = resolve_fudai_detail_ocr_switches(
|
||||
{
|
||||
"fudai_disable_content_recognition": True,
|
||||
"fudai_detail_ocr_content_enabled": True,
|
||||
"fudai_detail_ocr_participants_enabled": True,
|
||||
}
|
||||
)
|
||||
assert explicit.content is True
|
||||
assert explicit.participants is True
|
||||
|
||||
|
||||
def test_static_config_defaults_include_v2_ocr_keys():
|
||||
cfg = json.loads(open("config/config.json", encoding="utf-8").read())
|
||||
|
||||
assert cfg["fudai_detail_ui_mode"] == "auto"
|
||||
assert cfg["fudai_detail_ocr_content_enabled"] is True
|
||||
assert cfg["fudai_detail_ocr_value_enabled"] is True
|
||||
assert cfg["fudai_detail_ocr_countdown_enabled"] is True
|
||||
assert cfg["fudai_detail_ocr_task_enabled"] is True
|
||||
assert cfg["fudai_detail_ocr_task_count_enabled"] is True
|
||||
assert cfg["fudai_detail_ocr_button_enabled"] is True
|
||||
assert cfg["fudai_detail_ocr_participants_enabled"] is False
|
||||
assert cfg["fudai_detail_ocr_live_title_enabled"] is True
|
||||
|
||||
|
||||
def test_config_manager_loads_fudai_detail_ui_and_ocr_switches(tmp_path):
|
||||
from douyin.utils.douyin_config import ConfigManager
|
||||
|
||||
cfg_path = tmp_path / "config.json"
|
||||
cfg_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"fudai_detail_ui_mode": "legacy",
|
||||
"fudai_detail_ocr_content_enabled": False,
|
||||
"fudai_detail_ocr_button_enabled": True,
|
||||
"fudai_detail_ocr_participants_enabled": True,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
analyser = SimpleNamespace(config_path=str(cfg_path), needswitch=None)
|
||||
|
||||
ConfigManager.load_config_from_file(analyser, str(cfg_path))
|
||||
|
||||
assert analyser.fudai_detail_ui_mode == "legacy"
|
||||
assert analyser.fudai_detail_ocr_content_enabled is False
|
||||
assert analyser.fudai_detail_ocr_button_enabled is True
|
||||
assert analyser.fudai_detail_ocr_participants_enabled is True
|
||||
|
||||
|
||||
def test_v2_task_count_ocr_tries_one_task_shifted_region_first():
|
||||
from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2
|
||||
|
||||
calls = []
|
||||
|
||||
class _Operation:
|
||||
def analyse_pic_word(self, name, _mode):
|
||||
calls.append(name)
|
||||
if name == "福袋任务数量_v2_1task":
|
||||
return "(0/1)"
|
||||
return ""
|
||||
|
||||
def analyse_pic_digits(self, name, _mode):
|
||||
calls.append(name)
|
||||
return ""
|
||||
|
||||
class _Analyser:
|
||||
y_pianyi = 0
|
||||
operation = _Operation()
|
||||
|
||||
def cut_pic(self, x1, y1, x2, y2, _prefix, name, _offset):
|
||||
calls.append((name, (x1, y1, x2, y2)))
|
||||
|
||||
def _log_kv(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
assert _check_detail_task_count_v2(_Analyser()) == 1
|
||||
assert ("福袋任务数量_v2_1task", (890, 1855, 1040, 1950)) in calls
|
||||
assert "福袋任务数量_v2" not in calls
|
||||
|
||||
|
||||
def test_v2_task_count_pixels_choose_one_task_before_ocr(tmp_path, monkeypatch):
|
||||
from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2_pixels
|
||||
|
||||
screenshot_path = tmp_path / "one_task.png"
|
||||
img = Image.new("RGB", (1080, 2400), (10, 15, 46))
|
||||
img.putpixel((536, 1970), (255, 255, 255))
|
||||
img.save(screenshot_path)
|
||||
monkeypatch.setattr(
|
||||
"douyin.core.path_config.get_screenshot_path",
|
||||
lambda: str(screenshot_path),
|
||||
)
|
||||
|
||||
analyser = SimpleNamespace(
|
||||
fudai_detail_ui_mode="auto",
|
||||
resolution_ratio_x=1080,
|
||||
resolution_ratio_y=2400,
|
||||
_log_kv=lambda *_args, **_kwargs: None,
|
||||
)
|
||||
|
||||
assert _check_detail_task_count_v2_pixels(analyser) == 1
|
||||
assert analyser._fudai_detail_task_count_source == "v2_pixels"
|
||||
|
||||
|
||||
def test_v2_task_count_pixels_choose_two_task_from_dark_card(tmp_path, monkeypatch):
|
||||
from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2_pixels
|
||||
|
||||
screenshot_path = tmp_path / "two_task.png"
|
||||
img = Image.new("RGB", (1080, 2400), (10, 15, 46))
|
||||
img.save(screenshot_path)
|
||||
monkeypatch.setattr(
|
||||
"douyin.core.path_config.get_screenshot_path",
|
||||
lambda: str(screenshot_path),
|
||||
)
|
||||
|
||||
analyser = SimpleNamespace(
|
||||
fudai_detail_ui_mode="v2_0",
|
||||
resolution_ratio_x=1080,
|
||||
resolution_ratio_y=2400,
|
||||
_log_kv=lambda *_args, **_kwargs: None,
|
||||
)
|
||||
|
||||
assert _check_detail_task_count_v2_pixels(analyser) == 2
|
||||
|
||||
|
||||
def test_v2_task_count_pixels_disabled_for_legacy(tmp_path, monkeypatch):
|
||||
from douyin.detection.detection_pkg.detail import _check_detail_task_count_v2_pixels
|
||||
|
||||
screenshot_path = tmp_path / "legacy.png"
|
||||
Image.new("RGB", (1080, 2400), (255, 255, 255)).save(screenshot_path)
|
||||
monkeypatch.setattr(
|
||||
"douyin.core.path_config.get_screenshot_path",
|
||||
lambda: str(screenshot_path),
|
||||
)
|
||||
|
||||
analyser = SimpleNamespace(
|
||||
fudai_detail_ui_mode="legacy",
|
||||
resolution_ratio_x=1080,
|
||||
resolution_ratio_y=2400,
|
||||
)
|
||||
|
||||
assert _check_detail_task_count_v2_pixels(analyser) == 0
|
||||
|
||||
|
||||
def test_check_detail_height_v2_does_not_fallback_to_legacy_pixels(monkeypatch):
|
||||
from douyin.detection.detection_pkg import detail
|
||||
|
||||
monkeypatch.setattr(detail, "_check_detail_task_count_v2_pixels", lambda _analyser: 0)
|
||||
monkeypatch.setattr(detail, "_check_detail_task_count_v2", lambda _analyser: 0)
|
||||
|
||||
def _legacy_should_not_run(_analyser):
|
||||
raise AssertionError("v2 mode must not fallback to legacy pixel detection")
|
||||
|
||||
monkeypatch.setattr(detail, "_check_detail_task_count_legacy_pixels", _legacy_should_not_run)
|
||||
|
||||
analyser = SimpleNamespace(fudai_detail_ui_mode="v2_0")
|
||||
|
||||
assert detail.check_detail_height(analyser) == 0
|
||||
|
||||
|
||||
def test_check_detail_height_legacy_uses_legacy_pixels(monkeypatch):
|
||||
from douyin.detection.detection_pkg import detail
|
||||
|
||||
monkeypatch.setattr(detail, "_check_detail_task_count_legacy_pixels", lambda _analyser: 3)
|
||||
|
||||
analyser = SimpleNamespace(fudai_detail_ui_mode="legacy")
|
||||
|
||||
assert detail.check_detail_height(analyser) == 3
|
||||
@@ -103,7 +103,7 @@ class TestShouldSkipFudaiByConfig:
|
||||
|
||||
def test_high_value_passes(self):
|
||||
analyser = self._mock()
|
||||
detail = ('现金1000元', '2分钟', 50, 1, 1000.0,
|
||||
detail = ('现金1000元', '02:00', 50, 1, 1000.0,
|
||||
(time.time()+120, time.time()+120))
|
||||
skip, reason = should_skip_fudai_by_config(analyser, detail)
|
||||
assert skip is False
|
||||
@@ -119,14 +119,14 @@ class TestShouldSkipFudaiByConfig:
|
||||
|
||||
def test_low_value_skips(self):
|
||||
analyser = self._mock(min_prize_value_yuan=500.0)
|
||||
detail = ('现金100元', '2分钟', 50, 1, 100.0,
|
||||
detail = ('现金100元', '02:00', 50, 1, 100.0,
|
||||
(time.time()+120, time.time()+120))
|
||||
skip, _ = should_skip_fudai_by_config(analyser, detail)
|
||||
assert skip is True
|
||||
|
||||
def test_blacklist_skips(self):
|
||||
analyser = self._mock(contains_not_want=["袜子"])
|
||||
detail = ('袜子礼盒', '2分钟', 50, 1, 500.0,
|
||||
detail = ('袜子礼盒', '02:00', 50, 1, 500.0,
|
||||
(time.time()+120, time.time()+120))
|
||||
skip, _ = should_skip_fudai_by_config(analyser, detail)
|
||||
assert skip is True
|
||||
@@ -134,7 +134,7 @@ class TestShouldSkipFudaiByConfig:
|
||||
def test_single_room_mode_passes_always(self):
|
||||
# needswitch=False 时不论价值都不跳过
|
||||
analyser = self._mock(needswitch=False, min_prize_value_yuan=1e9)
|
||||
detail = ('现金1元', '2分钟', 50, 1, 1.0,
|
||||
detail = ('现金1元', '02:00', 50, 1, 1.0,
|
||||
(time.time()+120, time.time()+120))
|
||||
skip, reason = should_skip_fudai_by_config(analyser, detail)
|
||||
assert skip is False
|
||||
|
||||
+166
-2
@@ -6,7 +6,10 @@ adb 真实命令 / wifi_adb 涉及网络与设备,仅做"可调用 + 不抛"
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -30,9 +33,9 @@ class TestRunParams:
|
||||
assert dataclasses.is_dataclass(RunParams)
|
||||
|
||||
def test_field_count(self):
|
||||
# RunParams 当前有 28 个字段(与拆分时一致)
|
||||
# RunParams 字段会随配置扩展增加,至少应保留原核心字段数量。
|
||||
fields = dataclasses.fields(RunParams)
|
||||
assert len(fields) == 28
|
||||
assert len(fields) >= 28
|
||||
|
||||
def test_field_types(self):
|
||||
"""关键字段的类型注解。"""
|
||||
@@ -108,6 +111,33 @@ class TestReadConfig:
|
||||
assert cfg1 == cfg2
|
||||
|
||||
|
||||
class TestFudaiDetailOcrGuiConfig:
|
||||
def test_build_config_vars_exposes_fudai_detail_ocr_switches(self, monkeypatch):
|
||||
import tkinter as tk
|
||||
|
||||
from gui.components.config_vars import build_config_vars
|
||||
|
||||
monkeypatch.setattr(tk, "StringVar", lambda value="": MagicMock(get=lambda: value, set=lambda _v: None))
|
||||
monkeypatch.setattr(tk, "BooleanVar", lambda value=False: MagicMock(get=lambda: value, set=lambda _v: None))
|
||||
monkeypatch.setattr(tk, "IntVar", lambda value=0: MagicMock(get=lambda: value, set=lambda _v: None))
|
||||
monkeypatch.setattr(tk, "DoubleVar", lambda value=0.0: MagicMock(get=lambda: value, set=lambda _v: None))
|
||||
|
||||
vars_ = build_config_vars({})
|
||||
|
||||
for key in (
|
||||
"fudai_detail_ui_mode_var",
|
||||
"fudai_detail_ocr_content_enabled_var",
|
||||
"fudai_detail_ocr_value_enabled_var",
|
||||
"fudai_detail_ocr_countdown_enabled_var",
|
||||
"fudai_detail_ocr_task_enabled_var",
|
||||
"fudai_detail_ocr_task_count_enabled_var",
|
||||
"fudai_detail_ocr_button_enabled_var",
|
||||
"fudai_detail_ocr_participants_enabled_var",
|
||||
"fudai_detail_ocr_live_title_enabled_var",
|
||||
):
|
||||
assert key in vars_
|
||||
|
||||
|
||||
class TestWriteConfig:
|
||||
def test_write_and_read_roundtrip(self):
|
||||
# 读出 → 写回(不改任何字段)→ 再读出,应一致
|
||||
@@ -117,6 +147,45 @@ class TestWriteConfig:
|
||||
# 至少键集相等(具体值可能因写入时序略有变动)
|
||||
assert set(original.keys()) == set(after.keys())
|
||||
|
||||
def test_write_config_merges_nested_dicts(self, tmp_path, monkeypatch):
|
||||
from gui.gui_core_pkg import config as cfg_mod
|
||||
|
||||
cfg_path = tmp_path / "config.json"
|
||||
cfg_path.write_text(
|
||||
json.dumps({"logging": {"keep_days": 7, "compress_logs": True}, "other": 1}, ensure_ascii=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setattr(cfg_mod, "CONFIG_PATH", str(cfg_path))
|
||||
|
||||
cfg_mod.write_config({"logging": {"keep_days": 3}})
|
||||
|
||||
saved = json.loads(cfg_path.read_text(encoding="utf-8"))
|
||||
assert saved["logging"]["keep_days"] == 3
|
||||
assert saved["logging"]["compress_logs"] is True
|
||||
assert saved["other"] == 1
|
||||
|
||||
def test_write_config_concurrent_updates_keep_both_keys(self, tmp_path, monkeypatch):
|
||||
from gui.gui_core_pkg import config as cfg_mod
|
||||
|
||||
cfg_path = tmp_path / "config.json"
|
||||
cfg_path.write_text(json.dumps({"base": 1}, ensure_ascii=False), encoding="utf-8")
|
||||
monkeypatch.setattr(cfg_mod, "CONFIG_PATH", str(cfg_path))
|
||||
|
||||
def _writer(payload):
|
||||
cfg_mod.write_config(payload)
|
||||
|
||||
t1 = threading.Thread(target=_writer, args=({"alpha": 1},), daemon=True)
|
||||
t2 = threading.Thread(target=_writer, args=({"beta": 2},), daemon=True)
|
||||
t1.start()
|
||||
t2.start()
|
||||
t1.join(timeout=1)
|
||||
t2.join(timeout=1)
|
||||
|
||||
saved = json.loads(cfg_path.read_text(encoding="utf-8"))
|
||||
assert saved["base"] == 1
|
||||
assert saved["alpha"] == 1
|
||||
assert saved["beta"] == 2
|
||||
|
||||
|
||||
# ============================================================
|
||||
# adb.py — find_adb_executable / list_adb_devices / resolve_adb_device
|
||||
@@ -142,3 +211,98 @@ class TestAdbFunctions:
|
||||
# 指定了不存在的 device_id 应抛 RuntimeError
|
||||
with pytest.raises(RuntimeError):
|
||||
resolve_adb_device("", "nonexistent_device_xyz")
|
||||
|
||||
|
||||
class TestWifiAdbDialog:
|
||||
def test_open_wifi_adb_dialog_binds_toggle_button_without_nameerror(self, monkeypatch):
|
||||
from gui.components import wifi_adb_dialog as mod
|
||||
|
||||
class _FakeWidget:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
self.configs = {}
|
||||
|
||||
def pack(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
def grid(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
def grid_columnconfigure(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
def grid_rowconfigure(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
def config(self, **kwargs):
|
||||
self.configs.update(kwargs)
|
||||
|
||||
configure = config
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
self.configs[key] = value
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self.configs[key]
|
||||
|
||||
class _FakeDialog(_FakeWidget):
|
||||
def title(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
def geometry(self, *_args, **_kwargs):
|
||||
return "500x450"
|
||||
|
||||
def resizable(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
def minsize(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
def grid_columnconfigure(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
def update_idletasks(self):
|
||||
return None
|
||||
|
||||
def winfo_screenwidth(self):
|
||||
return 1000
|
||||
|
||||
def winfo_screenheight(self):
|
||||
return 800
|
||||
|
||||
def destroy(self):
|
||||
return None
|
||||
|
||||
created_buttons = []
|
||||
|
||||
def _fake_button(*args, **kwargs):
|
||||
created_buttons.append(kwargs)
|
||||
return _FakeWidget(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(mod.tk, "Toplevel", lambda parent: _FakeDialog(parent))
|
||||
monkeypatch.setattr(mod.ttk, "LabelFrame", _FakeWidget)
|
||||
monkeypatch.setattr(mod.ttk, "Frame", _FakeWidget)
|
||||
monkeypatch.setattr(mod.ttk, "Label", _FakeWidget)
|
||||
monkeypatch.setattr(mod.ttk, "Combobox", _FakeWidget)
|
||||
monkeypatch.setattr(mod.ttk, "Entry", _FakeWidget)
|
||||
monkeypatch.setattr(mod.ttk, "Button", _fake_button)
|
||||
monkeypatch.setattr(
|
||||
mod.tk,
|
||||
"StringVar",
|
||||
lambda value="": MagicMock(get=lambda: value, set=lambda _v: None),
|
||||
)
|
||||
monkeypatch.setattr(mod, "list_adb_devices", lambda _adb: [])
|
||||
monkeypatch.setattr(mod, "get_connected_wifi_devices", lambda _adb: [])
|
||||
|
||||
mod.open_wifi_adb_dialog(
|
||||
MagicMock(),
|
||||
adb_exe="adb",
|
||||
on_line=lambda _msg: None,
|
||||
refresh_devices=lambda: None,
|
||||
)
|
||||
|
||||
assert any(
|
||||
btn.get("text") == "放大/恢复" and callable(btn.get("command"))
|
||||
for btn in created_buttons
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from douyin.core.fudai_modules import handle_detail_filter as hdf
|
||||
|
||||
|
||||
def _mk_self():
|
||||
s = MagicMock()
|
||||
s._log_kv = MagicMock(return_value=None)
|
||||
s.high_value_fudai_enabled = True
|
||||
s.high_value_fudai_threshold_yuan = 500.0
|
||||
s.high_value_fudai_join_ahead_seconds = 100
|
||||
return s
|
||||
|
||||
|
||||
def test_high_value_reservation_failure_falls_back_to_still_skip():
|
||||
s = _mk_self()
|
||||
future_ts = time.time() + 600
|
||||
detail = ("高价值福袋", 0, 0, 0, 1000.0, (time.time(), future_ts, 600))
|
||||
|
||||
with patch(
|
||||
"douyin.fudai.douyin_fudai_core.basic_join_decision",
|
||||
side_effect=RuntimeError("record failed"),
|
||||
):
|
||||
result = hdf.try_high_value_reservation(
|
||||
s, detail, True, "countdown_gt_30", 0.0
|
||||
)
|
||||
|
||||
assert result == "still_skip"
|
||||
@@ -330,6 +330,21 @@ class TestPrepareForAttend:
|
||||
assert result == 0.0
|
||||
|
||||
|
||||
# ============================================================
|
||||
# check_invalid_detail_fallback
|
||||
# ============================================================
|
||||
|
||||
class TestCheckInvalidDetailFallback:
|
||||
def test_invalid_detail_clears_first_read_and_cached_tuple(self):
|
||||
s = _mk_self()
|
||||
s._fudai_detail_first_read = True
|
||||
s._last_fudai_detail_tuple = ("stale",)
|
||||
detail = ("", "", 0, 0, 0.0, (0, 0, 0))
|
||||
assert hd.check_invalid_detail_fallback(s, detail, 0.0) is True
|
||||
assert s._fudai_detail_first_read is False
|
||||
assert s._last_fudai_detail_tuple is None
|
||||
|
||||
|
||||
# ============================================================
|
||||
# check_last_status_branch
|
||||
# ============================================================
|
||||
@@ -360,16 +375,19 @@ class TestCheckLastStatusBranch:
|
||||
s = self._mk_for_status("coupon_popup")
|
||||
assert hd.check_last_status_branch(s, 0.0) is True
|
||||
assert s._fudai_detail_task_count_from_stage is None
|
||||
assert s._last_fudai_detail_status == ""
|
||||
|
||||
def test_watch_task_returns_true_clears_task_count(self):
|
||||
s = self._mk_for_status("watch_task")
|
||||
assert hd.check_last_status_branch(s, 0.0) is True
|
||||
assert s._fudai_detail_task_count_from_stage is None
|
||||
assert s._last_fudai_detail_status == ""
|
||||
|
||||
def test_validation_failed_returns_true_clears_task_count(self):
|
||||
s = self._mk_for_status("validation_failed")
|
||||
assert hd.check_last_status_branch(s, 0.0) is True
|
||||
assert s._fudai_detail_task_count_from_stage is None
|
||||
assert s._last_fudai_detail_status == ""
|
||||
|
||||
def test_error_without_task_count_zero_reason_returns_false(self):
|
||||
"""error 但 reason 不是 task_count_zero → 不在此处理。"""
|
||||
@@ -386,6 +404,21 @@ class TestCheckLastStatusBranch:
|
||||
assert result is True
|
||||
assert s._fudai_detail_consecutive_failures == 1
|
||||
s.swipe_up_to_next_live.assert_not_called()
|
||||
assert s._last_fudai_detail_status == ""
|
||||
assert s._last_fudai_detail_extra == {}
|
||||
|
||||
def test_error_not_in_fudai_detail_first_failure(self):
|
||||
"""read_once 返回的 not_in_fudai_detail 也应走同一条连续失败保护。"""
|
||||
s = self._mk_for_status("error", last_extra={"reason": "not_in_fudai_detail"})
|
||||
s._fudai_detail_consecutive_failures = 0
|
||||
s.swipe_up_to_next_live = MagicMock(return_value=None)
|
||||
with patch("douyin.fudai.douyin_fudai_detail.close_fudai_detail"):
|
||||
result = hd.check_last_status_branch(s, 0.0)
|
||||
assert result is True
|
||||
assert s._fudai_detail_consecutive_failures == 1
|
||||
s.swipe_up_to_next_live.assert_not_called()
|
||||
assert s._last_fudai_detail_status == ""
|
||||
assert s._last_fudai_detail_extra == {}
|
||||
|
||||
def test_error_task_count_zero_third_failure_swipes(self):
|
||||
"""task_count_zero 第 3 次:强制关详情 + 切直播间 + 重置计数。"""
|
||||
@@ -472,6 +505,8 @@ class TestHandleFirstOpenBranch:
|
||||
result = hd.handle_first_open_branch(s, 0.0)
|
||||
assert result is True
|
||||
mock_close.assert_called_once()
|
||||
assert s._fudai_detail_first_read is False
|
||||
assert s._last_fudai_detail_tuple is None
|
||||
|
||||
def test_filter_pass_saves_data_returns_false(self):
|
||||
"""筛选通过 → 保存 detail + 标记 first_read,return False 让 caller 继续。"""
|
||||
@@ -495,6 +530,27 @@ class TestHandleFirstOpenBranch:
|
||||
assert s._fudai_detail_first_read is True
|
||||
assert s._current_fudai_content == "有效福袋"
|
||||
|
||||
def test_special_status_does_not_mark_first_read(self):
|
||||
"""若 read_with_retries 已产出终止类状态,不应把详情误标成 second-open。"""
|
||||
import time
|
||||
|
||||
s = self._mk_for_first_open()
|
||||
s._last_fudai_detail_status = "watch_task"
|
||||
detail = ("X", 0, 0, 0, 100.0, (0, time.time() + 60, 60))
|
||||
with patch(
|
||||
"douyin.fudai.douyin_fudai_detail.read_fudai_detail_with_retries",
|
||||
return_value=detail,
|
||||
), patch(
|
||||
"douyin.fudai.douyin_fudai_detail.validate_fudai_detail",
|
||||
return_value=(True, ""),
|
||||
), patch(
|
||||
"douyin.fudai.douyin_fudai_core.should_skip_fudai_by_config",
|
||||
return_value=(False, ""),
|
||||
):
|
||||
result = hd.handle_first_open_branch(s, 0.0)
|
||||
assert result is False
|
||||
assert s._fudai_detail_first_read is False
|
||||
|
||||
def test_filter_skip_normal_closes_and_swipes(self):
|
||||
"""普通筛选不通过(非高价值)→ 关详情 + 切直播间 + return True。"""
|
||||
import time
|
||||
@@ -518,6 +574,8 @@ class TestHandleFirstOpenBranch:
|
||||
assert result is True
|
||||
mock_close.assert_called_once()
|
||||
s.swipe_up_to_next_live.assert_called_once()
|
||||
assert s._fudai_detail_first_read is False
|
||||
assert s._last_fudai_detail_tuple is None
|
||||
|
||||
def test_filter_skip_no_switch_when_needswitch_false(self):
|
||||
"""needswitch=False 筛选不通过时不切直播间。"""
|
||||
@@ -629,6 +687,19 @@ class TestHandleSecondOpenBranch:
|
||||
assert s._last_fudai_detail_tuple == new_detail
|
||||
assert s._current_fudai_content == "X"
|
||||
|
||||
def test_refetch_special_status_clears_first_read_flag(self):
|
||||
"""第二次打开重读后若状态已终止,不应继续保留 second-open 标志。"""
|
||||
s = self._mk_for_second_open()
|
||||
s._last_fudai_detail_tuple = None
|
||||
s._last_fudai_detail_status = "watch_task"
|
||||
with patch(
|
||||
"douyin.fudai.douyin_fudai_detail.read_fudai_detail_with_retries",
|
||||
return_value=("X", 0, 0, 0, 100.0, (0, 60.0, 60)),
|
||||
):
|
||||
result = hd.handle_second_open_branch(s, 0.0, 0.0)
|
||||
assert result is False
|
||||
assert s._fudai_detail_first_read is False
|
||||
|
||||
def test_short_tuple_triggers_refetch(self):
|
||||
"""缓存 tuple 长度 < 6 → 触发重新读取。"""
|
||||
s = self._mk_for_second_open()
|
||||
@@ -640,6 +711,19 @@ class TestHandleSecondOpenBranch:
|
||||
result = hd.handle_second_open_branch(s, 0.0, 0.0)
|
||||
assert result is False
|
||||
mock_read.assert_called_once()
|
||||
assert s._fudai_detail_first_read is False
|
||||
|
||||
def test_refetch_invalid_detail_clears_first_read_flag(self):
|
||||
"""第二次打开重读后仍拿不到有效 detail,不应无限保留 second-open 状态。"""
|
||||
s = self._mk_for_second_open()
|
||||
s._last_fudai_detail_tuple = None
|
||||
with patch(
|
||||
"douyin.fudai.douyin_fudai_detail.read_fudai_detail_with_retries",
|
||||
return_value=None,
|
||||
):
|
||||
result = hd.handle_second_open_branch(s, 0.0, 0.0)
|
||||
assert result is False
|
||||
assert s._fudai_detail_first_read is False
|
||||
|
||||
def test_attend_success_returns_true_clears_failures(self):
|
||||
"""attend_choujiang 成功 → 清标志 + 清失败计数 + return True。"""
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
|
||||
def test_save_high_value_rooms_is_atomic(tmp_path, monkeypatch):
|
||||
from douyin.other import douyin_high_value_room as mod
|
||||
|
||||
target = tmp_path / "high_value_rooms.json"
|
||||
monkeypatch.setattr(mod, "HIGH_VALUE_ROOMS_PATH", target)
|
||||
|
||||
mod._save_high_value_rooms({"updated_ts": 1, "total": 0, "rooms": []})
|
||||
|
||||
data = json.loads(target.read_text(encoding="utf-8"))
|
||||
assert data["updated_ts"] == 1
|
||||
assert data["rooms"] == []
|
||||
assert not target.with_suffix(target.suffix + ".tmp").exists()
|
||||
@@ -159,3 +159,191 @@ class TestKeyExports:
|
||||
"_safe_replace_file",
|
||||
):
|
||||
assert hasattr(operations, name), f"operations 包缺少导出 {name}"
|
||||
|
||||
def test_operations_package_import_tolerates_missing_optional_runtime_deps(self, monkeypatch):
|
||||
"""operations 包在缺少 Pillow 这类可安装依赖时,不应因为 eager import 直接炸掉。"""
|
||||
import sys
|
||||
|
||||
to_drop = [k for k in list(sys.modules) if k == "operations" or k.startswith("operations.")]
|
||||
saved = {k: sys.modules[k] for k in to_drop}
|
||||
for key in to_drop:
|
||||
sys.modules.pop(key, None)
|
||||
|
||||
real_import = __import__
|
||||
|
||||
def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002
|
||||
if name == "PIL" or name.startswith("PIL."):
|
||||
raise ModuleNotFoundError("No module named 'PIL'")
|
||||
return real_import(name, globals, locals, fromlist, level)
|
||||
|
||||
monkeypatch.setattr("builtins.__import__", fake_import)
|
||||
try:
|
||||
mod = importlib.import_module("operations")
|
||||
assert hasattr(mod, "analyse_pic_word")
|
||||
finally:
|
||||
sys.modules.pop("operations", None)
|
||||
for key in [k for k in list(sys.modules) if k.startswith("operations.")]:
|
||||
sys.modules.pop(key, None)
|
||||
sys.modules.update(saved)
|
||||
|
||||
def test_screenshot_service_import_tolerates_missing_pillow(self, monkeypatch):
|
||||
"""截图服务模块不应在 import 阶段强依赖 Pillow。"""
|
||||
import sys
|
||||
|
||||
to_drop = [k for k in list(sys.modules) if k == "operations" or k.startswith("operations.")]
|
||||
saved = {k: sys.modules[k] for k in to_drop}
|
||||
for key in to_drop:
|
||||
sys.modules.pop(key, None)
|
||||
|
||||
real_import = __import__
|
||||
|
||||
def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002
|
||||
if name == "PIL" or name.startswith("PIL."):
|
||||
raise ModuleNotFoundError("No module named 'PIL'")
|
||||
return real_import(name, globals, locals, fromlist, level)
|
||||
|
||||
monkeypatch.setattr("builtins.__import__", fake_import)
|
||||
try:
|
||||
mod = importlib.import_module("operations.screenshot_service")
|
||||
assert hasattr(mod, "ScreenshotService")
|
||||
finally:
|
||||
for key in [k for k in list(sys.modules) if k == "operations" or k.startswith("operations.")]:
|
||||
sys.modules.pop(key, None)
|
||||
sys.modules.update(saved)
|
||||
|
||||
def test_read_with_retries_import_tolerates_missing_pillow(self, monkeypatch):
|
||||
"""read_with_retries 作为高层重试入口,不应被 read_once 的 PIL 依赖卡死。"""
|
||||
import sys
|
||||
|
||||
prefixes = (
|
||||
"douyin.fudai.core.fudai_detail_orchestrator_pkg",
|
||||
"douyin.fudai.core.fudai_detail_orchestrator",
|
||||
)
|
||||
to_drop = [k for k in list(sys.modules) if k.startswith(prefixes)]
|
||||
saved = {k: sys.modules[k] for k in to_drop}
|
||||
for key in to_drop:
|
||||
sys.modules.pop(key, None)
|
||||
|
||||
real_import = __import__
|
||||
|
||||
def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002
|
||||
if name == "PIL" or name.startswith("PIL."):
|
||||
raise ModuleNotFoundError("No module named 'PIL'")
|
||||
return real_import(name, globals, locals, fromlist, level)
|
||||
|
||||
monkeypatch.setattr("builtins.__import__", fake_import)
|
||||
try:
|
||||
mod = importlib.import_module("douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries")
|
||||
assert hasattr(mod, "read_fudai_detail_with_retries")
|
||||
finally:
|
||||
for key in [k for k in list(sys.modules) if k.startswith(prefixes)]:
|
||||
sys.modules.pop(key, None)
|
||||
sys.modules.update(saved)
|
||||
|
||||
def test_read_with_retries_module_import_tolerates_missing_pillow(self, monkeypatch):
|
||||
"""read_with_retries 自身不应留下无用的 PIL 顶层依赖。"""
|
||||
import sys
|
||||
|
||||
prefixes = ("douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries",)
|
||||
to_drop = [k for k in list(sys.modules) if k.startswith(prefixes)]
|
||||
saved = {k: sys.modules[k] for k in to_drop}
|
||||
for key in to_drop:
|
||||
sys.modules.pop(key, None)
|
||||
|
||||
real_import = __import__
|
||||
|
||||
def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002
|
||||
if name == "PIL" or name.startswith("PIL."):
|
||||
raise ModuleNotFoundError("No module named 'PIL'")
|
||||
return real_import(name, globals, locals, fromlist, level)
|
||||
|
||||
monkeypatch.setattr("builtins.__import__", fake_import)
|
||||
try:
|
||||
mod = importlib.import_module("douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries")
|
||||
assert hasattr(mod, "read_fudai_detail_with_retries")
|
||||
finally:
|
||||
for key in [k for k in list(sys.modules) if k.startswith(prefixes)]:
|
||||
sys.modules.pop(key, None)
|
||||
sys.modules.update(saved)
|
||||
|
||||
def test_douyin_detection_import_tolerates_missing_pillow(self, monkeypatch):
|
||||
"""detection 包的顶层 shim 不应被 finder 的 PIL 依赖卡死。"""
|
||||
import sys
|
||||
|
||||
prefixes = (
|
||||
"douyin.detection.detection_pkg",
|
||||
"douyin.detection.douyin_detection",
|
||||
)
|
||||
to_drop = [k for k in list(sys.modules) if k.startswith(prefixes)]
|
||||
saved = {k: sys.modules[k] for k in to_drop}
|
||||
for key in to_drop:
|
||||
sys.modules.pop(key, None)
|
||||
|
||||
real_import = __import__
|
||||
|
||||
def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002
|
||||
if name == "PIL" or name.startswith("PIL."):
|
||||
raise ModuleNotFoundError("No module named 'PIL'")
|
||||
return real_import(name, globals, locals, fromlist, level)
|
||||
|
||||
monkeypatch.setattr("builtins.__import__", fake_import)
|
||||
try:
|
||||
mod = importlib.import_module("douyin.detection.douyin_detection")
|
||||
assert hasattr(mod, "check_have_fudai_with_ready_screenshot")
|
||||
finally:
|
||||
for key in [k for k in list(sys.modules) if k.startswith(prefixes)]:
|
||||
sys.modules.pop(key, None)
|
||||
sys.modules.update(saved)
|
||||
|
||||
def test_douyin_fudai_import_tolerates_missing_pillow(self, monkeypatch):
|
||||
"""douyin_fudai 主入口不应被若干调试/识别模块的 PIL 顶层导入卡死。"""
|
||||
import sys
|
||||
|
||||
prefixes = (
|
||||
"douyin.core.douyin_fudai",
|
||||
"douyin.detection",
|
||||
"douyin.fudai.core.fudai_debug_utils",
|
||||
)
|
||||
to_drop = [k for k in list(sys.modules) if k.startswith(prefixes)]
|
||||
saved = {k: sys.modules[k] for k in to_drop}
|
||||
for key in to_drop:
|
||||
sys.modules.pop(key, None)
|
||||
|
||||
real_import = __import__
|
||||
|
||||
def fake_import(name, globals=None, locals=None, fromlist=(), level=0): # noqa: A002
|
||||
if name == "PIL" or name.startswith("PIL."):
|
||||
raise ModuleNotFoundError("No module named 'PIL'")
|
||||
return real_import(name, globals, locals, fromlist, level)
|
||||
|
||||
monkeypatch.setattr("builtins.__import__", fake_import)
|
||||
try:
|
||||
mod = importlib.import_module("douyin.core.douyin_fudai")
|
||||
assert hasattr(mod, "fudai_analyse")
|
||||
finally:
|
||||
for key in [k for k in list(sys.modules) if k.startswith(prefixes)]:
|
||||
sys.modules.pop(key, None)
|
||||
sys.modules.update(saved)
|
||||
|
||||
def test_douyin_logging_import_chain_has_no_monitor_cycle(self):
|
||||
"""日志兼容入口不应再因为 monitor/config 相互导入而初始化失败。"""
|
||||
import sys
|
||||
|
||||
prefixes = (
|
||||
"douyin.logging.douyin_logging",
|
||||
"douyin.logging.douyin_logging_pkg",
|
||||
)
|
||||
to_drop = [k for k in list(sys.modules) if k.startswith(prefixes)]
|
||||
saved = {k: sys.modules[k] for k in to_drop}
|
||||
for key in to_drop:
|
||||
sys.modules.pop(key, None)
|
||||
|
||||
try:
|
||||
mod = importlib.import_module("douyin.logging.douyin_logging")
|
||||
assert hasattr(mod, "configure_logging")
|
||||
assert hasattr(mod, "start_log_monitor")
|
||||
assert hasattr(mod, "stop_log_monitor")
|
||||
finally:
|
||||
for key in [k for k in list(sys.modules) if k.startswith(prefixes)]:
|
||||
sys.modules.pop(key, None)
|
||||
sys.modules.update(saved)
|
||||
@@ -9,6 +9,7 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
@@ -120,3 +121,31 @@ def test_broken_analyser_does_not_raise(module_path, helper_name):
|
||||
fn = _import_helper(module_path, helper_name)
|
||||
# 不应抛任何异常
|
||||
fn(BrokenAnalyser(), "[test] broken", level="ERROR")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"module_path,helper_name",
|
||||
[
|
||||
("operations.screenshot_service", "_svc_log"),
|
||||
("operations.ocr_operations", "_ocr_log"),
|
||||
],
|
||||
)
|
||||
def test_logger_failure_falls_back_to_print(module_path, helper_name, monkeypatch):
|
||||
"""logger 自身异常时,helper 应直接兜底到 print,而不是递归调用自身。"""
|
||||
mod = importlib.import_module(module_path)
|
||||
fn = getattr(mod, helper_name)
|
||||
|
||||
class BrokenLogger:
|
||||
def info(self, *_args, **_kwargs):
|
||||
raise RuntimeError("logger broken")
|
||||
|
||||
warning = error = debug = info
|
||||
|
||||
printed: list[str] = []
|
||||
|
||||
monkeypatch.setattr(mod, "_LOGGER", BrokenLogger())
|
||||
monkeypatch.setattr("builtins.print", lambda msg: printed.append(str(msg)))
|
||||
|
||||
fn("[test] print fallback")
|
||||
|
||||
assert printed == ["[test] print fallback"]
|
||||
@@ -0,0 +1,87 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
||||
def test_lottery_result_ocr_uses_v2_confirm_region(monkeypatch):
|
||||
from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_BUTTON_V2
|
||||
from douyin.utils.douyin_helpers import HelperFunctions
|
||||
|
||||
calls = []
|
||||
|
||||
class _Operation:
|
||||
def analyse_pic_word(self, _name, _mode=0):
|
||||
return "我知道了"
|
||||
|
||||
analyser = SimpleNamespace(
|
||||
fudai_detail_ui_mode="v2_0",
|
||||
operation=_Operation(),
|
||||
_log_kv=lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"douyin.handlers.douyin_screenshot_handler.ScreenshotHandler.cut_pic",
|
||||
lambda _analyser, x1, y1, x2, y2, *_args: calls.append((x1, y1, x2, y2)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"douyin.utils.ocr_preprocess.preprocess_for_ocr",
|
||||
lambda _analyser, picname: picname,
|
||||
)
|
||||
|
||||
assert HelperFunctions.check_lottery_result_by_ocr(analyser) == "我知道了"
|
||||
assert calls == [LOTTERY_RESULT_CONFIRM_BUTTON_V2]
|
||||
|
||||
|
||||
def test_lottery_result_click_uses_v2_confirm_point():
|
||||
from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_CLICK_V2
|
||||
from douyin.utils.douyin_helpers import HelperFunctions
|
||||
|
||||
clicks = []
|
||||
|
||||
class _Operation:
|
||||
def click(self, _device_id, x, y):
|
||||
clicks.append((x, y))
|
||||
|
||||
def delay(self, _seconds):
|
||||
return None
|
||||
|
||||
analyser = SimpleNamespace(
|
||||
fudai_detail_ui_mode="v2_0",
|
||||
resolution_ratio_x=1080,
|
||||
resolution_ratio_y=2400,
|
||||
device_id="device",
|
||||
needswitch=False,
|
||||
operation=_Operation(),
|
||||
_log_kv=lambda *_args, **_kwargs: None,
|
||||
)
|
||||
|
||||
HelperFunctions.handle_lottery_result_by_ocr(analyser, "我知道了")
|
||||
|
||||
assert clicks[0] == LOTTERY_RESULT_CONFIRM_CLICK_V2
|
||||
|
||||
|
||||
def test_lottery_result_click_keeps_legacy_confirm_point():
|
||||
from douyin.fudai.core.coords import LOTTERY_RESULT_CONFIRM_CLICK_V1
|
||||
from douyin.utils.douyin_helpers import HelperFunctions
|
||||
|
||||
clicks = []
|
||||
|
||||
class _Operation:
|
||||
def click(self, _device_id, x, y):
|
||||
clicks.append((x, y))
|
||||
|
||||
def delay(self, _seconds):
|
||||
return None
|
||||
|
||||
analyser = SimpleNamespace(
|
||||
fudai_detail_ui_mode="legacy",
|
||||
resolution_ratio_x=1080,
|
||||
resolution_ratio_y=2400,
|
||||
device_id="device",
|
||||
needswitch=False,
|
||||
operation=_Operation(),
|
||||
_log_kv=lambda *_args, **_kwargs: None,
|
||||
)
|
||||
|
||||
HelperFunctions.handle_lottery_result_by_ocr(analyser, "我知道了")
|
||||
|
||||
assert clicks[0] == LOTTERY_RESULT_CONFIRM_CLICK_V1
|
||||
@@ -7,6 +7,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -126,6 +131,87 @@ class TestScreenshotOperations:
|
||||
|
||||
assert callable(save_reward_pic)
|
||||
|
||||
def test_find_pic_path_does_not_fall_back_to_operations_dir_for_reading(
|
||||
self, tmp_path, monkeypatch
|
||||
):
|
||||
from operations.screenshot_operations import ScreenshotOperations
|
||||
from douyin.core import path_config
|
||||
|
||||
pic_dir = tmp_path / "pic"
|
||||
pic_dir.mkdir()
|
||||
target_dir = tmp_path / "target_pic"
|
||||
target_dir.mkdir()
|
||||
fake_ops_dir = tmp_path / "operations"
|
||||
fake_ops_dir.mkdir()
|
||||
stray = fake_ops_dir / "foo.png"
|
||||
stray.write_bytes(b"x")
|
||||
|
||||
monkeypatch.setattr(path_config, "get_pic_dir", lambda: str(pic_dir))
|
||||
monkeypatch.setattr("operations.screenshot_operations.os.path.dirname", lambda _p: str(fake_ops_dir))
|
||||
|
||||
path = ScreenshotOperations()._find_pic_path("foo.png", for_reading=True)
|
||||
assert path is None
|
||||
|
||||
|
||||
class TestCutPicDebug:
|
||||
"""cut_pic 调试图保存策略测试。"""
|
||||
|
||||
def test_fudai_detail_field_skips_cut_pic_debug(self, monkeypatch):
|
||||
from PIL import Image
|
||||
from douyin.core.underlying_operations_pkg.image_ops import _save_cut_debug_images
|
||||
|
||||
saved = []
|
||||
monkeypatch.setenv("SAVE_CUT_PIC_DEBUG_IMAGES", "1")
|
||||
monkeypatch.setattr(
|
||||
"douyin.handlers.douyin_screenshot_manager.save_debug_image",
|
||||
lambda *args, **kwargs: saved.append((args, kwargs)) or "debug.png",
|
||||
)
|
||||
|
||||
img = Image.new("RGB", (20, 20), "white")
|
||||
_save_cut_debug_images(
|
||||
MagicMock(),
|
||||
img,
|
||||
img,
|
||||
"福袋内容",
|
||||
"screenshot.png",
|
||||
1,
|
||||
2,
|
||||
10,
|
||||
12,
|
||||
)
|
||||
|
||||
assert saved == []
|
||||
|
||||
def test_non_fudai_field_keeps_cut_pic_debug(self, monkeypatch):
|
||||
from PIL import Image
|
||||
from douyin.core.underlying_operations_pkg.image_ops import _save_cut_debug_images
|
||||
|
||||
saved = []
|
||||
monkeypatch.setenv("SAVE_CUT_PIC_DEBUG_IMAGES", "1")
|
||||
monkeypatch.setattr(
|
||||
"douyin.handlers.douyin_screenshot_manager.save_latest_attempt",
|
||||
lambda *args, **kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"douyin.handlers.douyin_screenshot_manager.save_debug_image",
|
||||
lambda *args, **kwargs: saved.append((args, kwargs)) or "debug.png",
|
||||
)
|
||||
|
||||
img = Image.new("RGB", (20, 20), "white")
|
||||
_save_cut_debug_images(
|
||||
MagicMock(),
|
||||
img,
|
||||
img,
|
||||
"普通字段",
|
||||
"screenshot.png",
|
||||
1,
|
||||
2,
|
||||
10,
|
||||
12,
|
||||
)
|
||||
|
||||
assert len(saved) == 1
|
||||
|
||||
|
||||
class TestScreenshotService:
|
||||
"""screenshot_service 模块测试。"""
|
||||
@@ -142,6 +228,47 @@ class TestScreenshotService:
|
||||
assert isinstance(workers, int)
|
||||
assert workers >= 1
|
||||
|
||||
def test_start_switch_device_does_not_deadlock(self, monkeypatch):
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
|
||||
svc = ScreenshotService()
|
||||
svc._running = True
|
||||
svc._current_device_id = "old-device"
|
||||
fake_thread = MagicMock()
|
||||
fake_thread.is_alive.return_value = False
|
||||
svc._thread = fake_thread
|
||||
|
||||
created_threads: list[tuple[object, tuple, dict]] = []
|
||||
|
||||
def _fake_thread_ctor(*args, **kwargs):
|
||||
created_threads.append((args, tuple(), kwargs))
|
||||
t = MagicMock()
|
||||
t.start.return_value = None
|
||||
t.is_alive.return_value = False
|
||||
return t
|
||||
|
||||
monkeypatch.setattr("operations.screenshot_service.threading.Thread", _fake_thread_ctor)
|
||||
monkeypatch.setattr("operations.screenshot_service.path_config.get_screenshot_path", lambda: "pic/screenshot.png")
|
||||
|
||||
done = threading.Event()
|
||||
err: list[BaseException] = []
|
||||
|
||||
def _runner():
|
||||
try:
|
||||
svc.start("new-device")
|
||||
except BaseException as exc: # pragma: no cover - test helper
|
||||
err.append(exc)
|
||||
finally:
|
||||
done.set()
|
||||
|
||||
t = threading.Thread(target=_runner, daemon=True)
|
||||
t.start()
|
||||
|
||||
assert done.wait(1.0), "switching ScreenshotService device should not deadlock"
|
||||
assert not err
|
||||
assert svc._current_device_id == "new-device"
|
||||
assert len(created_threads) == 1
|
||||
|
||||
|
||||
class TestOcrProcessor:
|
||||
"""OCRProcessor 类测试。"""
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -157,6 +161,29 @@ class TestDouyinYanghaoShimConsistency:
|
||||
assert f1 is f2
|
||||
|
||||
|
||||
class TestTimedYanghaoTrigger:
|
||||
def test_maybe_run_yanghao_uses_recommend_flow(self):
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
|
||||
s = SimpleNamespace()
|
||||
s.yanghao_recommend_interval_seconds = 60
|
||||
s.yanghao_recommend_duration_seconds = 30
|
||||
s._waiting_for_lottery_result = False
|
||||
s._current_attending_reservation_fudai = False
|
||||
s.reservations = []
|
||||
s.reservation_focus_until_ts = 0.0
|
||||
s._last_yanghao_ts = 0.0
|
||||
s._log_kv = MagicMock(return_value=None)
|
||||
s._yanghao_recommend_flow = MagicMock(return_value=None)
|
||||
s._yanghao_wait = MagicMock(return_value=None)
|
||||
|
||||
fudai_analyse._maybe_run_yanghao_during_run(s)
|
||||
|
||||
s._yanghao_recommend_flow.assert_called_once_with(30)
|
||||
s._yanghao_wait.assert_not_called()
|
||||
assert s._last_yanghao_ts > 0.0
|
||||
|
||||
|
||||
class TestOtherModules:
|
||||
"""other 子模块存在性测试。"""
|
||||
|
||||
|
||||
@@ -97,6 +97,11 @@ class TestSpecificPaths:
|
||||
path = path_config.get_actions_log_path()
|
||||
assert path.endswith(os.path.join("logs", "actions.log"))
|
||||
|
||||
def test_web_gui_host_ignores_generic_host_env(self, monkeypatch):
|
||||
monkeypatch.delenv("WEB_GUI_HOST", raising=False)
|
||||
monkeypatch.setenv("HOST", "0.0.0.0")
|
||||
assert path_config.get_web_gui_host() == path_config.DEFAULT_WEB_GUI_HOST
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 路径间不应互相重复
|
||||
|
||||
@@ -176,6 +176,28 @@ class TestReservationLogicCommon:
|
||||
)
|
||||
assert isinstance(_RESERVATION_ERROR_UTILS_AVAILABLE, bool)
|
||||
|
||||
def test_add_and_attend_window_import_error_flag(self):
|
||||
from douyin.reservation.reservation_logic import add, attend_window
|
||||
|
||||
assert isinstance(add._RESERVATION_ERROR_UTILS_AVAILABLE, bool)
|
||||
assert isinstance(attend_window._RESERVATION_ERROR_UTILS_AVAILABLE, bool)
|
||||
|
||||
def test_attend_window_imports_runtime_helpers(self):
|
||||
from douyin.reservation.reservation_logic import attend_window
|
||||
from douyin.reservation.reservation_logic.cleanup_validate import (
|
||||
cleanup_expired_reservations,
|
||||
)
|
||||
|
||||
assert attend_window.cleanup_expired_reservations is cleanup_expired_reservations
|
||||
|
||||
def test_seek_room_imports_dump_state_helper(self):
|
||||
from douyin.reservation.douyin_reservation_handler_pkg import seek_room
|
||||
from douyin.reservation.douyin_reservation_handler_pkg.dump_state import (
|
||||
_dump_room_pos_map_to_state,
|
||||
)
|
||||
|
||||
assert seek_room._dump_room_pos_map_to_state is _dump_room_pos_map_to_state
|
||||
|
||||
|
||||
# ============================================================
|
||||
# logging_wrapper_pkg._common
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
|
||||
def _mk_analyser():
|
||||
a = SimpleNamespace()
|
||||
a._log_kv = MagicMock(return_value=None)
|
||||
a._fudai_detail_task_count_from_stage = 1
|
||||
a._screenshot_ready_for_ocr = False
|
||||
a.device_id = "MOCK_DEVICE"
|
||||
a.enable_streaming_screenshot = True
|
||||
a.operation = SimpleNamespace(
|
||||
get_screenshot=lambda *_a, **_k: True,
|
||||
check_countdown=lambda _text: (30, 1234567890.0),
|
||||
)
|
||||
a.current_room_title = ""
|
||||
a.current_room_title_raw = ""
|
||||
return a
|
||||
|
||||
|
||||
def test_read_once_restarts_screenshot_service_after_ocr(tmp_path, monkeypatch):
|
||||
from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once import (
|
||||
read_fudai_detail_once,
|
||||
)
|
||||
|
||||
analyser = _mk_analyser()
|
||||
screenshot_path = tmp_path / "screenshot.png"
|
||||
screenshot_path.write_bytes(
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
b"\x00\x00\x00\rIHDR"
|
||||
b"\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00"
|
||||
b"\x90wS\xde"
|
||||
b"\x00\x00\x00\x0cIDATx\x9cc\xf8\xcf\xc0\x00\x00\x03\x01\x01\x00\xc9\xfe\x92\xef"
|
||||
b"\x00\x00\x00\x00IEND\xaeB`\x82"
|
||||
)
|
||||
|
||||
starts: list[tuple[str, float]] = []
|
||||
|
||||
class _Svc:
|
||||
def is_running(self):
|
||||
return True
|
||||
|
||||
def stop(self):
|
||||
return None
|
||||
|
||||
def start(self, device_id, interval=1.5):
|
||||
starts.append((device_id, interval))
|
||||
|
||||
pil_mod = ModuleType("PIL")
|
||||
pil_mod.Image = SimpleNamespace(
|
||||
open=lambda _p: type(
|
||||
"_Img",
|
||||
(),
|
||||
{
|
||||
"load": lambda self: None,
|
||||
"convert": lambda self, _mode: object(),
|
||||
"close": lambda self: None,
|
||||
},
|
||||
)()
|
||||
)
|
||||
|
||||
with patch(
|
||||
"douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.path_config.get_screenshot_path",
|
||||
return_value=str(screenshot_path),
|
||||
), patch(
|
||||
"douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.get_fudai_contain",
|
||||
return_value=("内容", "00:30", 1, 1, 10.0),
|
||||
), patch(
|
||||
"douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.validate_fudai_detail",
|
||||
return_value=(True, "ok"),
|
||||
), patch(
|
||||
"operations.screenshot_service.ScreenshotService.get_instance",
|
||||
return_value=_Svc(),
|
||||
):
|
||||
monkeypatch.setitem(sys.modules, "PIL", pil_mod)
|
||||
status, detail, extra = read_fudai_detail_once(analyser)
|
||||
|
||||
assert status == "ok"
|
||||
assert detail[0] == "内容"
|
||||
assert extra["task_count"] == 1
|
||||
assert starts == [("MOCK_DEVICE", 1.5)]
|
||||
|
||||
|
||||
def test_read_once_retries_fresh_screenshot_when_reused_file_is_unreadable(
|
||||
tmp_path, monkeypatch
|
||||
):
|
||||
from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once import (
|
||||
read_fudai_detail_once,
|
||||
)
|
||||
|
||||
analyser = _mk_analyser()
|
||||
analyser._screenshot_ready_for_ocr = True
|
||||
analyser.operation.get_screenshot = MagicMock(return_value=True)
|
||||
|
||||
screenshot_path = tmp_path / "broken_reused.png"
|
||||
screenshot_path.write_bytes(b"x" * 2048)
|
||||
|
||||
class _ImgObj:
|
||||
def load(self):
|
||||
return None
|
||||
|
||||
def convert(self, _mode):
|
||||
return object()
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
call_state = {"count": 0}
|
||||
|
||||
def _open(_path):
|
||||
call_state["count"] += 1
|
||||
if call_state["count"] == 1:
|
||||
raise OSError("broken png")
|
||||
return _ImgObj()
|
||||
|
||||
pil_mod = ModuleType("PIL")
|
||||
pil_mod.Image = SimpleNamespace(open=_open)
|
||||
|
||||
with patch(
|
||||
"douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.path_config.get_screenshot_path",
|
||||
return_value=str(screenshot_path),
|
||||
), patch(
|
||||
"douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.get_fudai_contain",
|
||||
return_value=("内容", "00:30", 1, 1, 10.0),
|
||||
), patch(
|
||||
"operations.screenshot_service.ScreenshotService.get_instance",
|
||||
return_value=SimpleNamespace(is_running=lambda: False),
|
||||
):
|
||||
monkeypatch.setitem(sys.modules, "PIL", pil_mod)
|
||||
status, detail, extra = read_fudai_detail_once(analyser)
|
||||
|
||||
assert status == "ok"
|
||||
assert detail[0] == "内容"
|
||||
assert extra["task_count"] == 1
|
||||
analyser.operation.get_screenshot.assert_called_once_with(
|
||||
analyser.device_id, use_service=False
|
||||
)
|
||||
|
||||
|
||||
def test_read_once_clears_reuse_flag_when_screenshot_still_unreadable(
|
||||
tmp_path, monkeypatch
|
||||
):
|
||||
from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once import (
|
||||
read_fudai_detail_once,
|
||||
)
|
||||
|
||||
analyser = _mk_analyser()
|
||||
analyser._screenshot_ready_for_ocr = True
|
||||
analyser.operation.get_screenshot = MagicMock(return_value=True)
|
||||
|
||||
screenshot_path = tmp_path / "still_broken.png"
|
||||
screenshot_path.write_bytes(b"x" * 2048)
|
||||
|
||||
pil_mod = ModuleType("PIL")
|
||||
pil_mod.Image = SimpleNamespace(open=lambda _p: (_ for _ in ()).throw(OSError("broken png")))
|
||||
|
||||
with patch(
|
||||
"douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once.path_config.get_screenshot_path",
|
||||
return_value=str(screenshot_path),
|
||||
), patch(
|
||||
"operations.screenshot_service.ScreenshotService.get_instance",
|
||||
return_value=SimpleNamespace(is_running=lambda: False),
|
||||
):
|
||||
monkeypatch.setitem(sys.modules, "PIL", pil_mod)
|
||||
status, _detail, extra = read_fudai_detail_once(analyser)
|
||||
|
||||
assert status == "error"
|
||||
assert extra["reason"] == "screenshot_failed"
|
||||
assert analyser._screenshot_ready_for_ocr is False
|
||||
@@ -0,0 +1,93 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
|
||||
def _mk_analyser():
|
||||
a = SimpleNamespace()
|
||||
a._fudai_detail_verified = False
|
||||
a.fudai_detail_initial_wait_seconds = 0.0
|
||||
a.fudai_detail_retry_delay_seconds = 0.0
|
||||
a.fudai_detail_max_attempts = 1
|
||||
a.operation = SimpleNamespace(delay=lambda _seconds: None)
|
||||
a._log_kv = MagicMock(return_value=None)
|
||||
return a
|
||||
|
||||
|
||||
def test_status_ok_with_invalid_tuple_does_not_crash():
|
||||
from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries import (
|
||||
read_fudai_detail_with_retries,
|
||||
)
|
||||
|
||||
analyser = _mk_analyser()
|
||||
|
||||
with patch(
|
||||
"douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries.read_fudai_detail_once",
|
||||
return_value=("ok", None, {}),
|
||||
):
|
||||
result = read_fudai_detail_with_retries(
|
||||
analyser,
|
||||
fudai_x=0,
|
||||
read_once_callback=None,
|
||||
close_detail_callback=lambda *_a, **_k: None,
|
||||
ensure_open_callback=lambda *_a, **_k: None,
|
||||
)
|
||||
|
||||
assert isinstance(result, tuple)
|
||||
assert len(result) == 6
|
||||
|
||||
|
||||
def test_read_once_callback_is_used_when_provided():
|
||||
from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries import (
|
||||
read_fudai_detail_with_retries,
|
||||
)
|
||||
|
||||
analyser = _mk_analyser()
|
||||
|
||||
def custom_read_once(_analyser):
|
||||
return ("watch_task", ("", "", 0, 0, 0.0, (0.0, 60.0)), {"source": "custom"})
|
||||
|
||||
result = read_fudai_detail_with_retries(
|
||||
analyser,
|
||||
fudai_x=0,
|
||||
read_once_callback=custom_read_once,
|
||||
close_detail_callback=lambda *_a, **_k: None,
|
||||
ensure_open_callback=lambda *_a, **_k: None,
|
||||
)
|
||||
|
||||
assert isinstance(result, tuple)
|
||||
assert len(result) == 6
|
||||
assert getattr(analyser, "_last_fudai_detail_status", "") == "watch_task"
|
||||
|
||||
|
||||
def test_task_count_zero_reason_from_read_once_triggers_reopen_retry():
|
||||
from douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries import (
|
||||
read_fudai_detail_with_retries,
|
||||
)
|
||||
|
||||
analyser = _mk_analyser()
|
||||
analyser.fudai_detail_max_attempts = 2
|
||||
|
||||
reopen_calls = []
|
||||
|
||||
seq = [
|
||||
("error", ("", "", 0, 0, 0.0, (0.0, 60.0)), {"reason": "not_in_fudai_detail", "task_count": 0}),
|
||||
("watch_task", ("", "", 0, 0, 0.0, (0.0, 60.0)), {}),
|
||||
]
|
||||
|
||||
with patch(
|
||||
"douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries.read_fudai_detail_once",
|
||||
side_effect=seq,
|
||||
):
|
||||
result = read_fudai_detail_with_retries(
|
||||
analyser,
|
||||
fudai_x=321,
|
||||
read_once_callback=None,
|
||||
close_detail_callback=lambda *_a, **_k: None,
|
||||
ensure_open_callback=lambda _a, x: reopen_calls.append(x),
|
||||
)
|
||||
|
||||
assert isinstance(result, tuple)
|
||||
assert len(result) == 6
|
||||
assert reopen_calls == [321]
|
||||
@@ -209,6 +209,55 @@ class TestScreenshotAndDiagnose:
|
||||
assert s._last_diag_seen == {"detail_seen": False}
|
||||
|
||||
|
||||
class TestFinderReuseRecovery:
|
||||
def test_invalid_reused_screenshot_falls_back_to_fresh_capture(self, monkeypatch, tmp_path):
|
||||
from douyin.detection.detection_pkg import finder as mod
|
||||
|
||||
class _Pic:
|
||||
size = (1080, 2400)
|
||||
def load(self): return None
|
||||
def convert(self, _mode): return self
|
||||
def close(self): return None
|
||||
|
||||
screenshot_path = tmp_path / "screenshot.png"
|
||||
screenshot_path.write_bytes(b"x" * 2048)
|
||||
|
||||
analyser = MagicMock()
|
||||
analyser.fudai_finder_optimized_enabled = False
|
||||
analyser.device_id = "MOCK"
|
||||
analyser._screenshot_ready_for_ocr = True
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.get_screenshot = MagicMock(return_value=True)
|
||||
analyser.operation.delay = MagicMock(return_value=None)
|
||||
analyser.resolution_ratio_x = 1080
|
||||
analyser.resolution_ratio_y = 2400
|
||||
analyser.y_pianyi = 0
|
||||
analyser._log_kv = MagicMock(return_value=None)
|
||||
|
||||
state = {"count": 0}
|
||||
def _open(_path):
|
||||
state["count"] += 1
|
||||
if state["count"] == 1:
|
||||
raise OSError("broken reused screenshot")
|
||||
return _Pic()
|
||||
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
|
||||
pil_mod = ModuleType("PIL")
|
||||
pil_mod.Image = SimpleNamespace(open=_open)
|
||||
monkeypatch.setitem(sys.modules, "PIL", pil_mod)
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.path_config.get_screenshot_path", lambda: str(screenshot_path))
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_with_numpy", lambda *a, **k: (False, None))
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.scan_pixel_by_pixel", lambda *a, **k: (False, None))
|
||||
monkeypatch.setattr("douyin.detection.detection_pkg.finder.match_template", lambda *a, **k: (False, None))
|
||||
|
||||
result = mod.check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
|
||||
|
||||
assert result is False
|
||||
analyser.operation.get_screenshot.assert_called_once_with(analyser.device_id, use_service=False)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# dispatch_stage_branch
|
||||
# ============================================================
|
||||
|
||||
@@ -68,6 +68,19 @@ class TestUnderlyingOperationsPaths:
|
||||
)
|
||||
assert not bad_pattern.search(src)
|
||||
|
||||
def test_no_dirname_target_pic_pattern_anywhere(self):
|
||||
sources = [
|
||||
_read("operations", "screenshot_operations.py"),
|
||||
_read("douyin", "core", "underlying_operations_pkg", "screenshot_direct.py"),
|
||||
]
|
||||
combined = "\n".join(sources)
|
||||
bad_pattern = re.compile(
|
||||
r"os\.path\.join\(\s*os\.path\.dirname\(__file__\)[^)]*?\"target_pic\""
|
||||
)
|
||||
assert not bad_pattern.search(combined), (
|
||||
"target_pic 路径不应再相对模块目录拼接,应锚到项目根"
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# douyin_fudai.py
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
def test_capture_screenshot_direct_invalid_fallback_png_returns_false(tmp_path):
|
||||
from douyin.core.underlying_operations_pkg.screenshot_direct import (
|
||||
capture_screenshot_direct,
|
||||
)
|
||||
|
||||
fake_self = SimpleNamespace(
|
||||
_adb_path=lambda: "adb",
|
||||
get_screenshot=lambda *_a, **_k: False,
|
||||
)
|
||||
|
||||
pic_dir = tmp_path / "pic"
|
||||
pic_dir.mkdir()
|
||||
|
||||
with patch(
|
||||
"douyin.core.underlying_operations_pkg.screenshot_direct.path_config.get_pic_dir",
|
||||
return_value=str(pic_dir),
|
||||
), patch(
|
||||
"douyin.core.underlying_operations_pkg.screenshot_direct.subprocess.run",
|
||||
return_value=SimpleNamespace(returncode=0),
|
||||
), patch(
|
||||
"douyin.core.underlying_operations_pkg.screenshot_direct._valid_png",
|
||||
return_value=False,
|
||||
):
|
||||
result = capture_screenshot_direct(fake_self, "MOCK", "pic")
|
||||
|
||||
assert result is False
|
||||
@@ -0,0 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_save_step_screenshot_uses_path_config_pic_dir():
|
||||
from pathlib import Path
|
||||
|
||||
src = Path("douyin/handlers/douyin_screenshot_handler.py").read_text(
|
||||
encoding="utf-8", errors="replace"
|
||||
)
|
||||
assert "path_config.get_pic_dir()" in src
|
||||
@@ -4,6 +4,7 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
@@ -236,3 +237,46 @@ class TestAdbCompat:
|
||||
write_config(cur) # 写回原值,不改任何东西
|
||||
except Exception as e:
|
||||
pytest.fail(f"write_config 不应抛: {e}")
|
||||
|
||||
|
||||
class TestRequestParsing:
|
||||
def test_read_json_invalid_content_length_returns_empty(self):
|
||||
from gui.web_gui_pkg.request_parsing import read_json
|
||||
|
||||
class _Dummy:
|
||||
headers = {"Content-Length": "abc"}
|
||||
rfile = io.BytesIO(b'{"x":1}')
|
||||
|
||||
assert read_json(_Dummy()) == {}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exc_type",
|
||||
[BrokenPipeError, ConnectionAbortedError, ConnectionResetError],
|
||||
)
|
||||
def test_send_json_ignores_client_disconnect(self, exc_type):
|
||||
from gui.web_gui_pkg.request_parsing import send_json
|
||||
|
||||
class _Dummy:
|
||||
def __init__(self):
|
||||
self.wfile = self
|
||||
self.status = None
|
||||
self.headers = []
|
||||
self.header_finished = False
|
||||
|
||||
def send_response(self, status):
|
||||
self.status = status
|
||||
|
||||
def send_header(self, key, value):
|
||||
self.headers.append((key, value))
|
||||
|
||||
def end_headers(self):
|
||||
self.header_finished = True
|
||||
|
||||
def write(self, _data):
|
||||
raise exc_type("client disconnected")
|
||||
|
||||
dummy = _Dummy()
|
||||
send_json(dummy, {"ok": True})
|
||||
|
||||
assert dummy.status == 200
|
||||
assert dummy.header_finished is True
|
||||
@@ -14,6 +14,8 @@ class _DummyHandler:
|
||||
self.headers = {"X-CSRF-Token": csrf_token}
|
||||
self._body = body if body is not None else {}
|
||||
self.calls = []
|
||||
self.client_address = ("127.0.0.1", 12345)
|
||||
self.static_calls = []
|
||||
|
||||
def _read_json(self):
|
||||
return self._body
|
||||
@@ -26,6 +28,10 @@ class _DummyHandler:
|
||||
self.calls.append((status, {"error": "send_error"}))
|
||||
return None
|
||||
|
||||
def _serve_static(self, rel_path):
|
||||
self.static_calls.append(rel_path)
|
||||
return None
|
||||
|
||||
|
||||
class _DummyRunner:
|
||||
def get_stats(self, include_events=False): # noqa: ARG002
|
||||
@@ -102,6 +108,55 @@ def test_config_bool_string_false_written_as_false(monkeypatch):
|
||||
assert written.get("enable_streaming_screenshot") is False
|
||||
|
||||
|
||||
def test_config_accepts_fudai_detail_v2_ocr_switches_and_ui_mode(monkeypatch):
|
||||
written = {}
|
||||
|
||||
monkeypatch.setattr(routes, "read_config", lambda: {})
|
||||
monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg))
|
||||
|
||||
status, obj = _post(
|
||||
"/api/config",
|
||||
{
|
||||
"config": {
|
||||
"fudai_detail_ui_mode": "v2_0",
|
||||
"fudai_detail_ocr_content_enabled": "true",
|
||||
"fudai_detail_ocr_value_enabled": "true",
|
||||
"fudai_detail_ocr_countdown_enabled": "true",
|
||||
"fudai_detail_ocr_task_enabled": "true",
|
||||
"fudai_detail_ocr_task_count_enabled": "true",
|
||||
"fudai_detail_ocr_button_enabled": "true",
|
||||
"fudai_detail_ocr_participants_enabled": "false",
|
||||
"fudai_detail_ocr_live_title_enabled": "false",
|
||||
}
|
||||
},
|
||||
monkeypatch,
|
||||
)
|
||||
|
||||
assert status == 200
|
||||
assert obj.get("ok") is True
|
||||
assert written["fudai_detail_ui_mode"] == "v2_0"
|
||||
assert written["fudai_detail_ocr_content_enabled"] is True
|
||||
assert written["fudai_detail_ocr_button_enabled"] is True
|
||||
assert written["fudai_detail_ocr_participants_enabled"] is False
|
||||
|
||||
|
||||
def test_config_rejects_invalid_fudai_detail_ui_mode(monkeypatch):
|
||||
written = {"fudai_detail_ui_mode": "legacy"}
|
||||
|
||||
monkeypatch.setattr(routes, "read_config", lambda: dict(written))
|
||||
monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg))
|
||||
|
||||
status, obj = _post(
|
||||
"/api/config",
|
||||
{"config": {"fudai_detail_ui_mode": "unknown"}},
|
||||
monkeypatch,
|
||||
)
|
||||
|
||||
assert status == 200
|
||||
assert obj.get("ok") is True
|
||||
assert written["fudai_detail_ui_mode"] == "legacy"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"ports_raw,expected_invalid",
|
||||
[
|
||||
@@ -153,3 +208,73 @@ def test_wifi_scan_includes_tried_subnets(monkeypatch):
|
||||
assert status == 200
|
||||
assert obj.get("ok") is True
|
||||
assert obj.get("subnets") == ["192.168.10.0/24", "10.0.0.0/24"]
|
||||
|
||||
|
||||
def test_wifi_disconnect_clears_last_target_only_on_exact_target(monkeypatch):
|
||||
cleared = {"called": False}
|
||||
|
||||
monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb")
|
||||
monkeypatch.setattr(routes, "list_adb_devices", lambda adb: []) # noqa: ARG001
|
||||
|
||||
import gui.gui_core as gui_core
|
||||
monkeypatch.setattr(gui_core, "disconnect_wifi_adb", lambda adb, ip, port: (True, "ok")) # noqa: ARG001
|
||||
|
||||
import gui.gui_core_pkg as core_pkg
|
||||
monkeypatch.setattr(core_pkg, "get_last_wifi_target", lambda: {"target": "192.168.1.10:37719"})
|
||||
monkeypatch.setattr(core_pkg, "clear_last_wifi_target", lambda: cleared.__setitem__("called", True))
|
||||
|
||||
status, obj = _post("/api/wifi/disconnect", {"ip": "192.168.1.1", "port": "37719"}, monkeypatch)
|
||||
assert status == 200
|
||||
assert obj.get("ok") is True
|
||||
assert cleared["called"] is False
|
||||
|
||||
|
||||
def test_rejects_non_local_post_requests(monkeypatch):
|
||||
monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb")
|
||||
handler = _DummyHandler(body={"config": {}}, csrf_token="token")
|
||||
handler.client_address = ("192.168.1.50", 55555)
|
||||
runner = _DummyRunner()
|
||||
u = SimpleNamespace(path="/api/config", query="")
|
||||
routes.handle_post(handler, u, runner, "token")
|
||||
assert handler.calls
|
||||
status, obj = handler.calls[-1]
|
||||
assert status == 403
|
||||
assert obj.get("error") == "Local access only"
|
||||
|
||||
|
||||
def test_rejects_non_local_get_api_requests(monkeypatch):
|
||||
monkeypatch.setattr(routes, "read_config", lambda: {"ok": True})
|
||||
handler = _DummyHandler()
|
||||
handler.client_address = ("192.168.1.50", 55555)
|
||||
runner = _DummyRunner()
|
||||
u = SimpleNamespace(path="/api/config", query="")
|
||||
routes.handle_get(handler, u, runner, "token")
|
||||
assert handler.calls
|
||||
status, obj = handler.calls[-1]
|
||||
assert status == 403
|
||||
assert obj.get("error") == "Local access only"
|
||||
|
||||
|
||||
def test_rejects_non_local_pic_requests(monkeypatch):
|
||||
handler = _DummyHandler()
|
||||
handler.client_address = ("192.168.1.50", 55555)
|
||||
runner = _DummyRunner()
|
||||
u = SimpleNamespace(path="/pic/screenshot.png", query="")
|
||||
routes.handle_get(handler, u, runner, "token")
|
||||
assert handler.calls
|
||||
status, obj = handler.calls[-1]
|
||||
assert status == 403
|
||||
assert obj.get("error") == "Local access only"
|
||||
|
||||
|
||||
def test_rejects_non_local_static_requests():
|
||||
handler = _DummyHandler()
|
||||
handler.client_address = ("192.168.1.50", 55555)
|
||||
runner = _DummyRunner()
|
||||
u = SimpleNamespace(path="/", query="")
|
||||
routes.handle_get(handler, u, runner, "token")
|
||||
assert handler.calls
|
||||
status, obj = handler.calls[-1]
|
||||
assert status == 403
|
||||
assert obj.get("error") == "send_error"
|
||||
assert handler.static_calls == []
|
||||
@@ -33,3 +33,34 @@ def test_web_gui_log_helper_does_not_raise():
|
||||
wg._wg_log("[smoke] info")
|
||||
wg._wg_log("[smoke] warn", level="WARNING")
|
||||
wg._wg_log("[smoke] error", level="ERROR")
|
||||
|
||||
|
||||
def test_cleanup_orphan_processes_filters_by_owned_pid(monkeypatch):
|
||||
import gui.web_gui as wg
|
||||
|
||||
runner = wg.ProcRunner()
|
||||
runner._owned_run_cli_pids = {111}
|
||||
|
||||
monkeypatch.setattr(
|
||||
runner,
|
||||
"_list_project_run_cli_processes",
|
||||
lambda: [
|
||||
(111, "python bin/run_cli.py --device-id A"),
|
||||
(222, "python bin/run_cli.py --device-id A"),
|
||||
],
|
||||
)
|
||||
|
||||
killed: list[list[str]] = []
|
||||
|
||||
def _fake_run(cmd, **kwargs): # noqa: ARG001
|
||||
killed.append(list(cmd))
|
||||
class _Result:
|
||||
returncode = 0
|
||||
return _Result()
|
||||
|
||||
monkeypatch.setattr(wg.subprocess, "run", _fake_run)
|
||||
|
||||
count = runner._cleanup_orphan_run_cli_processes("")
|
||||
|
||||
assert count == 0
|
||||
assert killed == []
|
||||
@@ -0,0 +1,29 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_stop_old_processes_targets_current_repo_only(monkeypatch):
|
||||
import gui.webgui_launcher as launcher
|
||||
|
||||
inst = launcher.WebGUILauncher.__new__(launcher.WebGUILauncher)
|
||||
logs: list[str] = []
|
||||
inst.log = logs.append
|
||||
|
||||
calls: list[list[str]] = []
|
||||
|
||||
def _fake_run(cmd, **kwargs): # noqa: ARG001
|
||||
calls.append(list(cmd))
|
||||
class _Result:
|
||||
returncode = 0
|
||||
return _Result()
|
||||
|
||||
monkeypatch.setattr(launcher.sys, "platform", "win32")
|
||||
monkeypatch.setattr(launcher.subprocess, "run", _fake_run)
|
||||
|
||||
inst.stop_old_processes()
|
||||
|
||||
assert calls, "expected stop_old_processes to invoke subprocess.run"
|
||||
ps_cmd = " ".join(calls[0])
|
||||
expected_root = str(Path(launcher.PROJECT_ROOT)).replace("\\", "\\\\")
|
||||
assert expected_root.lower() in ps_cmd.lower()
|
||||
@@ -166,6 +166,20 @@ class TestConnectWifiAdb:
|
||||
assert captured["cmd"][-1] == "192.168.5.2:5555"
|
||||
|
||||
|
||||
class TestDisconnectWifiAdb:
|
||||
def test_ip_port_input_does_not_duplicate_port(self):
|
||||
captured = {}
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
captured["cmd"] = cmd
|
||||
return _proc("disconnected 192.168.5.2:5555", "", 0)
|
||||
|
||||
with patch("subprocess.run", side_effect=fake_run):
|
||||
ok, _ = wifi_adb.disconnect_wifi_adb("/adb", "192.168.5.2:5555")
|
||||
assert ok is True
|
||||
assert captured["cmd"][-1] == "192.168.5.2:5555"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# auto_connect_wifi_adb — 关键 bug:以前先 tcpip 再 get_device_ip 必然失败
|
||||
# ============================================================
|
||||
|
||||
Reference in new issue
Block a user