"""gui/components/realtime_viewer 单元测试。 只测纯函数 _tail_read / _parse_minimal。 open_realtime_viewer 涉及 Tk Toplevel + 后台计时器,单测难度高,跳过。 """ from __future__ import annotations import pytest from gui.components.realtime_viewer import _parse_minimal, _tail_read # ============================================================ # _tail_read # ============================================================ class TestTailRead: def test_nonexistent_file_returns_empty(self, tmp_path): assert _tail_read(str(tmp_path / "nope.log")) == [] def test_small_file_returns_all_lines(self, tmp_path): p = tmp_path / "test.log" p.write_text("line1\nline2\nline3\n", encoding="utf-8") result = _tail_read(str(p)) assert result == ["line1", "line2", "line3"] def test_large_file_truncated_to_max_bytes(self, tmp_path): p = tmp_path / "test.log" # 写 100 行 text = "\n".join(f"line{i:04d}" for i in range(1000)) p.write_text(text, encoding="utf-8") # max_bytes=200 → 只读末尾 200 字节 result = _tail_read(str(p), max_bytes=200) # 末尾几行应该都在 assert any("line0999" in line for line in result) # 开头不应在 assert not any("line0000" in line for line in result) def test_invalid_encoding_does_not_crash(self, tmp_path): p = tmp_path / "binary.log" p.write_bytes(b"\xff\xfe valid text \n line2\n\xff\xfe") # decode(errors="ignore") 应该跳过无效字节 result = _tail_read(str(p)) assert isinstance(result, list) def test_empty_file(self, tmp_path): p = tmp_path / "empty.log" p.write_text("", encoding="utf-8") assert _tail_read(str(p)) == [] # ============================================================ # _parse_minimal # ============================================================ class TestParseMinimal: def test_no_耗时_returns_none(self): assert _parse_minimal("普通日志行 没有 timing 信息") is None def test_耗时_with_colon(self): result = _parse_minimal("点击参与按钮 耗时:1.5s") assert result == ("点击参与按钮", "1.5s") def test_耗时_with_equals(self): result = _parse_minimal("OCR识别 耗时=2.3s") assert result == ("OCR识别", "2.3s") def test_耗时_no_separator(self): # "耗时 1.5s" → 应回落到 "([0-9]+s)" pattern result = _parse_minimal("操作完成 耗时 1.5s") # action 取 idx="耗时" 之前的文本 = "操作完成 " assert result is not None assert result[0] == "操作完成" assert result[1] == "1.5s" def test_耗时_present_but_no_seconds_returns_none(self): # "耗时未知" 没有数字 → None assert _parse_minimal("某操作 耗时未知") is None def test_action_truncated_to_80_chars(self): long_action = "a" * 100 result = _parse_minimal(f"{long_action} 耗时:1.5s") assert result is not None action, dur = result assert len(action) <= 80 assert action.endswith("...") assert dur == "1.5s" def test_empty_action_uses_line_start(self): result = _parse_minimal("耗时:0.5s") assert result is not None action, dur = result # action 为空时回退到 line.strip()[:80] assert action == "耗时:0.5s" def test_integer_duration(self): result = _parse_minimal("步骤A 耗时:5s") assert result == ("步骤A", "5s")