gui_app.py 的 ThreadSafeLogWriter 类(109 行)是自包含的日志文件写入器: threading.Lock 保护、按日期分割、配置开关、PermissionError/Exception 兜底。 抽到 gui/components/log_writer.py,原 gui_app 中的 109 行类定义 + 1 行实例化 替换为 3 行导入 + 实例化。read_config 通过 staticmethod _read_config 延迟导入, 避免循环依赖。 新增 15 个单元测试覆盖: - __init__:默认 log_dir / 配置开关 / dated_logs / 相对路径解析 / 配置异常兜底 - write:正常写 / 禁用跳过 / 空行跳过 / 时间戳前缀 / 已格式化行原样写 - 100 线程 × 10 行的并发安全测试(确认 1000 行无丢失) - PermissionError / 通用异常下不抛 + warn 一次 1408 passed (+15)。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
234 lines
9.1 KiB
Python
234 lines
9.1 KiB
Python
"""gui/components/log_writer 单元测试。
|
||
|
||
ThreadSafeLogWriter 写日志文件 + 配置开关 + 日期分割。
|
||
所有测试用 tmp_path 隔离,避免污染真实 logs/ 目录。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import threading
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from unittest.mock import patch
|
||
|
||
import pytest
|
||
|
||
from gui.components.log_writer import ThreadSafeLogWriter
|
||
|
||
|
||
def _patch_config(monkeypatch, cfg):
|
||
"""让 _read_config 返回指定 cfg。"""
|
||
monkeypatch.setattr(
|
||
ThreadSafeLogWriter, "_read_config", staticmethod(lambda: cfg)
|
||
)
|
||
|
||
|
||
# ============================================================
|
||
# __init__ / _init_log_file
|
||
# ============================================================
|
||
|
||
class TestInit:
|
||
def test_default_log_dir_used_when_none(self, tmp_path, monkeypatch):
|
||
_patch_config(monkeypatch, {"log_unified_enabled": True})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
assert writer._log_dir == str(tmp_path)
|
||
assert writer._log_file_enabled is True
|
||
|
||
def test_log_unified_enabled_false(self, tmp_path, monkeypatch):
|
||
_patch_config(monkeypatch, {"log_unified_enabled": False})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
assert writer._log_file_enabled is False
|
||
|
||
def test_dated_logs_default_appends_today(self, tmp_path, monkeypatch):
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_path": str(tmp_path / "test.log"),
|
||
"logging": {"use_dated_logs": True},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
today = datetime.now().strftime("%Y-%m-%d")
|
||
assert writer._log_file_path.endswith(f"_{today}.log")
|
||
|
||
def test_dated_logs_disabled_keeps_path(self, tmp_path, monkeypatch):
|
||
path = str(tmp_path / "test.log")
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_path": path,
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
assert writer._log_file_path == path
|
||
|
||
def test_relative_path_resolved_to_project_root(self, tmp_path, monkeypatch):
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_path": "logs/relative.log",
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
# 路径应该是绝对的(拼到 PROJECT_ROOT)
|
||
assert os.path.isabs(writer._log_file_path)
|
||
assert "relative.log" in writer._log_file_path
|
||
|
||
def test_config_read_failure_falls_back_to_default(self, tmp_path, monkeypatch):
|
||
"""模拟配置读取抛异常,仍能初始化(用兜底路径)。"""
|
||
def broken_config():
|
||
raise RuntimeError("config broken")
|
||
monkeypatch.setattr(
|
||
ThreadSafeLogWriter, "_read_config",
|
||
staticmethod(broken_config),
|
||
)
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
# 应该用兜底路径,包含 unified_<日期>.log
|
||
today = datetime.now().strftime("%Y-%m-%d")
|
||
assert f"unified_{today}.log" in writer._log_file_path
|
||
|
||
|
||
# ============================================================
|
||
# write
|
||
# ============================================================
|
||
|
||
class TestWrite:
|
||
def test_write_appends_to_file(self, tmp_path, monkeypatch):
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_enabled": True,
|
||
"log_unified_path": str(tmp_path / "test.log"),
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
writer.write("hello")
|
||
writer.write("world")
|
||
with open(writer._log_file_path, "r", encoding="utf-8-sig") as f:
|
||
content = f.read()
|
||
assert "hello" in content
|
||
assert "world" in content
|
||
|
||
def test_write_disabled_skips(self, tmp_path, monkeypatch):
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_enabled": False,
|
||
"log_unified_path": str(tmp_path / "test.log"),
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
writer.write("should not appear")
|
||
assert not os.path.exists(writer._log_file_path)
|
||
|
||
def test_write_empty_line_skipped(self, tmp_path, monkeypatch):
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_enabled": True,
|
||
"log_unified_path": str(tmp_path / "test.log"),
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
writer.write("")
|
||
writer.write(" ")
|
||
# 文件可能根本没创建,或者创建了但空(tolerate both)
|
||
if os.path.exists(writer._log_file_path):
|
||
with open(writer._log_file_path, "r", encoding="utf-8-sig") as f:
|
||
content = f.read()
|
||
assert content.strip() == ""
|
||
|
||
def test_write_adds_timestamp_prefix(self, tmp_path, monkeypatch):
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_enabled": True,
|
||
"log_unified_path": str(tmp_path / "test.log"),
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
writer.write("plain message")
|
||
with open(writer._log_file_path, "r", encoding="utf-8-sig") as f:
|
||
content = f.read()
|
||
# 应含 [GUI] 前缀和时间戳
|
||
assert "[GUI]" in content
|
||
assert "plain message" in content
|
||
|
||
def test_write_preserves_existing_timestamp(self, tmp_path, monkeypatch):
|
||
"""已含 'YYYY-MM-DD HH:MM:SS - [' 前缀的行应原样写。"""
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_enabled": True,
|
||
"log_unified_path": str(tmp_path / "test.log"),
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
# 行以数字开头 + " - [" 模式 → 不再加前缀
|
||
writer.write("2026-05-22 12:00:00 - [INFO] - already formatted")
|
||
with open(writer._log_file_path, "r", encoding="utf-8-sig") as f:
|
||
content = f.read()
|
||
# [GUI] 不应出现
|
||
assert "[GUI]" not in content
|
||
assert "[INFO] - already formatted" in content
|
||
|
||
|
||
# ============================================================
|
||
# 线程安全
|
||
# ============================================================
|
||
|
||
class TestThreadSafety:
|
||
def test_concurrent_writes_no_loss(self, tmp_path, monkeypatch):
|
||
"""100 线程并发写各 10 行,最终文件应有 1000 行。"""
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_enabled": True,
|
||
"log_unified_path": str(tmp_path / "concurrent.log"),
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
|
||
def worker(thread_id: int):
|
||
for i in range(10):
|
||
writer.write(f"thread-{thread_id}-line-{i}")
|
||
|
||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(100)]
|
||
for t in threads:
|
||
t.start()
|
||
for t in threads:
|
||
t.join()
|
||
|
||
with open(writer._log_file_path, "r", encoding="utf-8-sig") as f:
|
||
content = f.read()
|
||
# 1000 行(每个非空)
|
||
non_empty_lines = [ln for ln in content.splitlines() if ln.strip()]
|
||
assert len(non_empty_lines) == 1000
|
||
|
||
|
||
# ============================================================
|
||
# 错误兜底
|
||
# ============================================================
|
||
|
||
class TestErrorHandling:
|
||
def test_permission_error_does_not_crash(self, tmp_path, monkeypatch, caplog):
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_enabled": True,
|
||
"log_unified_path": str(tmp_path / "test.log"),
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
|
||
with patch("builtins.open", side_effect=PermissionError("no perms")):
|
||
# 不应抛
|
||
writer.write("hello")
|
||
assert writer._write_error_warned is True
|
||
|
||
def test_generic_exception_does_not_crash(self, tmp_path, monkeypatch):
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_enabled": True,
|
||
"log_unified_path": str(tmp_path / "test.log"),
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
|
||
with patch("builtins.open", side_effect=RuntimeError("disk full")):
|
||
writer.write("hello")
|
||
assert writer._write_error_warned is True
|
||
|
||
def test_error_only_warns_once(self, tmp_path, monkeypatch):
|
||
"""重复出错时 _write_error_warned 永久 True,避免日志噪音。"""
|
||
_patch_config(monkeypatch, {
|
||
"log_unified_enabled": True,
|
||
"log_unified_path": str(tmp_path / "test.log"),
|
||
"logging": {"use_dated_logs": False},
|
||
})
|
||
writer = ThreadSafeLogWriter(log_dir=str(tmp_path))
|
||
writer._write_error_warned = True
|
||
|
||
with patch("builtins.open", side_effect=PermissionError):
|
||
writer.write("hello")
|
||
# 仍是 True
|
||
assert writer._write_error_warned is True
|