"""douyin/utils/param_usage_tracker 的 pytest 单元测试。 覆盖 track_param / track_call 装饰器 / read_entries。注意 tracker 默认写入 state/param_usage.json,测试用 monkeypatch 把日志路径改到 tmp_path,避免污染 真实 state/ 目录。 """ from __future__ import annotations import json import pytest from douyin.utils import param_usage_tracker as tracker @pytest.fixture def isolated_log(tmp_path, monkeypatch): """把 _get_log_path 重定向到 tmp_path,避免污染 state/。""" log_file = tmp_path / "param_usage.json" monkeypatch.setattr(tracker, "_get_log_path", lambda: str(log_file)) return log_file # ============================================================ # track_param # ============================================================ class TestTrackParam: def test_writes_one_entry(self, isolated_log): tracker.track_param("threshold", 42) assert isolated_log.is_file() lines = isolated_log.read_text(encoding="utf-8").strip().splitlines() assert len(lines) == 1 entry = json.loads(lines[0]) assert entry["param"] == "threshold" assert entry["value"] == "42" assert entry["type"] == "param_access" # 必有调用方信息 assert "caller_file" in entry assert "caller_line" in entry def test_extra_fields_merged(self, isolated_log): tracker.track_param("x", "v", extra={"context": "test", "trace_id": "abc"}) entry = json.loads(isolated_log.read_text(encoding="utf-8").strip()) assert entry["context"] == "test" assert entry["trace_id"] == "abc" def test_appends_multiple(self, isolated_log): for i in range(3): tracker.track_param(f"p{i}", i) lines = isolated_log.read_text(encoding="utf-8").strip().splitlines() assert len(lines) == 3 def test_unrepresentable_value_does_not_crash(self, isolated_log): class BadRepr: def __repr__(self): raise RuntimeError("repr broken") # 应不抛 + 写入兜底字符串 tracker.track_param("bad", BadRepr()) entry = json.loads(isolated_log.read_text(encoding="utf-8").strip()) assert "value" in entry # 至少有 value 字段 # ============================================================ # track_call 装饰器 # ============================================================ class TestTrackCall: def test_records_call_with_args(self, isolated_log): @tracker.track_call() def add(a, b): return a + b assert add(2, 3) == 5 entry = json.loads(isolated_log.read_text(encoding="utf-8").strip()) assert entry["type"] == "call" assert entry["func_name"] == "add" assert "params" in entry assert entry["params"]["a"] == "2" assert entry["params"]["b"] == "3" def test_skip_args_when_disabled(self, isolated_log): @tracker.track_call(include_args=False) def fn(a, b): return a * b fn(2, 3) entry = json.loads(isolated_log.read_text(encoding="utf-8").strip()) assert "params" not in entry def test_preserves_function_metadata(self, isolated_log): @tracker.track_call() def my_func(): """docstring.""" return 42 assert my_func.__name__ == "my_func" assert my_func.__doc__ == "docstring." def test_exception_propagates(self, isolated_log): @tracker.track_call() def raises(): raise ValueError("boom") with pytest.raises(ValueError): raises() # 注意:实现是先 _write_ndjson 再 func(),所以异常时也会写一条 call 记录 # 但具体行为不强求,只要不崩 + 异常被传播 def test_kwargs_recorded(self, isolated_log): @tracker.track_call() def fn(*, x, y=1): return (x, y) fn(x=10, y=20) entry = json.loads(isolated_log.read_text(encoding="utf-8").strip()) assert entry["params"]["x"] == "10" assert entry["params"]["y"] == "20" # ============================================================ # read_entries # ============================================================ class TestReadEntries: def test_no_log_returns_empty(self, isolated_log): # 文件不存在 → [] assert tracker.read_entries() == [] def test_reads_back_what_was_written(self, isolated_log): for i in range(5): tracker.track_param(f"k{i}", i) entries = tracker.read_entries() assert len(entries) == 5 assert entries[0]["param"] == "k0" assert entries[-1]["param"] == "k4" def test_limit_returns_recent(self, isolated_log): for i in range(10): tracker.track_param(f"k{i}", i) last3 = tracker.read_entries(limit=3) assert len(last3) == 3 assert last3[0]["param"] == "k7" assert last3[-1]["param"] == "k9" def test_skips_malformed_lines(self, isolated_log): # 手动写入一条坏行 + 一条好行 isolated_log.write_text( "this-is-not-json\n" + json.dumps({"k": "v"}) + "\n", encoding="utf-8", ) entries = tracker.read_entries() assert len(entries) == 1 assert entries[0] == {"k": "v"}