| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218 |
- """``scripts/soak_watch.py`` 的日志解析 / 判据单测(不需要板卡、不需要 C++ 构建)。
- 守三件事(2026-11-16 板端 30 min 浸泡实测暴露的两个真缺陷都在这里):
- 1. **带时间戳前缀的 ``[stat]`` 行也要解析出来**:经 systemd / journald / ``tee``
- 转发后行首会多出 ``16:17:55 | INFO | portcv.runner | ``,旧实现用
- ``line.startswith("[stat]")`` 匹配,``frames`` 恒为 ``None``,进度停滞判据等于失效;
- 2. **Python 版 ``portcv run`` 的单行摘要也要认**(``seq= fps= lat= ... pub=``),
- 否则同一个脚本盯不了 Python 服务;
- 3. **进程异常退出 / 样本太少时不许判"无泄漏"**:旧实现会在子进程秒退(rc≠0,
- 例如端口被占用)时输出"结论: 无明显泄漏迹象",这是最危险的一类假绿。
- """
- from __future__ import annotations
- import importlib.util
- import os
- import sys
- import tempfile
- import unittest
- ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- if ROOT not in sys.path:
- sys.path.insert(0, ROOT)
- def _load(name: str = "soak_watch"):
- """按路径加载 ``scripts/<name>.py``(scripts 不是包,沿用 test_check_configs 的写法)。"""
- path = os.path.join(ROOT, "scripts", name + ".py")
- spec = importlib.util.spec_from_file_location(name, path)
- module = importlib.util.module_from_spec(spec)
- assert spec.loader is not None
- sys.modules.setdefault(name, module)
- spec.loader.exec_module(module)
- return module
- sw = _load()
- CXX_RAW = "[stat] 已发布 50 帧,本轮 15.0 fps(滑窗 15.0 fps),单帧 全程均 12.34 / 近 50 帧 p50 12.10 p95 15.80 p99 18.20 / 最大 18.20 ms"
- CXX_EXIT = "实测帧率: 滑窗 14.7 fps(26 个采样 / 2.0 s 窗口) 发布 fps_x10=147 LOW_FPS 下限=3.0"
- PY_STATUS = ("16:17:55 | INFO | portcv.runner | state=2(no_container,0.42) seq=88 fps=15.0 "
- "lat=63ms npr=97% frames=441 pub=441 chg=0 err=0")
- class ReadLogProgressTest(unittest.TestCase):
- def _write(self, text: str) -> str:
- fd, path = tempfile.mkstemp(suffix=".log")
- os.close(fd)
- with open(path, "w", encoding="utf-8") as fh:
- fh.write(text)
- self.addCleanup(os.unlink, path)
- return path
- def test_cxx_raw_line(self):
- got = sw.read_log_progress(self._write(CXX_RAW + "\n"))
- self.assertEqual(got["frames"], 50)
- self.assertIsNone(got["fps"]) # [stat] 行只给"本轮 fps",不给 fps_x10
- self.assertEqual(got["warn_lines"], 0)
- def test_cxx_exit_fps_x10(self):
- got = sw.read_log_progress(self._write(CXX_EXIT + "\n"))
- self.assertEqual(got["fps"], 14.7)
- self.assertIsNone(got["frames"])
- def test_prefixed_stat_line_still_parsed(self):
- """回归:行首带时间戳前缀时也要能抓到帧数(旧实现这里恒为 None)。"""
- text = "16:17:55 | INFO | portcv.runner | " + CXX_RAW + "\n"
- got = sw.read_log_progress(self._write(text))
- self.assertEqual(got["frames"], 50)
- self.assertIn("已发布 50 帧", got["last"])
- def test_python_status_line(self):
- got = sw.read_log_progress(self._write(PY_STATUS + "\n"))
- self.assertEqual(got["frames"], 441) # 取 pub=(已发布)口径
- self.assertEqual(got["fps"], 15.0)
- self.assertEqual(got["errors"], 0)
- def test_last_progress_wins(self):
- text = "\n".join([
- PY_STATUS,
- PY_STATUS.replace("seq=88", "seq=900").replace("pub=441", "pub=9000"),
- ]) + "\n"
- got = sw.read_log_progress(self._write(text))
- self.assertEqual(got["frames"], 9000)
- def test_warn_counting_both_styles(self):
- text = "\n".join([
- "[warn] 实测帧率 1.50 fps < 下限 3.00 → flags.LOW_FPS=1",
- "16:20:01 | WARNING | portcv.io.capture | 取流失败:rtsp 超时",
- PY_STATUS,
- ]) + "\n"
- self.assertEqual(sw.read_log_progress(self._write(text))["warn_lines"], 2)
- def test_missing_file_is_neutral(self):
- got = sw.read_log_progress(os.path.join(tempfile.gettempdir(), "definitely-absent-soak.log"))
- self.assertIsNone(got["frames"])
- self.assertIsNone(got["fps"])
- self.assertEqual(got["bytes"], 0)
- class TrendHelpersTest(unittest.TestCase):
- def test_slope_per_min(self):
- # 每 10 s +1 MB → 6 MB/min
- samples = [(float(t), float(t) / 10.0) for t in range(0, 120, 10)]
- self.assertAlmostEqual(sw.slope_per_min(samples), 6.0, places=6)
- def test_slope_needs_three_points(self):
- self.assertEqual(sw.slope_per_min([(0.0, 1.0), (10.0, 2.0)]), 0.0)
- def test_rise_ratio(self):
- rising = [(float(t), float(t)) for t in range(0, 180, 10)]
- flat = [(float(t), 5.0) for t in range(0, 180, 10)]
- self.assertEqual(sw.rise_ratio(rising), 1.0)
- self.assertEqual(sw.rise_ratio(flat), 0.0)
- class VerdictTest(unittest.TestCase):
- def test_child_failure_is_not_green(self):
- """回归:子进程秒退(rc≠0)时不许输出"无泄漏迹象",退出码必须是 1。"""
- with tempfile.TemporaryDirectory() as tmp:
- rc = sw.main([
- "--interval", "0.1", "--minutes", "0.05", "--warmup", "0",
- "--outdir", tmp,
- "--", sys.executable, "-c",
- "import sys, time; time.sleep(0.3); sys.exit(3)",
- ])
- self.assertEqual(rc, 1)
- txt = [os.path.join(tmp, n) for n in os.listdir(tmp) if n.endswith(".txt")]
- self.assertEqual(len(txt), 1)
- with open(txt[0], encoding="utf-8") as fh:
- body = fh.read()
- self.assertIn("不作数", body)
- self.assertNotIn("无明显泄漏迹象", body)
- def test_clean_child_is_green(self):
- """子进程正常退出(rc=0)时不该被误判为异常。"""
- with tempfile.TemporaryDirectory() as tmp:
- rc = sw.main([
- "--interval", "0.1", "--minutes", "0.05", "--warmup", "0",
- "--outdir", tmp,
- "--", sys.executable, "-c", "import time; time.sleep(0.6)",
- ])
- self.assertEqual(rc, 0)
- class ProcStatusTest(unittest.TestCase):
- """Linux 采样口径:``private_mb`` 必须是 RssAnon,不是 VmSize。"""
- STATUS = """Name:\tpython
- VmSize:\t1526876 kB
- VmRSS:\t 146820 kB
- RssAnon:\t 95360 kB
- VmHWM:\t 147600 kB
- Threads:\t24
- """
- def test_private_is_rss_anon_not_vmsize(self):
- got = sw.parse_proc_status(self.STATUS)
- self.assertAlmostEqual(got["rss_mb"], 146820 / 1024.0, places=3)
- self.assertAlmostEqual(got["private_mb"], 95360 / 1024.0, places=3)
- self.assertAlmostEqual(got["peak_rss_mb"], 147600 / 1024.0, places=3)
- self.assertEqual(got["threads"], 24)
- def test_missing_keys_are_absent(self):
- self.assertEqual(sw.parse_proc_status("Name:\tpython\n"), {})
- class ThreadLeakTest(unittest.TestCase):
- def test_exec_instant_not_counted(self):
- """回归:t=0 的 1 线程长到 24 后稳定,不该判泄漏(预热窗口内才是判定区间)。"""
- warmup = [{"threads": 1}, {"threads": 24}]
- post = [{"threads": 24}, {"threads": 24}, {"threads": 24}]
- self.assertEqual(sw.thread_leak(post), "")
- # 直接把含 exec 瞬间的序列喂进去会误报 —— 所以 main() 只传预热后的窗口
- self.assertIn("疑似线程泄漏", sw.thread_leak(warmup))
- def test_real_rise_is_reported(self):
- post = [{"threads": 20}, {"threads": 21}, {"threads": 24}]
- self.assertIn("疑似线程泄漏", sw.thread_leak(post))
- def test_too_few_samples(self):
- self.assertEqual(sw.thread_leak([]), "")
- self.assertEqual(sw.thread_leak([{"threads": 24}]), "")
- class ReplayTest(unittest.TestCase):
- """``--replay``:拿旧 CSV 用修好的判据重算(板端 30 min 那份就是这么救回来的)。"""
- HEADER = ("t_s,wall,rss_mb,private_mb,peak_rss_mb,paged_pool_mb,nonpaged_pool_mb,"
- "handles,threads,cpu_s,io_read_mb,io_write_mb,frames,fps,warn_lines,alive")
- def test_replay_ignores_exec_instant(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = os.path.join(tmp, "soak_x.csv")
- lines = [self.HEADER,
- "0.0,16:00:00,0.0,6.8,0,0,0,4,1,0,0,0,,,0,1", # exec 瞬间
- "10.0,16:00:10,146.0,95.0,147,0,0,10,24,17,0,0,,,0,1"] # 起来之后
- for i in range(2, 13):
- lines.append("%d.0,16:00:%02d,146.0,95.0,147,0,0,10,24,%d,0,0,,,0,1"
- % (i * 10, i, i * 17))
- with open(path, "w", encoding="utf-8") as fh:
- fh.write("\n".join(lines) + "\n")
- rc = sw.main(["--replay", path, "--warmup", "60"])
- self.assertEqual(rc, 0)
- with open(os.path.join(tmp, "soak_x.replay.txt"), encoding="utf-8") as fh:
- body = fh.read()
- self.assertIn("预热后首 24 → 末 24", body)
- self.assertNotIn("疑似线程泄漏", body)
- if __name__ == "__main__":
- unittest.main()
|