""" GUI日志写入功能测试脚本 用于验证GUI应用的日志文件写入功能是否正常工作 """ import os import sys import time import threading from datetime import datetime # 确保在项目根目录 os.chdir(os.path.dirname(os.path.abspath(__file__))) # 添加项目路径 sys.path.insert(0, os.path.dirname(__file__)) from path_config import get_logs_dir, PROJECT_ROOT from gui_core import read_config def test_log_writer(): """测试日志写入器的基本功能""" print("=" * 60) print("测试1: 日志写入器基本功能") print("=" * 60) # 导入GUI应用中的日志写入器类 # 由于日志写入器是在main函数内部定义的,我们需要模拟它 import threading import queue class ThreadSafeLogWriter: """线程安全的日志文件写入器""" def __init__(self, log_dir: str | None = None): self._lock = threading.Lock() self._log_dir = log_dir or get_logs_dir() self._log_file_path: str = "" self._log_file_enabled: bool = True self._init_log_file() self._write_error_warned = False def _init_log_file(self) -> None: """初始化日志文件路径(按日期)""" try: os.makedirs(self._log_dir, exist_ok=True) cfg = read_config() self._log_file_enabled = bool(cfg.get("log_unified_enabled", True)) log_path = cfg.get("log_unified_path") or "logs/unified.log" if not os.path.isabs(log_path): log_path = os.path.join(PROJECT_ROOT, log_path) use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True) if use_dated_logs: base_name = os.path.splitext(log_path)[0] today = datetime.now().strftime("%Y-%m-%d") self._log_file_path = f"{base_name}_{today}.log" else: self._log_file_path = log_path except Exception as e: today = datetime.now().strftime("%Y-%m-%d") self._log_file_path = os.path.join(self._log_dir, f"unified_{today}.log") print(f"[测试] 配置读取失败,使用默认路径: {e}") def write(self, line: str) -> None: """线程安全地写入日志行到文件""" if not self._log_file_enabled: return if not line or not line.strip(): return with self._lock: try: cfg = read_config() use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True) if use_dated_logs: today = datetime.now().strftime("%Y-%m-%d") current_base = os.path.splitext(self._log_file_path)[0] if not current_base.endswith(today): base_name = current_base.rsplit("_", 1)[0] if "_" in os.path.basename(current_base) else current_base self._log_file_path = f"{base_name}_{today}.log" log_dir = os.path.dirname(self._log_file_path) if log_dir: os.makedirs(log_dir, exist_ok=True) with open( self._log_file_path, "a", encoding="utf-8-sig", errors="replace" ) as f: if line.strip() and not (line[0].isdigit() and " - [" in line): timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] formatted_line = f"{timestamp} - [GUI] - {line}\n" else: formatted_line = f"{line}\n" f.write(formatted_line) f.flush() except Exception as e: if not self._write_error_warned: print(f"[测试] 写入日志文件失败: {e}") self._write_error_warned = True # 创建日志写入器 writer = ThreadSafeLogWriter() print(f"[测试] 日志文件路径: {writer._log_file_path}") print(f"[测试] 日志目录: {writer._log_dir}") print(f"[测试] 日志启用状态: {writer._log_file_enabled}") # 测试写入 test_lines = [ "这是一条测试日志", "2025-12-22 12:00:00.000 - [INFO] - 这是带时间戳的日志", "测试中文日志:你好世界", "测试特殊字符:!@#$%^&*()", ] print("\n[测试] 开始写入测试日志...") for line in test_lines: writer.write(line) print(f"[测试] 已写入: {line}") # 验证文件是否存在 if os.path.exists(writer._log_file_path): print(f"\n[测试] [OK] 日志文件已创建: {writer._log_file_path}") file_size = os.path.getsize(writer._log_file_path) print(f"[测试] [OK] 文件大小: {file_size} bytes") # 读取文件内容验证 with open(writer._log_file_path, "r", encoding="utf-8-sig") as f: content = f.read() lines = content.strip().split("\n") print(f"[测试] [OK] 文件包含 {len(lines)} 行") print("\n[测试] 文件内容预览(最后5行):") for line in lines[-5:]: print(f" {line}") else: print(f"\n[测试] [FAIL] 日志文件未创建: {writer._log_file_path}") return False return True def test_thread_safety(): """测试多线程环境下的日志写入安全性""" print("\n" + "=" * 60) print("测试2: 多线程安全性") print("=" * 60) # 使用与上面相同的日志写入器类 import threading class ThreadSafeLogWriter: def __init__(self, log_dir: str | None = None): self._lock = threading.Lock() self._log_dir = log_dir or get_logs_dir() self._log_file_path: str = "" self._log_file_enabled: bool = True self._init_log_file() self._write_error_warned = False def _init_log_file(self) -> None: try: os.makedirs(self._log_dir, exist_ok=True) cfg = read_config() self._log_file_enabled = bool(cfg.get("log_unified_enabled", True)) log_path = cfg.get("log_unified_path") or "logs/unified.log" if not os.path.isabs(log_path): log_path = os.path.join(PROJECT_ROOT, log_path) use_dated_logs = cfg.get("logging", {}).get("use_dated_logs", True) if use_dated_logs: base_name = os.path.splitext(log_path)[0] today = datetime.now().strftime("%Y-%m-%d") self._log_file_path = f"{base_name}_{today}.log" else: self._log_file_path = log_path except Exception: today = datetime.now().strftime("%Y-%m-%d") self._log_file_path = os.path.join(self._log_dir, f"unified_{today}.log") def write(self, line: str) -> None: if not self._log_file_enabled or not line or not line.strip(): return with self._lock: try: log_dir = os.path.dirname(self._log_file_path) if log_dir: os.makedirs(log_dir, exist_ok=True) with open(self._log_file_path, "a", encoding="utf-8-sig", errors="replace") as f: if line.strip() and not (line[0].isdigit() and " - [" in line): timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] formatted_line = f"{timestamp} - [GUI] - {line}\n" else: formatted_line = f"{line}\n" f.write(formatted_line) f.flush() except Exception: pass writer = ThreadSafeLogWriter() # 创建多个线程同时写入 def write_thread(thread_id: int, count: int): for i in range(count): writer.write(f"[线程{thread_id}] 日志消息 {i+1}") time.sleep(0.001) # 短暂延迟模拟真实场景 num_threads = 5 messages_per_thread = 20 print(f"[测试] 启动 {num_threads} 个线程,每个线程写入 {messages_per_thread} 条消息...") threads = [] for i in range(num_threads): t = threading.Thread(target=write_thread, args=(i+1, messages_per_thread)) threads.append(t) t.start() # 等待所有线程完成 for t in threads: t.join() print("[测试] 所有线程已完成写入") # 验证文件完整性 if os.path.exists(writer._log_file_path): with open(writer._log_file_path, "r", encoding="utf-8-sig") as f: content = f.read() lines = [l for l in content.strip().split("\n") if l.strip()] expected_lines = num_threads * messages_per_thread print(f"[测试] [OK] 文件包含 {len(lines)} 行(预期约 {expected_lines} 行)") # 检查是否有重复或丢失 thread_counts = {} for line in lines: if "[线程" in line: thread_id = line.split("[线程")[1].split("]")[0] thread_counts[thread_id] = thread_counts.get(thread_id, 0) + 1 print(f"[测试] [OK] 各线程写入统计:") for thread_id in sorted(thread_counts.keys()): print(f" 线程{thread_id}: {thread_counts[thread_id]} 条") return True else: print("[测试] [FAIL] 日志文件未创建") return False def test_log_file_integrity(): """测试日志文件完整性""" print("\n" + "=" * 60) print("测试3: 日志文件完整性检查") print("=" * 60) log_dir = get_logs_dir() today = datetime.now().strftime("%Y-%m-%d") # 查找今天的日志文件 log_files = [] if os.path.exists(log_dir): for fname in os.listdir(log_dir): if fname.endswith(f"_{today}.log") or fname == "unified.log": log_files.append(os.path.join(log_dir, fname)) if not log_files: print("[测试] [FAIL] 未找到日志文件") return False print(f"[测试] 找到 {len(log_files)} 个日志文件:") for log_file in log_files: print(f" - {log_file}") if os.path.exists(log_file): file_size = os.path.getsize(log_file) print(f" 大小: {file_size} bytes") # 读取文件检查格式 try: with open(log_file, "r", encoding="utf-8-sig") as f: lines = f.readlines() print(f" 行数: {len(lines)}") # 检查最后几行的格式 if lines: print(" 最后3行示例:") for line in lines[-3:]: line = line.strip() if line: print(f" {line[:80]}...") except Exception as e: print(f" [FAIL] 读取文件失败: {e}") return False return True if __name__ == "__main__": print("GUI日志写入功能测试") print("=" * 60) results = [] # 运行测试 try: results.append(("基本功能", test_log_writer())) results.append(("线程安全", test_thread_safety())) results.append(("文件完整性", test_log_file_integrity())) except Exception as e: print(f"\n[错误] 测试过程中发生异常: {e}") import traceback traceback.print_exc() sys.exit(1) # 汇总结果 print("\n" + "=" * 60) print("测试结果汇总") print("=" * 60) all_passed = True for test_name, passed in results: status = "[PASS] 通过" if passed else "[FAIL] 失败" print(f"{test_name}: {status}") if not passed: all_passed = False if all_passed: print("\n[总结] 所有测试通过!日志写入功能正常。") sys.exit(0) else: print("\n[总结] 部分测试失败,请检查日志写入功能。") sys.exit(1)