diff --git a/tests/test_action_logger.py b/tests/test_action_logger.py new file mode 100644 index 0000000..fb2e72e --- /dev/null +++ b/tests/test_action_logger.py @@ -0,0 +1,87 @@ +"""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_decision(self, alog, caplog): + with caplog.at_level(logging.INFO): + alog.log_decision("参与", elapsed=0.05) + alog.log_decision("跳过") + + def test_log_state_change(self, alog, caplog): + with caplog.at_level(logging.INFO): + alog.log_state_change("recommend", "live_room", elapsed=0.5) + alog.log_state_change("A", "B") + + def test_log_ocr(self, alog, caplog): + with caplog.at_level(logging.INFO): + alog.log_ocr("countdown_region", "00:30", elapsed=0.1) + alog.log_ocr("region", "") + + 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