tests: 新增 check_contain + log_formatter 测试 (41 用例)
- test_check_contain.py:fudai_filter.check_contain 黑名单关键词检查 * 空黑名单 / 命中 / 未命中 / None / 空字符串 * 命中后短路(不继续遍历) * 黑名单空字符串关键词不误匹配 * 缺 contains_not_want 属性 / broken _log_kv 兜底 - test_log_formatter.py:9 个格式化纯函数 * format_action_log / format_debug_log / format_error_log(前缀 + tag + 字段) * format_parameters / format_variables / format_call_stack * format_exception(含 traceback) * add_colors(默认绿 / red / 未知颜色兜底) * add_separators(带/不带 label) * beautify_log_output / colorize_log_line(不抛 + 一致性) 回归:tests/ 308 passed / 1 skipped。 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
1 parent
a39da30d16
commit
dba43e18f9
2 files changed
+269
No files matched your search
@@ -0,0 +1,85 @@
|
||||
"""douyin/fudai/core/fudai_filter.check_contain 的 pytest 单元测试。
|
||||
|
||||
check_contain 是黑名单关键词检查(只保留黑名单逻辑):
|
||||
- True → 命中 analyser.contains_not_want 中任一关键词,"建议丢弃"
|
||||
- False → 未命中,"可以保留"
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.fudai.core.fudai_filter import check_contain
|
||||
|
||||
|
||||
class FakeAnalyser:
|
||||
def __init__(self, contains_not_want=None):
|
||||
self.contains_not_want = contains_not_want if contains_not_want is not None else []
|
||||
self.log_calls = []
|
||||
|
||||
def _log_kv(self, *args, **kwargs):
|
||||
self.log_calls.append((args, kwargs))
|
||||
|
||||
|
||||
class TestCheckContain:
|
||||
def test_no_blacklist_returns_false(self):
|
||||
"""空黑名单 → 任何内容都不命中。"""
|
||||
a = FakeAnalyser(contains_not_want=[])
|
||||
assert check_contain(a, "现金红包") is False
|
||||
|
||||
def test_blacklist_hit_returns_true(self):
|
||||
a = FakeAnalyser(contains_not_want=["袜子", "首饰盒"])
|
||||
assert check_contain(a, "精美袜子礼盒") is True
|
||||
|
||||
def test_blacklist_miss_returns_false(self):
|
||||
a = FakeAnalyser(contains_not_want=["袜子", "首饰盒"])
|
||||
assert check_contain(a, "现金红包 100 元") is False
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"contains,expected",
|
||||
[
|
||||
("", False), # 空字符串
|
||||
(None, False), # None(应被视为空)
|
||||
("袜子", True), # 命中
|
||||
("现金", False), # 未命中
|
||||
],
|
||||
)
|
||||
def test_various_inputs(self, contains, expected):
|
||||
a = FakeAnalyser(contains_not_want=["袜子"])
|
||||
assert check_contain(a, contains) is expected
|
||||
|
||||
def test_first_match_short_circuits(self):
|
||||
"""命中第一个关键词后立即返回,不继续遍历。"""
|
||||
a = FakeAnalyser(contains_not_want=["袜子", "首饰盒", "优惠券"])
|
||||
check_contain(a, "袜子礼盒")
|
||||
# 日志应只记录一次"命中"
|
||||
hit_logs = [c for c in a.log_calls if "命中黑名单" in str(c)]
|
||||
assert len(hit_logs) == 1
|
||||
|
||||
def test_empty_keyword_in_list_does_not_match(self):
|
||||
"""黑名单里的空字符串关键词不应误命中任何内容。"""
|
||||
a = FakeAnalyser(contains_not_want=["", "袜子"])
|
||||
assert check_contain(a, "现金红包") is False
|
||||
assert check_contain(a, "袜子") is True
|
||||
|
||||
def test_missing_attribute_does_not_crash(self):
|
||||
"""analyser 没有 contains_not_want 属性也不应抛。"""
|
||||
|
||||
class A:
|
||||
def _log_kv(self, *a, **kw):
|
||||
pass
|
||||
|
||||
# getattr 兜底为 [] → 不命中
|
||||
assert check_contain(A(), "袜子") is False
|
||||
|
||||
def test_broken_log_kv_does_not_raise(self):
|
||||
"""analyser._log_kv 抛异常也不应让 check_contain 崩。"""
|
||||
|
||||
class A:
|
||||
contains_not_want = ["袜子"]
|
||||
|
||||
def _log_kv(self, *args, **kwargs):
|
||||
raise RuntimeError("logger broken")
|
||||
|
||||
# 命中 + 未命中两条路径都试
|
||||
assert check_contain(A(), "袜子") is True
|
||||
assert check_contain(A(), "现金") is False
|
||||
@@ -0,0 +1,184 @@
|
||||
"""douyin/logging/log_formatter 的 pytest 单元测试。
|
||||
|
||||
覆盖 9 个格式化纯函数:
|
||||
- format_action_log / format_debug_log / format_error_log
|
||||
- format_parameters / format_variables / format_call_stack
|
||||
- format_exception / add_colors / add_separators
|
||||
- beautify_log_output / colorize_log_line(一致性 + 不抛断言)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.logging import log_formatter as f
|
||||
|
||||
|
||||
# ============================================================
|
||||
# format_action_log
|
||||
# ============================================================
|
||||
|
||||
class TestFormatActionLog:
|
||||
def test_action_only(self):
|
||||
assert f.format_action_log("click") == "[ACTION] click"
|
||||
|
||||
def test_action_with_details(self):
|
||||
assert f.format_action_log("click", "button") == "[ACTION] click"
|
||||
|
||||
def test_action_with_kv_fields(self):
|
||||
result = f.format_action_log("click", x=100, y=200)
|
||||
# 字段顺序按 dict 插入序
|
||||
assert "[ACTION] click" in result
|
||||
assert "x=100" in result
|
||||
assert "y=200" in result
|
||||
|
||||
|
||||
# ============================================================
|
||||
# format_debug_log
|
||||
# ============================================================
|
||||
|
||||
class TestFormatDebugLog:
|
||||
def test_default_level(self):
|
||||
assert f.format_debug_log("msg") == "[DEBUG] msg"
|
||||
|
||||
def test_custom_level(self):
|
||||
assert f.format_debug_log("msg", level="INFO") == "[INFO] msg"
|
||||
|
||||
def test_with_tag(self):
|
||||
result = f.format_debug_log("msg", tag="TEST", x=1)
|
||||
assert "[TEST]" in result
|
||||
assert "[DEBUG]" in result
|
||||
assert "msg" in result
|
||||
assert "x=1" in result
|
||||
|
||||
|
||||
# ============================================================
|
||||
# format_error_log
|
||||
# ============================================================
|
||||
|
||||
class TestFormatErrorLog:
|
||||
def test_default_level(self):
|
||||
assert f.format_error_log("failure") == "[ERROR] failure"
|
||||
|
||||
def test_with_tag_and_level(self):
|
||||
result = f.format_error_log("failure", level="WARNING", tag="IO")
|
||||
assert "[IO]" in result
|
||||
assert "[WARNING]" in result
|
||||
assert "failure" in result
|
||||
|
||||
|
||||
# ============================================================
|
||||
# format_parameters / format_variables
|
||||
# ============================================================
|
||||
|
||||
class TestFormatParametersVariables:
|
||||
def test_format_parameters_with_data(self):
|
||||
result = f.format_parameters({"a": 1, "b": "x"})
|
||||
assert "a=1" in result
|
||||
assert "b=x" in result
|
||||
|
||||
def test_format_parameters_empty(self):
|
||||
assert f.format_parameters({}) == ""
|
||||
|
||||
def test_format_variables_with_data(self):
|
||||
result = f.format_variables({"k": "v"})
|
||||
assert "k=v" in result
|
||||
|
||||
def test_format_variables_empty(self):
|
||||
assert f.format_variables({}) == ""
|
||||
|
||||
|
||||
# ============================================================
|
||||
# format_call_stack
|
||||
# ============================================================
|
||||
|
||||
class TestFormatCallStack:
|
||||
def test_empty(self):
|
||||
assert f.format_call_stack() == ""
|
||||
|
||||
def test_with_frames(self):
|
||||
result = f.format_call_stack(["frame1", "frame2"])
|
||||
assert "frame1" in result
|
||||
assert "frame2" in result
|
||||
|
||||
|
||||
# ============================================================
|
||||
# format_exception
|
||||
# ============================================================
|
||||
|
||||
class TestFormatException:
|
||||
def test_includes_traceback(self):
|
||||
try:
|
||||
raise RuntimeError("boom")
|
||||
except RuntimeError as e:
|
||||
result = f.format_exception(e)
|
||||
assert "RuntimeError" in result
|
||||
assert "boom" in result
|
||||
|
||||
def test_returns_string(self):
|
||||
try:
|
||||
raise ValueError("bad")
|
||||
except ValueError as e:
|
||||
result = f.format_exception(e)
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
|
||||
|
||||
# ============================================================
|
||||
# add_colors / add_separators
|
||||
# ============================================================
|
||||
|
||||
class TestAddColors:
|
||||
def test_default_color_green(self):
|
||||
# 默认绿色 ANSI 码 \x1b[32m
|
||||
result = f.add_colors("hi")
|
||||
assert "\x1b[32m" in result
|
||||
assert "hi" in result
|
||||
assert "\x1b[0m" in result
|
||||
|
||||
def test_red_color(self):
|
||||
result = f.add_colors("hi", color="red")
|
||||
assert "\x1b[31m" in result
|
||||
assert "hi" in result
|
||||
|
||||
def test_unknown_color_does_not_crash(self):
|
||||
# 未知颜色应不抛
|
||||
result = f.add_colors("hi", color="不存在的颜色")
|
||||
assert "hi" in result
|
||||
|
||||
|
||||
class TestAddSeparators:
|
||||
def test_with_label(self):
|
||||
result = f.add_separators("content", label="SECTION")
|
||||
assert "content" in result
|
||||
assert "SECTION" in result
|
||||
# 包含分隔线
|
||||
assert "=" * 80 in result
|
||||
|
||||
def test_without_label(self):
|
||||
result = f.add_separators("content")
|
||||
assert "content" in result
|
||||
assert "=" * 80 in result
|
||||
|
||||
|
||||
# ============================================================
|
||||
# beautify_log_output / colorize_log_line(一致性 / 不抛)
|
||||
# ============================================================
|
||||
|
||||
class TestBeautify:
|
||||
@pytest.mark.parametrize(
|
||||
"line",
|
||||
["plain line", "", "[INFO] message", "中文行", "x" * 500],
|
||||
)
|
||||
def test_does_not_crash(self, line):
|
||||
result = f.beautify_log_output(line)
|
||||
assert isinstance(result, str)
|
||||
|
||||
|
||||
class TestColorize:
|
||||
@pytest.mark.parametrize(
|
||||
"line",
|
||||
["test", "", "[ERROR] something failed", "中文行"],
|
||||
)
|
||||
def test_does_not_crash(self, line):
|
||||
result = f.colorize_log_line(line)
|
||||
assert isinstance(result, str)
|
||||
Reference in new issue
Block a user