[CI] Add five unittest (#4958)

* add unittest

* Update test_logger.py
This commit is contained in:
Echo-Nie
2025-11-12 10:43:33 +08:00
committed by GitHub
parent a5103eb198
commit 2aabaecbc2
5 changed files with 363 additions and 120 deletions
+52 -59
View File
@@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import logging
import os
@@ -26,13 +25,8 @@ from fastdeploy.logger.setup_logging import setup_logging
class TestSetupLogging(unittest.TestCase):
# -------------------------------------------------
# 夹具:每个测试独占临时目录
# -------------------------------------------------
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="logger_setup_test_")
# 统一 patch 环境变量
self.patches = [
patch("fastdeploy.envs.FD_LOG_DIR", self.temp_dir),
patch("fastdeploy.envs.FD_DEBUG", 0),
@@ -43,92 +37,91 @@ class TestSetupLogging(unittest.TestCase):
def tearDown(self):
[p.stop() for p in self.patches]
shutil.rmtree(self.temp_dir, ignore_errors=True)
# 清理单例标记,避免影响其他测试
if hasattr(setup_logging, "_configured"):
delattr(setup_logging, "_configured")
# -------------------------------------------------
# 基础:目录自动创建
# -------------------------------------------------
def test_log_dir_created(self):
nested = os.path.join(self.temp_dir, "a", "b", "c")
setup_logging(log_dir=nested)
self.assertTrue(Path(nested).is_dir())
# -------------------------------------------------
# 默认配置文件:文件 handler 不带颜色
# -------------------------------------------------
def test_default_config_file_no_ansi(self):
setup_logging()
def test_default_config_fallback(self):
"""Pass a non-existent config_file to trigger default_config"""
fake_cfg = os.path.join(self.temp_dir, "no_such_cfg.json")
setup_logging(config_file=fake_cfg)
logger = logging.getLogger("fastdeploy")
logger.error("test ansi")
self.assertTrue(logger.handlers)
handler_classes = [h.__class__.__name__ for h in logger.handlers]
self.assertIn("TimedRotatingFileHandler", handler_classes[0])
default_file = Path(self.temp_dir) / "default.log"
self.assertTrue(default_file.exists())
with default_file.open() as f:
content = f.read()
# 文件中不应出现 ANSI 转义
self.assertNotIn("\033[", content)
# -------------------------------------------------
# 调试级别开关
# -------------------------------------------------
def test_debug_level(self):
def test_debug_level_affects_handlers(self):
"""FD_DEBUG=1 should force DEBUG level"""
with patch("fastdeploy.envs.FD_DEBUG", 1):
setup_logging()
logger = logging.getLogger("fastdeploy")
self.assertEqual(logger.level, logging.DEBUG)
# debug 消息应该能落到文件
logger.debug("debug msg")
default_file = Path(self.temp_dir) / "default.log"
self.assertIn("debug msg", default_file.read_text())
with patch("logging.config.dictConfig") as mock_cfg:
setup_logging()
called_config = mock_cfg.call_args[0][0]
for handler in called_config["handlers"].values():
self.assertIn("formatter", handler)
self.assertEqual(called_config["handlers"]["console"]["level"], "DEBUG")
# -------------------------------------------------
# 自定义 JSON 配置文件加载
# -------------------------------------------------
def test_custom_config_file(self):
@patch("logging.config.dictConfig")
def test_custom_config_with_dailyrotating_and_debug(self, mock_dict):
custom_cfg = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {"plain": {"format": "%(message)s"}},
"handlers": {
"custom": {
"class": "logging.FileHandler",
"filename": os.path.join(self.temp_dir, "custom.log"),
"daily": {
"class": "logging.handlers.DailyRotatingFileHandler",
"level": "INFO",
"formatter": "plain",
}
},
"loggers": {"fastdeploy": {"handlers": ["custom"], "level": "INFO"}},
"loggers": {"fastdeploy": {"handlers": ["daily"], "level": "INFO"}},
}
cfg_path = Path(self.temp_dir) / "cfg.json"
cfg_path.write_text(json.dumps(custom_cfg))
setup_logging(config_file=str(cfg_path))
logger = logging.getLogger("fastdeploy")
logger.info("from custom cfg")
with patch("fastdeploy.envs.FD_DEBUG", 1):
setup_logging(config_file=str(cfg_path))
custom_file = Path(self.temp_dir) / "custom.log"
self.assertEqual(custom_file.read_text().strip(), "from custom cfg")
config_used = mock_dict.call_args[0][0]
self.assertIn("daily", config_used["handlers"])
self.assertEqual(config_used["handlers"]["daily"]["level"], "DEBUG")
self.assertIn("backupCount", config_used["handlers"]["daily"])
# -------------------------------------------------
# 重复调用 setup_logging 不会重复配置
# -------------------------------------------------
def test_configure_once(self):
logger1 = setup_logging()
logger2 = setup_logging()
self.assertIs(logger1, logger2)
"""Ensure idempotent setup"""
l1 = setup_logging()
l2 = setup_logging()
self.assertIs(l1, l2)
def test_envs_priority_used_for_log_dir(self):
"""When log_dir=None, should use envs.FD_LOG_DIR"""
with patch("fastdeploy.envs.FD_LOG_DIR", self.temp_dir):
setup_logging()
self.assertTrue(os.path.exists(self.temp_dir))
# -------------------------------------------------
# 控制台 handler 使用 ColoredFormatter
# -------------------------------------------------
@patch("logging.StreamHandler.emit")
def test_console_colored(self, mock_emit):
setup_logging()
logger = logging.getLogger("fastdeploy")
logger.error("color test")
# 只要 ColoredFormatter 被实例化即可,简单断言 emit 被调用
self.assertTrue(mock_emit.called)
@patch("logging.config.dictConfig")
def test_backup_count_merging(self, mock_dict):
custom_cfg = {
"version": 1,
"handlers": {"daily": {"class": "logging.handlers.DailyRotatingFileHandler", "formatter": "plain"}},
"loggers": {"fastdeploy": {"handlers": ["daily"], "level": "INFO"}},
}
cfg_path = Path(self.temp_dir) / "cfg.json"
cfg_path.write_text(json.dumps(custom_cfg))
setup_logging(config_file=str(cfg_path))
config_used = mock_dict.call_args[0][0]
self.assertEqual(config_used["handlers"]["daily"]["backupCount"], 3)
if __name__ == "__main__":
unittest.main()