SHA256
61 lines
1.7 KiB
Python
61 lines
1.7 KiB
Python
"""验证 src.log.get_logger 的命名空间和幂等性"""
|
|
|
|
import logging
|
|
|
|
import pytest
|
|
|
|
from src import log as log_mod
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _reset_initialized():
|
|
"""每个测试都从未初始化状态开始,避免 handler 残留串扰其他测试"""
|
|
saved = log_mod._INITIALIZED
|
|
yield
|
|
log_mod._INITIALIZED = saved
|
|
|
|
|
|
def test_logger_has_ashare_namespace():
|
|
logger = log_mod.get_logger("daily")
|
|
assert logger.name == "ashare.daily"
|
|
|
|
|
|
def test_init_is_idempotent():
|
|
"""重复调用 _init_root 不应叠加 handler"""
|
|
log_mod._INITIALIZED = False
|
|
root = logging.getLogger("ashare")
|
|
root.handlers.clear()
|
|
|
|
log_mod._init_root()
|
|
first_count = len(root.handlers)
|
|
log_mod._init_root()
|
|
second_count = len(root.handlers)
|
|
|
|
assert first_count == second_count
|
|
assert first_count >= 1 # 至少有 stdout handler
|
|
|
|
|
|
def test_root_does_not_propagate():
|
|
"""ashare logger 不应向 root 冒泡,避免重复输出"""
|
|
log_mod._INITIALIZED = False
|
|
log_mod._init_root()
|
|
root = logging.getLogger("ashare")
|
|
assert root.propagate is False
|
|
|
|
|
|
def test_log_level_from_env(monkeypatch):
|
|
"""ASHARE_LOG_LEVEL 环境变量应改变 root 日志级别"""
|
|
monkeypatch.setenv("ASHARE_LOG_LEVEL", "DEBUG")
|
|
log_mod._INITIALIZED = False
|
|
logging.getLogger("ashare").handlers.clear()
|
|
log_mod._init_root()
|
|
assert logging.getLogger("ashare").level == logging.DEBUG
|
|
|
|
|
|
def test_unknown_log_level_falls_back_to_info(monkeypatch):
|
|
monkeypatch.setenv("ASHARE_LOG_LEVEL", "NONSENSE")
|
|
log_mod._INITIALIZED = False
|
|
logging.getLogger("ashare").handlers.clear()
|
|
log_mod._init_root()
|
|
assert logging.getLogger("ashare").level == logging.INFO
|