"""douyin/detection/pixel/_common.py 单元测试。 只测 _safe_open_screenshot_rgb:用 tmp_path 构造合法 / 非法 / 不存在的图片文件。 """ from __future__ import annotations import os import pytest from PIL import Image from douyin.detection.pixel import _safe_open_screenshot_rgb # ============================================================ # 工具:构造合法 / 非法 PNG # ============================================================ def _make_valid_png(path: str, size: tuple = (10, 10)) -> None: """生成一张最小的合法 PNG。""" img = Image.new("RGB", size, color=(255, 0, 0)) img.save(path, "PNG") # ============================================================ # 测试 # ============================================================ class TestSafeOpenScreenshotRgb: def test_valid_png(self, tmp_path): p = tmp_path / "ok.png" _make_valid_png(str(p)) result = _safe_open_screenshot_rgb(str(p)) assert result is not None assert result.mode == "RGB" assert result.size == (10, 10) def test_missing_file_returns_none(self, tmp_path): p = tmp_path / "nonexistent.png" assert _safe_open_screenshot_rgb(str(p)) is None def test_empty_path_returns_none(self): assert _safe_open_screenshot_rgb("") is None def test_corrupt_file_returns_none(self, tmp_path): # 写入非 PNG 内容 p = tmp_path / "corrupt.png" p.write_bytes(b"not a real png") result = _safe_open_screenshot_rgb(str(p)) # PIL 可能抛 OSError/SyntaxError,函数应吞掉返回 None assert result is None def test_truncated_file_returns_none(self, tmp_path): # 先生成合法 PNG,再截断到一半 full = tmp_path / "full.png" _make_valid_png(str(full)) truncated = tmp_path / "truncated.png" truncated.write_bytes(full.read_bytes()[:50]) result = _safe_open_screenshot_rgb(str(truncated)) # truncated PNG 应被 catch 并返回 None assert result is None def test_returns_rgb_mode(self, tmp_path): # 即使源文件是 RGBA / L 模式,也应转成 RGB p = tmp_path / "rgba.png" Image.new("RGBA", (5, 5), color=(0, 255, 0, 128)).save(str(p), "PNG") result = _safe_open_screenshot_rgb(str(p)) assert result is not None assert result.mode == "RGB"