"""douyin/handlers/screenshot_manager 子模块单元测试。 覆盖: - save_image: _sanitize_filename_part 纯函数 - save_files: 函数签名验证 """ from __future__ import annotations from PIL import Image import pytest class TestSanitizeFilenamePart: """_sanitize_filename_part 纯函数测试。""" def test_empty_string(self): from douyin.handlers.screenshot_manager.save_image import _sanitize_filename_part result = _sanitize_filename_part("") assert result == "" def test_none_input(self): from douyin.handlers.screenshot_manager.save_image import _sanitize_filename_part result = _sanitize_filename_part(None) assert result == "" def test_removes_invalid_chars(self): from douyin.handlers.screenshot_manager.save_image import _sanitize_filename_part result = _sanitize_filename_part('file<>:"/\\|?*name') assert "<" not in result assert ">" not in result assert ":" not in result assert '"' not in result assert "/" not in result assert "\\" not in result assert "|" not in result assert "?" not in result assert "*" not in result def test_normal_filename(self): from douyin.handlers.screenshot_manager.save_image import _sanitize_filename_part result = _sanitize_filename_part("normal_filename") assert "normal" in result assert "filename" in result def test_chinese_filename(self): from douyin.handlers.screenshot_manager.save_image import _sanitize_filename_part result = _sanitize_filename_part("福袋截图") assert "福袋" in result or len(result) > 0 def test_extracts_basename_from_path(self): from douyin.handlers.screenshot_manager.save_image import _sanitize_filename_part result = _sanitize_filename_part("/path/to/file.png") assert "path" not in result or "file" in result class TestSaveFilesModule: """save_files 模块测试。""" def test_cleanup_ocr_dir_exists(self): from douyin.handlers.screenshot_manager.save_files import cleanup_ocr_dir assert callable(cleanup_ocr_dir) def test_save_latest_attempt_exists(self): from douyin.handlers.screenshot_manager.save_files import save_latest_attempt assert callable(save_latest_attempt) def test_save_last_success_exists(self): from douyin.handlers.screenshot_manager.save_files import save_last_success assert callable(save_last_success) def test_save_attempt_from_file_exists(self): from douyin.handlers.screenshot_manager.save_files import save_attempt_from_file assert callable(save_attempt_from_file) def test_save_success_from_file_exists(self): from douyin.handlers.screenshot_manager.save_files import save_success_from_file assert callable(save_success_from_file) class TestSaveImageModule: """save_image 模块测试。""" def test_save_debug_image_exists(self): from douyin.handlers.screenshot_manager.save_image import save_debug_image assert callable(save_debug_image) def test_build_debug_filename_uses_short_english_codes(self): from douyin.handlers.screenshot_manager.save_image_helpers import build_debug_filename filename = build_debug_filename( "pixel_detect", "lucky_draw_result", "before_detect", (290, 1300, 790, 1415), { "threshold": 0.8, "region_size": "500x115", "ui_version": "v2_0", "pixel_style": "white", "text_preview": "我知道了", }, ) assert filename.endswith(".png") assert len(filename) <= 120 assert "_px_lottery_pre_" in filename assert "像素检测" not in filename assert "抽奖结果" not in filename assert "检测前" not in filename def test_cleanup_single_operation_debug_images_keeps_pixel_history(self, tmp_path, monkeypatch): from douyin.handlers.screenshot_manager.save_image_helpers import ( cleanup_single_operation_debug_images, ) (tmp_path / "20260603_像素检测_福袋图标_检测成功.png").write_bytes(b"old") (tmp_path / "20260603_px_pxstage_ov_ok_1.png").write_bytes(b"old") ocr_file = tmp_path / "20260603_ocr_fdcontent_postocr.png" ocr_file.write_bytes(b"keep") monkeypatch.setattr( "douyin.handlers.screenshot_manager.save_image_helpers.get_debug_captures_dir", lambda: str(tmp_path), ) cleanup_single_operation_debug_images("pixel_detect") assert (tmp_path / "20260603_像素检测_福袋图标_检测成功.png").exists() assert (tmp_path / "20260603_px_pxstage_ov_ok_1.png").exists() assert ocr_file.exists() def test_detection_debug_filename_uses_short_code(self): from douyin.handlers.screenshot_manager.save_image_helpers import build_debug_filename filename = build_debug_filename( "detection", "fudai_icon", "detected", (41, 348, 561, 540), {"result": "success", "detected_x": 209}, ) assert "_det_fdicon_ok_" in filename assert "福袋" not in filename def test_build_debug_filename_includes_subsecond_timestamp(self): from douyin.handlers.screenshot_manager.save_image_helpers import build_debug_filename filename = build_debug_filename( "pixel_detect", "pixel_stage", "overview", None, {"ok": 3}, ) assert filename.endswith(".png") assert len(filename.split("_", 3)[2]) == 6 def test_cleanup_single_operation_debug_images_cleans_detection_only(self, tmp_path, monkeypatch): from douyin.handlers.screenshot_manager.save_image_helpers import ( cleanup_single_operation_debug_images, ) old_det = tmp_path / "20260603_detection_福袋图标_检测成功.png" old_det.write_bytes(b"old") old_px = tmp_path / "20260603_px_pxstage_ov_ok_1.png" old_px.write_bytes(b"keep") monkeypatch.setattr( "douyin.handlers.screenshot_manager.save_image_helpers.get_debug_captures_dir", lambda: str(tmp_path), ) cleanup_single_operation_debug_images("detection") assert not old_det.exists() assert old_px.exists() def test_annotate_debug_image_uses_cn_maps_without_nameerror(self): from douyin.handlers.screenshot_manager.save_image_helpers import annotate_debug_image image = Image.new("RGB", (200, 120), "white") annotated = annotate_debug_image( image=image, picname="fudai_content", step="after_ocr", coords=(10, 10, 100, 80), extra_info={"text_preview": "儿童装饰手表生活"}, ) assert annotated.size == image.size def test_annotate_debug_image_draws_green_arrow_for_fudai_icon_detected(self): from douyin.handlers.screenshot_manager.save_image_helpers import annotate_debug_image image = Image.new("RGB", (240, 160), "white") annotated = annotate_debug_image( image=image, picname="fudai_icon", step="detected", coords=(80, 60, 180, 100), extra_info={"detected_x_scaled": 150, "result": "success"}, ) assert annotated.size == image.size green_pixels = 0 for x in range(30, 151): for y in range(10, 81): r, g, b = annotated.getpixel((x, y)) if g >= 160 and r <= 80 and b <= 120: green_pixels += 1 assert green_pixels > 20 def test_maybe_auto_cleanup_skips_repeated_same_day_over_limit_scan( self, tmp_path, monkeypatch ): from datetime import datetime from douyin.handlers.screenshot_manager import save_image_helpers as helpers debug_base = tmp_path / "debug_captures" debug_base.mkdir() today = datetime.now().strftime("%Y-%m-%d") (debug_base / ".cleanup_marker").write_text(today, encoding="utf-8") config_path = tmp_path / "config.json" config_path.write_text( '{"debug_captures":{"max_files":1}}', encoding="utf-8", ) calls = {"count": 0} monkeypatch.setattr(helpers, "get_debug_captures_base_dir", lambda: str(debug_base)) monkeypatch.setattr( "douyin.handlers.screenshot_manager.save_image_helpers.path_config.get_config_path", lambda: str(config_path), ) monkeypatch.setattr( helpers, "count_debug_captures_files", lambda: calls.__setitem__("count", calls["count"] + 1) or 2, ) monkeypatch.setattr(helpers, "cleanup_debug_captures", lambda **_kwargs: 0) helpers.maybe_auto_cleanup(True, lambda _msg: None) helpers.maybe_auto_cleanup(True, lambda _msg: None) assert calls["count"] == 1 class TestScreenshotManagerSubmodules: """screenshot_manager 子模块存在性测试。""" def test_paths_importable(self): from douyin.handlers.screenshot_manager import paths assert paths is not None def test_cleanup_importable(self): from douyin.handlers.screenshot_manager import cleanup assert cleanup is not None def test_async_save_importable(self): from douyin.handlers.screenshot_manager import async_save assert async_save is not None def test_save_files_importable(self): from douyin.handlers.screenshot_manager import save_files assert save_files is not None def test_save_image_importable(self): from douyin.handlers.screenshot_manager import save_image assert save_image is not None