From af8145b8a89dc080f130d8832c8b570c93c91fa7 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 21 May 2026 21:01:15 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=20fudai=5Ffilter=5Fpkg=20/=20logging?= =?UTF-8?q?=5Fpkg=20=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95=20+=20=E4=BF=AE?= =?UTF-8?q?=20monitor=20=E7=BC=BA=20datetime=20import?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增测试: - test_fudai_filter_pkg (24) 覆盖 helpers / should_skip / join_decision 三个子模块 含 _is_short_countdown_text / is_watch_task_fudai / check_contain + should_skip_fudai_by_config 5 个业务场景断言(高价值通过 / 观看任务跳过 / 低价值跳过 / 黑名单跳过 / 单间模式必参) - test_logging_pkg (22) 覆盖 _common 全局状态 + handlers 类构造 + cleanup 纯函数边界 + monitor 类构造 + config 全部对外 API(get_logger 缓存 / get_caller_info / format_exception_info / LogContext / log_function_call 装饰器) 修复 1 个真实回归 bug: - douyin/logging/douyin_logging_pkg/monitor.py 缺 from datetime import datetime (原文件用的是 from datetime import datetime, timedelta;拆分时只写了 import 模块导致 datetime.now() 抛 NameError) 修复后 LogRotationMonitor 可正常构造 回归: - 全套 581 → 627 (+46 用例) - 全部 627 passed in 22s - compileall exit 0 Co-Authored-By: Claude Opus 4.7 --- douyin/logging/douyin_logging_pkg/monitor.py | 1 + tests/test_fudai_filter_pkg.py | 159 ++++++++++++++ tests/test_logging_pkg.py | 211 +++++++++++++++++++ 3 files changed, 371 insertions(+) create mode 100644 tests/test_fudai_filter_pkg.py create mode 100644 tests/test_logging_pkg.py diff --git a/douyin/logging/douyin_logging_pkg/monitor.py b/douyin/logging/douyin_logging_pkg/monitor.py index 78ddccf..f5141e7 100644 --- a/douyin/logging/douyin_logging_pkg/monitor.py +++ b/douyin/logging/douyin_logging_pkg/monitor.py @@ -12,6 +12,7 @@ import logging import os import threading import time +from datetime import datetime from typing import Any, Dict, Optional from douyin.core import path_config diff --git a/tests/test_fudai_filter_pkg.py b/tests/test_fudai_filter_pkg.py new file mode 100644 index 0000000..2c65733 --- /dev/null +++ b/tests/test_fudai_filter_pkg.py @@ -0,0 +1,159 @@ +"""douyin/fudai/core/fudai_filter_pkg/ 子包单元测试。 + +helpers / should_skip / join_decision 三个子模块。 +helpers 已在 test_filter_logging.py 间接覆盖;本文件做子包内部验证。 +""" +from __future__ import annotations + +import time + +import pytest + +from douyin.fudai.core.fudai_filter_pkg import ( + _is_short_countdown_text, + basic_join_decision, + check_contain, + is_watch_task_fudai, + should_skip_fudai_by_config, +) + + +# ============================================================ +# helpers.py — _is_short_countdown_text / check_contain / is_watch_task_fudai +# ============================================================ + +class TestIsShortCountdownText: + """实际语义:剩余 ≤ 2 秒。""" + + @pytest.mark.parametrize( + "text,expected", + [ + ("00:00", True), + ("00:02", True), + ("0:01", True), + ("00秒", True), + ("02秒", True), + ("00:03", False), + ("0:30", False), + ("3秒", False), + ("", False), + ], + ) + def test_threshold(self, text, expected): + assert _is_short_countdown_text(text) is expected + + +class TestIsWatchTaskFudai: + @pytest.mark.parametrize( + "content,expected", + [ + ("观看3分钟即可参与", True), + ("观看5分钟", True), + ("需要观看10分钟", True), + ("现金红包", False), + ("", False), + ], + ) + def test_detect(self, content, expected): + assert is_watch_task_fudai(content) is expected + + +class TestCheckContain: + """check_contain 实际逻辑:内容命中黑名单返回 True(应跳过)。""" + + def test_no_blacklist_returns_false(self): + class A: + contains_not_want = [] + def _log_kv(self, *a, **k): pass + # 内容里没东西可以命中黑名单 + assert check_contain(A(), "现金红包") is False + + def test_blacklist_match_returns_true(self): + class A: + contains_not_want = ["袜子"] + def _log_kv(self, *a, **k): pass + assert check_contain(A(), "袜子礼盒") is True + + def test_blacklist_no_match_returns_false(self): + class A: + contains_not_want = ["袜子"] + def _log_kv(self, *a, **k): pass + assert check_contain(A(), "现金红包") is False + + +# ============================================================ +# should_skip.py — 通过子包路径调用,应与 fudai_filter_pkg / 主入口等价 +# ============================================================ + +class TestShouldSkipFudaiByConfig: + def _mock(self, **kw): + class M: + def __init__(s, **kw): + s.needswitch = True + s.min_prize_value_yuan = 0.0 + s.min_participants = 0 + s.max_participants = 0 + s.skip_if_countdown_lt_seconds = 0 + s.contains_want = [] + s.contains_not_want = [] + for k, v in kw.items(): + setattr(s, k, v) + def _log_kv(self, *a, **k): pass + return M(**kw) + + def test_high_value_passes(self): + analyser = self._mock() + detail = ('现金1000元', '2分钟', 50, 1, 1000.0, + (time.time()+120, time.time()+120)) + skip, reason = should_skip_fudai_by_config(analyser, detail) + assert skip is False + assert reason == "ok" + + def test_watch_task_skips(self): + analyser = self._mock() + detail = ('观看3分钟即可参与', '3分钟', 5, 1, 100.0, + (time.time()+180, time.time()+180)) + skip, reason = should_skip_fudai_by_config(analyser, detail) + assert skip is True + assert "watch" in reason.lower() or "观看" in reason + + def test_low_value_skips(self): + analyser = self._mock(min_prize_value_yuan=500.0) + detail = ('现金100元', '2分钟', 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, + (time.time()+120, time.time()+120)) + skip, _ = should_skip_fudai_by_config(analyser, detail) + assert skip is True + + 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, + (time.time()+120, time.time()+120)) + skip, reason = should_skip_fudai_by_config(analyser, detail) + assert skip is False + assert "single" in reason.lower() or "single_room" in reason + + def test_invalid_detail_does_not_raise(self): + analyser = self._mock() + # 传单元素 tuple,函数应兜底返回 (False, ...) 而非抛异常 + skip, reason = should_skip_fudai_by_config(analyser, ("only_one",)) + assert isinstance(skip, bool) + assert isinstance(reason, str) + + +# ============================================================ +# join_decision.py — basic_join_decision +# ============================================================ + +class TestBasicJoinDecisionExists: + """basic_join_decision 业务依赖很多 analyser 状态,只测可调用性。""" + + def test_callable(self): + assert callable(basic_join_decision) diff --git a/tests/test_logging_pkg.py b/tests/test_logging_pkg.py new file mode 100644 index 0000000..1cf9a98 --- /dev/null +++ b/tests/test_logging_pkg.py @@ -0,0 +1,211 @@ +"""douyin/logging/douyin_logging_pkg/ 子包单元测试。 + +覆盖: +- _common 全局状态 +- handlers 类构造 +- cleanup 纯函数(compress_log_file、cleanup_old_logs 边界情况) +- monitor LogRotationMonitor 类构造 / start/stop(不真启线程) +- config get_logger / get_caller_info / format_exception_info / LogContext +""" +from __future__ import annotations + +import logging +import os +import sys + +import pytest + +from douyin.logging.douyin_logging_pkg import ( + DatedFileHandler, + LogContext, + LogRotationMonitor, + RotatingDatedFileHandler, + cleanup_old_logs, + compress_log_file, + format_exception_info, + get_caller_info, + get_log_stats, + get_logger, + log_function_call, +) +from douyin.logging.douyin_logging_pkg import _common as _state + + +# ============================================================ +# _common.py — 全局状态 +# ============================================================ + +class TestCommonState: + def test_logger_cache_is_dict(self): + assert isinstance(_state._logger_cache, dict) + + def test_logging_configured_is_bool(self): + assert isinstance(_state._logging_configured, bool) + + +# ============================================================ +# handlers.py +# ============================================================ + +class TestHandlersConstruct: + def test_rotating_dated_file_handler(self, tmp_path): + # 不实际写盘,只看构造能否成功 + h = RotatingDatedFileHandler( + base_filename=str(tmp_path / "test.log"), + max_bytes=1024, + backup_count=2, + compress_old=False, + ) + assert h is not None + h.close() + + def test_dated_file_handler(self, tmp_path): + h = DatedFileHandler( + base_filename=str(tmp_path / "dated.log"), + ) + assert h is not None + h.close() + + +# ============================================================ +# cleanup.py +# ============================================================ + +class TestCompressLogFile: + def test_missing_file_returns_false(self, tmp_path): + result = compress_log_file(str(tmp_path / "nonexistent.log")) + # 文件不存在应返回 False(或 0/None),实现可能不同 + assert result in (False, None, 0) + + def test_compress_real_file(self, tmp_path): + log_file = tmp_path / "to_compress.log" + log_file.write_text("some log content\n" * 100, encoding="utf-8") + + result = compress_log_file(str(log_file)) + # 真实文件应能成功压缩或返回成功标志 + # 压缩成功后会生成 .gz 并删原文件 + if result: + assert (tmp_path / "to_compress.log.gz").exists() + + +class TestCleanupOldLogs: + def test_empty_dir_returns_zero_counts(self, tmp_path): + result = cleanup_old_logs( + logs_dir=str(tmp_path), + base_name="test", + keep_days=30, + ) + assert isinstance(result, dict) + # 至少应含 'deleted' / 'compressed' 等 key(具体看实现) + + def test_nonexistent_dir_does_not_raise(self, tmp_path): + # 不存在的目录应不抛 + result = cleanup_old_logs( + logs_dir=str(tmp_path / "nonexistent"), + base_name="test", + ) + assert isinstance(result, dict) + + +# ============================================================ +# monitor.py — LogRotationMonitor +# ============================================================ + +class TestLogRotationMonitorConstruct: + def test_construct(self, tmp_path): + m = LogRotationMonitor( + logs_dir=str(tmp_path), + base_name="test", + warning_size_mb=10.0, + critical_size_mb=100.0, + check_interval=60, + ) + assert m.logs_dir == str(tmp_path) + assert m.base_name == "test" + + def test_running_flag_default_false(self, tmp_path): + m = LogRotationMonitor(logs_dir=str(tmp_path), base_name="t") + # 实例化后不应立即开始运行 + assert getattr(m, "_running", False) is False + + +class TestGetLogStats: + def test_empty_dir(self, tmp_path): + result = get_log_stats(str(tmp_path), "test") + assert isinstance(result, dict) + + +# ============================================================ +# config.py +# ============================================================ + +class TestGetLogger: + def test_returns_logger(self): + log = get_logger("smoke.test_logging_pkg") + assert isinstance(log, logging.Logger) + + def test_cached(self): + # 同名两次应返回同一对象 + log1 = get_logger("smoke.same_name_xyz123") + log2 = get_logger("smoke.same_name_xyz123") + assert log1 is log2 + + def test_default_name(self): + # 不传名字应返回 root logger 或默认 logger + log = get_logger() + assert isinstance(log, logging.Logger) + + +class TestGetCallerInfo: + def test_returns_dict_with_keys(self): + info = get_caller_info() + assert isinstance(info, dict) + # 实际 key 是 file / line / function / module + for key in ("file", "line", "function"): + assert key in info, f"missing key: {key}" + + +class TestFormatExceptionInfo: + def test_with_no_exception(self): + # 没活跃异常时应返回空串或可序列化 + result = format_exception_info(None) + assert isinstance(result, str) + + def test_with_exception(self): + try: + raise ValueError("test error xyz") + except ValueError: + result = format_exception_info(sys.exc_info()) + assert isinstance(result, str) + assert "ValueError" in result or "test error" in result + + +class TestLogContext: + def test_construct(self): + ctx = LogContext("test message") + assert ctx is not None + + def test_use_as_context_manager(self): + with LogContext("test step", level="DEBUG"): + pass # 不应抛异常 + + +class TestLogFunctionCallDecorator: + def test_returns_decorator(self): + decorator = log_function_call() + assert callable(decorator) + + def test_decorate_simple_function(self): + @log_function_call() + def double(x): + return x * 2 + + assert double(5) == 10 + + def test_decorated_function_with_exception(self): + @log_function_call() + def bad(): + raise RuntimeError("bad") + + with pytest.raises(RuntimeError): + bad()