"""douyin/core 模块单元测试。 覆盖: - io_utils: _verify_png_integrity, _ensure_parent_dir 纯函数 - path_config: 路径配置函数 - version: 版本信息 - douyin_main_flow: MainFlowController 类存在性 """ from __future__ import annotations import os import json import tempfile from types import SimpleNamespace from unittest.mock import MagicMock import pytest class TestVerifyPngIntegrity: """_verify_png_integrity 纯函数测试。""" def test_valid_png_file(self): from douyin.core.io_utils import _verify_png_integrity # 创建一个最小的有效 PNG 文件 # PNG 签名 + IHDR + IEND png_data = ( b'\x89PNG\r\n\x1a\n' # PNG 签名 b'\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde' # IHDR b'\x00\x00\x00\x00IEND\xaeB`\x82' # IEND ) with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f: f.write(png_data) tmp_path = f.name try: result = _verify_png_integrity(tmp_path) assert result is True finally: os.unlink(tmp_path) def test_invalid_png_header(self): from douyin.core.io_utils import _verify_png_integrity with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f: f.write(b'not a png file') tmp_path = f.name try: result = _verify_png_integrity(tmp_path) assert result is False finally: os.unlink(tmp_path) def test_nonexistent_file(self): from douyin.core.io_utils import _verify_png_integrity result = _verify_png_integrity('/nonexistent/path/file.png') assert result is False def test_empty_file(self): from douyin.core.io_utils import _verify_png_integrity with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f: tmp_path = f.name try: result = _verify_png_integrity(tmp_path) assert result is False finally: os.unlink(tmp_path) class TestEnsureParentDir: """_ensure_parent_dir 函数测试。""" def test_function_exists(self): from douyin.core.io_utils import _ensure_parent_dir assert callable(_ensure_parent_dir) def test_creates_parent_directory(self): from douyin.core.io_utils import _ensure_parent_dir with tempfile.TemporaryDirectory() as tmpdir: nested_path = os.path.join(tmpdir, 'a', 'b', 'c', 'file.txt') _ensure_parent_dir(nested_path) parent = os.path.dirname(nested_path) assert os.path.isdir(parent) class TestSafeReplaceFile: """_safe_replace_file 函数测试。""" def test_function_exists(self): from douyin.core.io_utils import _safe_replace_file assert callable(_safe_replace_file) def test_replaces_file(self): from douyin.core.io_utils import _safe_replace_file with tempfile.TemporaryDirectory() as tmpdir: src = os.path.join(tmpdir, 'src.txt') dst = os.path.join(tmpdir, 'dst.txt') with open(src, 'w') as f: f.write('new content') with open(dst, 'w') as f: f.write('old content') result = _safe_replace_file(src, dst) assert result is True with open(dst) as f: assert f.read() == 'new content' class TestPathConfig: """path_config 模块测试。""" def test_project_root_exists(self): from douyin.core.path_config import PROJECT_ROOT assert PROJECT_ROOT is not None assert os.path.isdir(PROJECT_ROOT) def test_get_config_path_returns_string(self): from douyin.core.path_config import get_config_path result = get_config_path() assert isinstance(result, str) assert len(result) > 0 def test_get_log_file_path_returns_string(self): from douyin.core.path_config import get_log_file_path result = get_log_file_path() assert isinstance(result, str) def test_get_webui_dir_returns_string(self): from douyin.core.path_config import get_webui_dir result = get_webui_dir() assert isinstance(result, str) class TestVersion: """version 模块测试。""" def test_app_version_format(self): from douyin.core.version import APP_VERSION assert APP_VERSION.startswith('V') parts = APP_VERSION.lstrip('V').split('.') assert len(parts) == 3 assert all(p.isdigit() for p in parts) def test_app_build_date_format(self): from douyin.core.version import APP_BUILD_DATE parts = APP_BUILD_DATE.split('-') assert len(parts) == 3 assert len(parts[0]) == 4 # year assert len(parts[1]) == 2 # month assert len(parts[2]) == 2 # day def test_get_version_string(self): from douyin.core.version import get_version_string result = get_version_string() assert isinstance(result, str) assert 'V' in result def test_print_version_banner(self): from douyin.core.version import print_version_banner assert callable(print_version_banner) class TestMainFlowController: """MainFlowController 类测试。""" def test_class_exists(self): from douyin.core.douyin_main_flow import MainFlowController assert MainFlowController is not None class TestFlowControlShimConsistency: """验证 flow_control shim 与子模块导出一致。""" def test_find_and_open_fudai_detail_same_object(self): from douyin.core.douyin_flow_control import find_and_open_fudai_detail as f1 from douyin.core.douyin_flow_control_pkg import find_and_open_fudai_detail as f2 assert f1 is f2 class TestFudaiDetectionDefaults: def test_shopping_redpacket_stage_detection_defaults_enabled(self): from douyin.core.fudai_modules.init_helpers import apply_fudai_defaults analyser = SimpleNamespace() apply_fudai_defaults(analyser) assert analyser.pixel_detect_shopping_redpacket_enabled is True assert analyser.ocr_shopping_redpacket_enabled is False def test_apply_defaults_clears_runtime_reservation_and_mapping_state(self, tmp_path, monkeypatch): from douyin.core import path_config from douyin.core.fudai_modules.init_helpers import apply_fudai_defaults state_dir = tmp_path / "state" state_dir.mkdir() reservations_path = state_dir / "reservations.json" reservations_path.write_text( json.dumps( { "reason": "old_run", "room_pos": 9, "reservations": [ { "future_ts": 9999999999.0, "content": "old", "pos_seen": 9, } ], }, ensure_ascii=False, ), encoding="utf-8", ) for name, content in { "room_pos_map.json": '{"9": {"title": "old"}}', "room_pos_map.csv": "pos,title\n9,old\n", "room_pos_map.md": "| pos | title |\n| 9 | old |\n", }.items(): (state_dir / name).write_text(content, encoding="utf-8") monkeypatch.setattr(path_config, "get_reservations_path", lambda: str(reservations_path)) analyser = SimpleNamespace( _run_id="unit_run", _log_kv=MagicMock(return_value=None), ) apply_fudai_defaults(analyser) reservations = json.loads(reservations_path.read_text(encoding="utf-8")) assert reservations["reason"] == "startup_clear" assert reservations["reservations"] == [] room_map = json.loads((state_dir / "room_pos_map.json").read_text(encoding="utf-8")) assert room_map.get("_meta", {}).get("reason") == "startup_clear" assert [key for key in room_map.keys() if not str(key).startswith("_")] == [] assert (state_dir / "room_pos_map.csv").read_text(encoding="utf-8").strip() == "pos,title,title_raw,has_fudai,fudai_content" assert "暂无映射" in (state_dir / "room_pos_map.md").read_text(encoding="utf-8") def test_config_loader_defaults_shopping_redpacket_detection_enabled(self): from douyin.utils.douyin_config import ConfigManager analyser = SimpleNamespace() with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f: json.dump({}, f) tmp_path = f.name try: ConfigManager.load_config_from_file(analyser, tmp_path) finally: os.unlink(tmp_path) assert analyser.pixel_detect_shopping_redpacket_enabled is True assert analyser.ocr_shopping_redpacket_enabled is False def test_config_loader_loads_reservation_timing_fields(self): from douyin.utils.douyin_config import ConfigManager analyser = SimpleNamespace() config = { "reservation_back_verify_wait_seconds": 1.5, "reservation_direct_attend_min_action_seconds": 6.0, "reservation_direct_attend_max_failures": 3, "reservation_direct_attend_open_max_wait_seconds": 2.25, } with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f: json.dump(config, f) tmp_path = f.name try: ConfigManager.load_config_from_file(analyser, tmp_path) finally: os.unlink(tmp_path) assert analyser.reservation_back_verify_wait_seconds == 1.5 assert analyser.reservation_direct_attend_min_action_seconds == 6.0 assert analyser.reservation_direct_attend_max_failures == 3 assert analyser.reservation_direct_attend_open_max_wait_seconds == 2.25 def test_config_loader_loads_reservation_prejoin_fansclub_delays(self): from douyin.utils.douyin_config import ConfigManager analyser = SimpleNamespace() config = { "reservation_prejoin_fansclub_participate_wait_seconds": 0.25, "reservation_prejoin_fansclub_confirm_wait_seconds": 0.35, } with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f: json.dump(config, f) tmp_path = f.name try: ConfigManager.load_config_from_file(analyser, tmp_path) finally: os.unlink(tmp_path) assert analyser.reservation_prejoin_fansclub_participate_wait_seconds == 0.25 assert analyser.reservation_prejoin_fansclub_confirm_wait_seconds == 0.35 class TestCoreModules: """core 子模块存在性测试。""" def test_io_utils_importable(self): from douyin.core import io_utils assert io_utils is not None def test_path_config_importable(self): from douyin.core import path_config assert path_config is not None def test_version_importable(self): from douyin.core import version assert version is not None def test_douyin_main_flow_importable(self): from douyin.core import douyin_main_flow assert douyin_main_flow is not None def test_douyin_flow_control_importable(self): from douyin.core import douyin_flow_control assert douyin_flow_control is not None def test_underlying_operations_importable(self): from douyin.core import underlying_operations assert underlying_operations is not None