import json import socketserver import threading import time from pathlib import Path import pytest import stats_data from stats_data import (Container, StatsReader, cpu_pct, list_containers, parse_cpu_times, parse_mem_pct, parse_pid_stat, short_name, status_label) FIXTURES = Path(__file__).parent / "fixtures" # --- pure parsers ----------------------------------------------------------- def test_parse_cpu_times_and_pct(): first = parse_cpu_times("cpu 100 0 50 800 50 0 0 0 0 0\ncpu0 1 2 3 4 5 6 7 8 9 10\n") second = parse_cpu_times("cpu 200 0 100 1600 100 0 0 0 0 0\n") assert first == (150, 1000) # busy = total - idle - iowait assert second == (300, 2000) assert cpu_pct(first, second) == pytest.approx(15.0) def test_cpu_pct_none_without_previous(): assert cpu_pct(None, (300, 2000)) is None def test_cpu_pct_none_on_zero_delta(): assert cpu_pct((300, 2000), (300, 2000)) is None def test_parse_mem_pct_real_fixture(): # fixture: MemTotal 16147480 kB, MemAvailable 13909124 kB (home server) assert parse_mem_pct((FIXTURES / "meminfo").read_text()) == pytest.approx(13.86, abs=0.01) def test_parse_pid_stat_with_parens_and_spaces(): text = "4242 (my (odd) proc) S 1 4242 4242 0 -1 4194304 100 0 0 0 70 30 0 0 20 0 1 0 12345 1 2" assert parse_pid_stat(text) == ("my (odd) proc", 100) @pytest.mark.parametrize("name, expected", [ ("n8n-ebe62bdjbp9f755kwh59lv8d", "n8n"), ("screen-pe28mpghgqnxaz12vyfyijrg-151725872213", "screen"), ("task-runners-ebe62bdjbp9f755kwh59lv8d", "task-runners"), ("plex-z0qh1wrbuzxo0jsfiazc3evc", "plex"), ("coolify-db", "coolify-db"), ]) def test_short_name_strips_coolify_suffix(name, expected): assert short_name(name, {}, "x/y:1") == expected def test_short_name_hash_only_uses_label_then_image_then_hash(): hashed = "jn5mdu87ituoxzyojk84ugdj-20261018T132559" assert short_name(hashed, {"com.docker.compose.service": "web"}, "a/b:1") == "web" assert short_name(hashed, {}, "ghcr.io/acme/tool:1.2") == "tool" # the real container on the server: hash in name, label and image assert short_name(hashed, {"com.docker.compose.service": hashed}, "jn5mdu87ituoxzyojk84ugdj:1833c2f1bf67cbe93e579ed6d9b569fe3cd3b668") == "jn5mdu87" @pytest.mark.parametrize("state, health, expected", [ ("running", "healthy", "OK"), ("running", None, "UP"), ("running", "starting", "UP"), ("running", "unhealthy", "UNHEALTHY"), ("restarting", None, "RESTART"), ("exited", None, "EXITED"), ]) def test_status_label_cases(state, health, expected): assert status_label(Container("x", state, health)) == expected # --- docker over a unix socket --------------------------------------------- class FakeDocker: """Tiny HTTP server on a unix socket (relative path: macOS limits socket paths to ~100 chars).""" def __init__(self, path: str, body: bytes = b"[]", hang: bool = False): self.release = threading.Event() self.requests = 0 outer = self class Handler(socketserver.StreamRequestHandler): def handle(self): while self.rfile.readline() not in (b"\r\n", b""): pass outer.requests += 1 if hang: outer.release.wait(5) return self.wfile.write(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" + f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n".encode() + body) self.server = socketserver.ThreadingUnixStreamServer(path, Handler) self.server.daemon_threads = True self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) self.thread.start() def close(self): self.release.set() self.server.shutdown() self.server.server_close() @pytest.fixture def docker_in(tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) servers = [] def make(body=b"[]", hang=False): s = FakeDocker("d.sock", body, hang) servers.append(s) make.server = s return "d.sock" yield make for s in servers: s.close() def test_list_containers_parses_fixture(docker_in): sock = docker_in((FIXTURES / "docker_containers.json").read_bytes()) containers = {c.name: c for c in list_containers(sock)} assert containers["coolify"] == Container("coolify", "running", "healthy") assert containers["n8n"].health == "healthy" assert containers["screen"] == Container("screen", "running", None) assert containers["apod-test"].state == "exited" assert "jn5mdu87" in containers def test_list_containers_missing_socket_raises(tmp_path): with pytest.raises(OSError): list_containers(str(tmp_path / "nope.sock")) # --- reader on a fake /proc tree --------------------------------------------- def write_proc(root: Path, cpu: str, procs: dict[int, str]): root.mkdir(parents=True, exist_ok=True) (root / "stat").write_text(cpu + "\n") (root / "meminfo").write_text((FIXTURES / "meminfo").read_text()) (root / "loadavg").write_text("0.60 0.52 0.44 3/777 3724104\n") (root / "uptime").write_text("934423.99 5265468.77\n") for pid, stat in procs.items(): (root / str(pid)).mkdir(exist_ok=True) (root / str(pid) / "stat").write_text(stat) def pid_line(pid, name, ticks): return f"{pid} ({name}) S 1 {pid} {pid} 0 -1 4194304 0 0 0 0 {ticks} 0 0 0 20 0 1 0 1 1 1\n" def thermal(sys_root: Path, zones: dict[str, tuple[str, int]]): for zone, (kind, milli) in zones.items(): z = sys_root / "class" / "thermal" / zone z.mkdir(parents=True) (z / "type").write_text(kind + "\n") (z / "temp").write_text(f"{milli}\n") def make_reader(tmp_path, docker_sock="missing.sock", **kw): kw.setdefault("docker_every", 0.0) kw.setdefault("proc_every", 0.0) proc, sys_root = tmp_path / "proc", tmp_path / "sys" thermal(sys_root, {"thermal_zone0": ("acpitz", 30000), "thermal_zone1": ("x86_pkg_temp", 41000)}) write_proc(proc, "cpu 100 0 50 800 50 0 0 0 0 0", {10: pid_line(10, "postgres", 0), 11: pid_line(11, "postgres", 0), 12: pid_line(12, "node", 0)}) return StatsReader(proc_root=str(proc), sys_root=str(sys_root), disk_path=str(tmp_path), docker_sock=docker_sock, **kw), proc def test_reader_first_read_has_no_cpu_pct(tmp_path): reader, _ = make_reader(tmp_path) s = reader.read() assert s.cpu_pct is None and s.procs == () assert s.mem_pct == pytest.approx(13.86, abs=0.01) assert s.load == (0.60, 0.52, 0.44) assert s.uptime_s == pytest.approx(934423.99) assert 0 <= s.disk_pct <= 100 def test_reader_second_read_has_cpu_and_grouped_processes(tmp_path): reader, proc = make_reader(tmp_path) reader.read() write_proc(proc, "cpu 200 0 100 1600 100 0 0 0 0 0", {10: pid_line(10, "postgres", 60), 11: pid_line(11, "postgres", 40), 12: pid_line(12, "node", 20)}) s = reader.read() assert s.cpu_pct == pytest.approx(15.0) names = [(p.name, round(p.cpu_pct, 1)) for p in s.procs] assert names == [("postgres", 10.0), ("node", 2.0)] # share of total jiffies delta (1000), grouped by name def test_reader_prefers_cpu_package_temperature(tmp_path): reader, _ = make_reader(tmp_path) assert reader.read().temp_c == 41.0 def test_reader_temperature_falls_back_to_hottest_zone(tmp_path): reader, _ = make_reader(tmp_path) for z in (tmp_path / "sys" / "class" / "thermal").glob("thermal_zone1"): (z / "type").write_text("other\n") assert reader.read().temp_c == 41.0 def test_reader_survives_vanished_process(tmp_path): reader, proc = make_reader(tmp_path) reader.read() (proc / "12" / "stat").unlink() # directory still listed, file gone: the process exited mid-read write_proc(proc, "cpu 200 0 100 1600 100 0 0 0 0 0", {10: pid_line(10, "postgres", 10)}) s = reader.read() assert s.cpu_pct == pytest.approx(15.0) assert [p.name for p in s.procs] == ["postgres"] def test_reader_docker_down_still_returns_other_stats(tmp_path): reader, _ = make_reader(tmp_path, docker_sock=str(tmp_path / "nope.sock")) s = reader.read() assert s.containers is None assert s.mem_pct is not None def test_reader_reads_containers(tmp_path, docker_in): sock = docker_in((FIXTURES / "docker_containers.json").read_bytes()) reader, _ = make_reader(tmp_path, docker_sock=sock) s = reader.read() assert s.containers is not None and any(c.name == "n8n" for c in s.containers) def test_reader_docker_hang_times_out(tmp_path, docker_in): sock = docker_in(hang=True) reader, _ = make_reader(tmp_path, docker_sock=sock, docker_timeout=0.3) start = time.monotonic() s = reader.read() assert time.monotonic() - start < 2.0 assert s.containers is None and s.mem_pct is not None def test_reader_missing_proc_files_give_none_not_error(tmp_path): reader = StatsReader(proc_root=str(tmp_path / "nothing"), sys_root=str(tmp_path / "nothing"), disk_path=str(tmp_path / "nothing"), docker_sock="missing.sock") s = reader.read() assert (s.cpu_pct, s.mem_pct, s.disk_pct, s.load, s.temp_c, s.uptime_s, s.containers) == (None,) * 7 assert s.procs == () class FakeClock: def __init__(self): self.t = 0.0 def __call__(self): return self.t def test_reader_asks_docker_only_every_docker_every_seconds(tmp_path, docker_in): sock = docker_in((FIXTURES / "docker_containers.json").read_bytes()) clock = FakeClock() reader, _ = make_reader(tmp_path, docker_sock=sock, docker_every=5.0, clock=clock) first = reader.read() clock.t = 1.0 second = reader.read() assert docker_in.server.requests == 1 assert second.containers == first.containers and second.containers is not None clock.t = 5.5 reader.read() assert docker_in.server.requests == 2 def test_reader_caches_a_docker_failure_for_the_interval_too(tmp_path): clock = FakeClock() reader, _ = make_reader(tmp_path, docker_sock=str(tmp_path / "nope.sock"), docker_every=5.0, clock=clock) assert reader.read().containers is None clock.t = 1.0 assert reader.read().containers is None # no new attempt, still reported as unavailable def test_reader_ranks_processes_over_a_longer_window(tmp_path): clock = FakeClock() reader, proc = make_reader(tmp_path, proc_every=3.0, clock=clock) assert reader.read().procs == () # first snapshot clock.t = 1.0 write_proc(proc, "cpu 600 0 300 2400 100 0 0 0 0 0", {10: pid_line(10, "postgres", 10)}) assert reader.read().procs == () # window not over yet: nothing new to rank clock.t = 3.5 write_proc(proc, "cpu 900 0 450 3600 150 0 0 0 0 0", {10: pid_line(10, "postgres", 60)}) s = reader.read() # 60 ticks over a jiffy window of 5100 - 1000 = 4100 -> 1.46 % assert [(p.name, round(p.cpu_pct, 2)) for p in s.procs] == [("postgres", 1.46)] clock.t = 4.0 assert reader.read().procs == s.procs # between windows the last ranking stays on screen