Files
douyi_guaji_main/tests/test_action_logger.py

85 lines
2.6 KiB
Python

"""douyin/logging/action_logger 的 pytest 单元测试。
覆盖 ActionLogger 5 个 log_* 方法 + track_action 装饰器。这些方法都是
"侧效应函数"(写日志),断言侧重在不抛异常 + 装饰器透传值 + handler 可获取。
"""
from __future__ import annotations
import logging
import pytest
from douyin.logging.action_logger import ActionLogger, track_action
@pytest.fixture
def alog():
return ActionLogger()
# ============================================================
# log_* 5 个方法:调用不抛
# ============================================================
class TestActionLoggerMethods:
def test_log_step(self, alog, caplog):
with caplog.at_level(logging.INFO):
alog.log_step("test_step", elapsed=0.01)
alog.log_step("no_elapsed")
def test_log_operation(self, alog, caplog):
with caplog.at_level(logging.INFO):
alog.log_operation("click", details="button_x", x=100, y=200)
alog.log_operation("simple_op")
def test_log_operation_preserves_elapsed_seconds_kwarg(self, alog, caplog):
with caplog.at_level(logging.INFO):
alog.log_operation("click", details="button_x", elapsed_seconds=1.23)
assert any("耗时=1230.00ms" in r.getMessage() for r in caplog.records)
def test_log_operation_preserves_elapsed_kwarg(self, alog, caplog):
with caplog.at_level(logging.INFO):
alog.log_operation("click", details="button_x", elapsed=0.48)
assert any("耗时=480.00ms" in r.getMessage() for r in caplog.records)
def test_long_kwargs_does_not_raise(self, alog):
# 大量 kwargs 不应导致格式化失败
alog.log_operation("complex", **{f"k{i}": i for i in range(50)})
# ============================================================
# track_action 装饰器
# ============================================================
class TestTrackAction:
def test_passes_through_return_value(self):
@track_action("test_op")
def add(a, b):
return a + b
assert add(2, 3) == 5
def test_default_name_uses_func_name(self):
@track_action()
def my_func():
return "result"
assert my_func() == "result"
def test_exception_propagates(self):
@track_action("test_op")
def raises():
raise ValueError("boom")
with pytest.raises(ValueError):
raises()
def test_does_not_swallow_kwargs(self):
@track_action("with_kwargs")
def fn(*, x):
return x * 2
assert fn(x=5) == 10