"""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()