"""operations 模块单元测试。 覆盖: - ocr_operations: 缓存机制(cache_get/put/clear/stats)、_img_fingerprint - screenshot_operations: _find_pic_path 纯逻辑 """ from __future__ import annotations import os import threading from pathlib import Path from unittest.mock import MagicMock import pytest class TestOcrCache: """OCR 缓存机制测试。""" def test_cache_put_and_get(self): from operations.ocr_operations import cache_clear, cache_get, cache_put cache_clear() cache_put("test_key_1", {"text": "hello"}) result = cache_get("test_key_1") assert result == {"text": "hello"} def test_cache_miss_returns_none(self): from operations.ocr_operations import cache_clear, cache_get cache_clear() result = cache_get("nonexistent_key") assert result is None def test_cache_clear(self): from operations.ocr_operations import cache_clear, cache_get, cache_put cache_put("key_to_clear", "value") cache_clear() assert cache_get("key_to_clear") is None def test_cache_stats(self): from operations.ocr_operations import cache_clear, cache_get, cache_put, cache_stats cache_clear() # 重置 stats stats = cache_stats() initial_hit = stats.get("hit", 0) initial_miss = stats.get("miss", 0) cache_put("stats_key", "value") cache_get("stats_key") # hit cache_get("nonexistent") # miss stats = cache_stats() # 验证 stats 结构 assert "hit" in stats assert "miss" in stats def test_cache_overwrites_existing_key(self): from operations.ocr_operations import cache_clear, cache_get, cache_put cache_clear() cache_put("overwrite_key", "old_value") cache_put("overwrite_key", "new_value") assert cache_get("overwrite_key") == "new_value" class TestImgFingerprint: """_img_fingerprint 哈希函数测试。""" def test_same_bytes_same_hash(self): from operations.ocr_operations import _img_fingerprint data = b"test image data" h1 = _img_fingerprint(data, mode=0) h2 = _img_fingerprint(data, mode=0) assert h1 == h2 def test_different_bytes_different_hash(self): from operations.ocr_operations import _img_fingerprint h1 = _img_fingerprint(b"image1", mode=0) h2 = _img_fingerprint(b"image2", mode=0) assert h1 != h2 def test_different_mode_different_hash(self): from operations.ocr_operations import _img_fingerprint data = b"same data" h1 = _img_fingerprint(data, mode=0) h2 = _img_fingerprint(data, mode=1) assert h1 != h2 def test_hash_is_hex_string(self): from operations.ocr_operations import _img_fingerprint h = _img_fingerprint(b"test", mode=0) assert isinstance(h, str) assert all(c in "0123456789abcdef" for c in h) def test_hash_length_consistent(self): from operations.ocr_operations import _img_fingerprint h1 = _img_fingerprint(b"short", mode=0) h2 = _img_fingerprint(b"a much longer piece of data", mode=0) assert len(h1) == len(h2) # blake2b digest_size=12 → 24 hex chars class TestScreenshotOperations: """screenshot_operations 模块测试。""" def test_class_exists(self): from operations.screenshot_operations import ScreenshotOperations assert ScreenshotOperations is not None def test_get_screenshot_function_exists(self): from operations.screenshot_operations import get_screenshot assert callable(get_screenshot) def test_cut_pic_function_exists(self): from operations.screenshot_operations import cut_pic assert callable(cut_pic) def test_save_reward_pic_function_exists(self): from operations.screenshot_operations import save_reward_pic 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 模块测试。""" def test_class_exists(self): from operations.screenshot_service import ScreenshotService assert ScreenshotService is not None def test_get_optimal_workers(self): from operations.screenshot_service import get_optimal_workers workers = get_optimal_workers() 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 类测试。""" def test_class_exists(self): from operations.ocr_operations import OCRProcessor assert OCRProcessor is not None def test_class_has_expected_methods(self): from operations.ocr_operations import OCRProcessor # 检查类方法存在 assert hasattr(OCRProcessor, "_init_ocr") assert hasattr(OCRProcessor, "_ensure_ocr")