Files
lightgui_python/tests/test_monitor.py
T
Muse cff0c74605 Fix gauge arcs: stray diagonal line; wall-time per-process CPU%
- Cairo arc() draws a connecting line from the current point to
  the arc start, and _wtext() leaves a current point (move_to +
  show_text), so the tachometer / arc / donut gauges grew a stray
  diagonal in the track color. New _arc_stroke() helper does
  new_path() before every arc.
- Tachometer digital readout moved below the hub (was colliding
  with the 0/max tick labels).
- XProcessList CPU% is now per-core against per-process wall
  time: on this VPS /proc/stat totals advance at only ~320
  jiffies/s for 8 cores (host vCPU scheduling), so the stat
  denominator inflated a busy loop to ~240%; wall time gives
  ~97% (verified live against a busy loop).
2026-12-05 17:07:19 +00:00

416 lines
16 KiB
Python

"""Tests for the X* monitor family (15 widgets, registry 547-561).
Display-free: widgets draw to offscreen Cairo surfaces (the
test_draw.py pattern). Live /proc checks run only where /proc
exists; where a check can legitimately return None the test
accepts it and checks the demo fallback instead.
"""
import socket
import unittest
import cairo
from lightgui import props
from lightgui.xframe import core
from lightgui.xframe import monitor as monitor_mod
from lightgui.xframe import palette
MONITOR_KINDS = (
"XHistoryGraph", "XCoreGrid", "XNetGraph", "XTempHistory",
"XUsageBar", "XStackBar", "XVerticalBar", "XTachometer",
"XArcGauge", "XDonutGauge", "XProcessList", "XLoadBadge",
"XMonitorButton", "XMonitorGrid", "XSysBox",
)
# (kind, default_w, default_h) -- must match palette.py.
MONITOR_SIZES = {
"XHistoryGraph": (320, 200),
"XCoreGrid": (320, 200),
"XNetGraph": (320, 200),
"XTempHistory": (320, 200),
"XUsageBar": (320, 36),
"XStackBar": (320, 48),
"XVerticalBar": (60, 200),
"XTachometer": (220, 180),
"XArcGauge": (200, 140),
"XDonutGauge": (160, 160),
"XProcessList": (360, 220),
"XLoadBadge": (220, 60),
"XMonitorButton": (200, 48),
"XMonitorGrid": (320, 200),
"XSysBox": (320, 200),
}
def _draw(widget):
"""Draw *widget* on a fresh white surface; return the surface."""
surface = cairo.ImageSurface(
cairo.FORMAT_ARGB32, widget.width + 4, widget.height + 4)
cr = cairo.Context(surface)
cr.set_source_rgb(1, 1, 1)
cr.paint()
widget.draw(cr)
return surface
def _non_white_pixels(surface):
data = surface.get_data()
stride = surface.get_stride()
count = 0
for y in range(surface.get_height()):
row = data[y * stride:(y + 1) * stride]
for x in range(0, len(row), 4):
b, g, r = row[x], row[x + 1], row[x + 2]
if (r, g, b) != (255, 255, 255):
count += 1
return count
def _closed_port():
"""A localhost TCP port nothing is listening on right now."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
sock.close()
return port
class RegistryTests(unittest.TestCase):
def test_15_monitor_kinds_in_palette(self):
for kind in MONITOR_KINDS:
entry = palette.find(kind)
self.assertIsNotNone(entry, kind)
self.assertEqual(entry.family, "X")
self.assertEqual(entry.section, "Misc / X")
self.assertEqual(entry.archetype, "Monitor")
self.assertEqual(entry.kind, kind)
self.assertEqual((entry.default_w, entry.default_h),
MONITOR_SIZES[kind], kind)
def test_indices_are_547_to_561(self):
indices = sorted(palette.find(k).index for k in MONITOR_KINDS)
self.assertEqual(indices, list(range(547, 562)))
def test_lookup_returns_monitor_widget(self):
for kind in MONITOR_KINDS:
cls = core.lookup(kind)
self.assertIs(cls, monitor_mod.MonitorWidget, kind)
self.assertEqual(cls.ARCHETYPE, "Monitor")
widget = core.create(kind, kind + "_001")
self.assertIsNotNone(widget, kind)
self.assertEqual((widget.width, widget.height),
MONITOR_SIZES[kind], kind)
def test_monitor_archetype_in_archetype_classes(self):
self.assertIn("Monitor", core.ARCHETYPE_CLASSES)
self.assertIs(core.ARCHETYPE_CLASSES["Monitor"],
monitor_mod.MonitorWidget)
class DrawTests(unittest.TestCase):
def test_every_monitor_draws_without_crashing(self):
for kind in MONITOR_KINDS:
widget = core.create(kind, kind + "_001")
try:
_draw(widget)
except Exception as exc: # noqa: BLE001 - report the kind
self.fail("%s draw crashed: %r" % (kind, exc))
def test_every_monitor_draws_something(self):
for kind in MONITOR_KINDS:
widget = core.create(kind, kind + "_001")
surface = _draw(widget)
self.assertGreater(_non_white_pixels(surface), 0, kind)
def test_every_monitor_draws_with_live_data(self):
# Exercise the push paths in draw, not just the demo data.
graph = core.create("XHistoryGraph", "XHistoryGraph_001")
for i in range(70):
graph.push(50 + 20 * (i % 2), series=i % 3)
_draw(graph)
cores = core.create("XCoreGrid", "XCoreGrid_001")
for c in range(8):
for i in range(10):
cores.push_core(c, 10 + c * 5)
_draw(cores)
net = core.create("XNetGraph", "XNetGraph_001")
net.push_net(18000, 3000)
_draw(net)
temp = core.create("XTempHistory", "XTempHistory_001")
temp.push(90.0) # over the 80C threshold
_draw(temp)
stack = core.create("XStackBar", "XStackBar_001")
stack.set_segments([("used", 60, "red"), ("free", 40, "green")])
_draw(stack)
procs = core.create("XProcessList", "XProcessList_001")
procs.set_rows([{"pid": 1, "name": "init", "user": "root",
"mem_kb": 1024, "cpu": 75.0}])
_draw(procs)
grid = core.create("XMonitorGrid", "XMonitorGrid_001")
grid.add_monitor("process", "python3", "Python")
_draw(grid)
class HistoryDataTests(unittest.TestCase):
def test_push_starts_fresh_series(self):
# Demo data is shown until the first push; push() does NOT
# extend the demo series (IndicatorWidget convention).
graph = core.create("XHistoryGraph", "XHistoryGraph_001")
demo = graph.get_series(0)
self.assertEqual(len(demo), 60)
graph.push(42.0)
self.assertEqual(graph.get_series(0), [42.0])
def test_push_trims_to_window(self):
graph = core.create("XHistoryGraph", "XHistoryGraph_001")
graph.set_prop("window", 5)
for i in range(8):
graph.push(float(i))
self.assertEqual(graph.get_series(0), [3.0, 4.0, 5.0, 6.0, 7.0])
def test_set_series_replaces(self):
graph = core.create("XHistoryGraph", "XHistoryGraph_001")
graph.set_series([1.0, 2.0, 3.0], series=1)
self.assertEqual(graph.get_series(1), [1.0, 2.0, 3.0])
self.assertEqual(len(graph.get_series(0)), 60) # demo
def test_push_net_accumulates_totals(self):
net = core.create("XNetGraph", "XNetGraph_001")
net.push_net(1000, 500)
net.push_net(2000, 500)
self.assertEqual(net.get_totals(), (3000.0, 1000.0))
self.assertEqual(net.get_series(0), [1000.0, 2000.0])
def test_series_names_default(self):
graph = core.create("XHistoryGraph", "XHistoryGraph_001")
self.assertEqual(graph._series_names(), ["S1", "S2"])
graph.set_prop("series-names", "CPU|MEM")
self.assertEqual(graph._series_names(), ["CPU", "MEM"])
class PeakTests(unittest.TestCase):
def test_set_value_tracks_peak(self):
bar = core.create("XVerticalBar", "XVerticalBar_001")
bar.set_value(65)
bar.set_value(82)
bar.set_value(40)
self.assertEqual(bar.get_peak(), 82.0)
bar.reset_peak()
self.assertEqual(bar.get_peak(), 0.0)
def test_push_tracks_peak(self):
graph = core.create("XHistoryGraph", "XHistoryGraph_001")
graph.push(30)
graph.push(91)
self.assertEqual(graph.get_peak(), 91.0)
class StackBarTests(unittest.TestCase):
def test_set_segments(self):
bar = core.create("XStackBar", "XStackBar_001")
bar.set_segments([("used", 60, (1.0, 0.0, 0.0)),
("free", 40, "green")])
segments = bar.get_segments()
self.assertEqual(segments[0][:2], ("used", 60.0))
self.assertEqual(segments[1][0], "free")
def test_segments_prop_parses(self):
bar = core.create("XStackBar", "XStackBar_001")
bar.set_prop("segments", "used=45|cached=25|free=30")
segments = bar.get_segments()
self.assertEqual([s[0] for s in segments],
["used", "cached", "free"])
self.assertEqual([s[1] for s in segments], [45.0, 25.0, 30.0])
def test_demo_segments_when_empty(self):
bar = core.create("XStackBar", "XStackBar_001")
self.assertEqual([s[0] for s in bar.get_segments()],
["used", "cached", "buffers", "free"])
class ProcessListTests(unittest.TestCase):
def test_demo_rows_present(self):
procs = core.create("XProcessList", "XProcessList_001")
rows = procs.get_rows()
self.assertGreater(len(rows), 0)
self.assertIn("pid", rows[0])
self.assertIn("cpu", rows[0])
def test_sort_by_cpu_desc_default(self):
procs = core.create("XProcessList", "XProcessList_001")
procs.set_rows([
{"pid": 1, "name": "a", "user": "root", "mem_kb": 10,
"cpu": 5.0},
{"pid": 2, "name": "b", "user": "root", "mem_kb": 20,
"cpu": 50.0},
{"pid": 3, "name": "c", "user": "root", "mem_kb": 30,
"cpu": 1.0},
])
self.assertEqual([r["pid"] for r in procs._sorted_rows()],
[2, 1, 3])
procs.sort_by("mem")
self.assertEqual([r["pid"] for r in procs._sorted_rows()],
[3, 2, 1])
def test_refresh_reads_proc_when_available(self):
procs = core.create("XProcessList", "XProcessList_001")
count = procs.refresh_processes()
if count is None:
self.skipTest("/proc unavailable here")
self.assertGreater(count, 0)
rows = procs.get_rows()
self.assertGreater(len(rows), 0)
# Second refresh computes real CPU% values (per-core: 100%
# = one core, so a multithreaded process can exceed 100).
import os
procs.refresh_processes()
self.assertTrue(all(0.0 <= r["cpu"] <= 100.0 * (os.cpu_count() or 1)
for r in procs.get_rows()))
class CoreGridTests(unittest.TestCase):
def test_core_count_positive(self):
grid = core.create("XCoreGrid", "XCoreGrid_001")
self.assertGreater(grid.core_count(), 0)
grid.set_prop("cores", 4)
self.assertEqual(grid.core_count(), 4)
def test_refresh_cores_two_samples(self):
grid = core.create("XCoreGrid", "XCoreGrid_001")
first = grid.refresh_cores()
if first is None and grid._prev_cpu is None:
self.skipTest("/proc/stat unavailable here")
self.assertIsNone(first) # first sample has no delta yet
values = grid.refresh_cores()
self.assertIsNotNone(values)
self.assertEqual(len(values), grid.core_count())
self.assertTrue(all(0.0 <= v <= 100.0 for v in values))
class LoadBadgeTests(unittest.TestCase):
def test_load_values_always_4_tuple(self):
badge = core.create("XLoadBadge", "XLoadBadge_001")
values = badge._load_values()
self.assertEqual(len(values), 4)
self.assertTrue(all(v >= 0 for v in values[:3]))
def test_refresh_load(self):
badge = core.create("XLoadBadge", "XLoadBadge_001")
values = badge.refresh_load()
if values is None:
self.skipTest("getloadavg unavailable here")
self.assertEqual(len(values), 4)
class MonitorButtonTests(unittest.TestCase):
def test_process_check_finds_python3(self):
button = core.create("XMonitorButton", "XMonitorButton_001")
button.set_prop("check-type", "Process")
button.set_prop("target", "python3")
button.set_prop("label", "Python")
# The test runner itself is python3, so this must be up.
self.assertEqual(button.poll(), "up")
self.assertTrue(button.detail.startswith("pid "))
def test_closed_port_is_down(self):
button = core.create("XMonitorButton", "XMonitorButton_001")
button.set_prop("check-type", "Port")
button.set_prop("target", str(_closed_port()))
self.assertEqual(button.poll(), "down")
self.assertEqual(button.detail, "closed")
def test_bad_port_is_unknown(self):
button = core.create("XMonitorButton", "XMonitorButton_001")
button.set_prop("check-type", "Port")
button.set_prop("target", "not-a-port")
self.assertEqual(button.poll(), "unknown")
def test_update_alias(self):
button = core.create("XMonitorButton", "XMonitorButton_001")
button.set_prop("check-type", "Process")
button.set_prop("target", "python3")
self.assertEqual(button.update(), "up")
self.assertEqual(button.status, "up")
def test_check_monitor_helpers(self):
self.assertEqual(monitor_mod.check_monitor(0, "python3")[0],
"up")
status, _detail = monitor_mod.check_monitor(
2, str(_closed_port()))
self.assertEqual(status, "down")
self.assertEqual(monitor_mod.check_monitor(2, "xx")[0],
"unknown")
class MonitorGridTests(unittest.TestCase):
def test_add_and_poll(self):
grid = core.create("XMonitorGrid", "XMonitorGrid_001")
grid.add_monitor("process", "python3", "Python")
grid.add_monitor("port", str(_closed_port()), "Closed port")
self.assertEqual(len(grid.get_monitors()), 2)
statuses = grid.poll_all()
self.assertEqual(statuses, ["up", "down"])
monitors = grid.get_monitors()
self.assertEqual(monitors[0]["status"], "up")
self.assertTrue(monitors[0]["detail"].startswith("pid "))
def test_set_monitors(self):
grid = core.create("XMonitorGrid", "XMonitorGrid_001")
grid.set_monitors([(0, "python3", "Python"),
(2, "22", "SSH")])
self.assertEqual([m["label"] for m in grid.get_monitors()],
["Python", "SSH"])
def test_cell_at(self):
grid = core.create("XMonitorGrid", "XMonitorGrid_001")
grid.add_monitor("process", "python3", "Python")
grid.add_monitor("process", "python3", "Python 2")
cells = grid._cell_layout()
self.assertEqual(len(cells), 2)
x, y, w, h = cells[0]
self.assertEqual(grid.cell_at(x + 2, y + 2), 0)
self.assertIsNone(grid.cell_at(1, 1)) # title area
self.assertIsNone(grid.cell_at(grid.width - 1,
grid.height - 1))
class PropsTests(unittest.TestCase):
def test_monitor_kinds_have_generic_set(self):
# Same check as test_props.py's generic-set test, applied
# to the 15 new kinds.
for kind in MONITOR_KINDS:
self.assertEqual(props.GENERIC_NAMES,
props.GENERIC_NAMES
& props.prop_names(kind), kind)
def test_custom_props_present(self):
self.assertIn("series-count",
props.prop_names("XHistoryGraph"))
self.assertIn("threshold", props.prop_names("XTempHistory"))
self.assertIn("redline", props.prop_names("XTachometer"))
self.assertIn("check-type",
props.prop_names("XMonitorButton"))
self.assertIn("target", props.prop_names("XMonitorButton"))
self.assertIn("sort-by", props.prop_names("XProcessList"))
self.assertIn("segments", props.prop_names("XStackBar"))
self.assertIn("cores", props.prop_names("XCoreGrid"))
self.assertIn("value", props.prop_names("XUsageBar"))
self.assertIn("unit", props.prop_names("XSysBox"))
def test_set_prop_validation(self):
bar = core.create("XUsageBar", "XUsageBar_001")
bar.set_prop("value", 65)
self.assertEqual(bar.get_value(), 65.0)
with self.assertRaises(ValueError):
bar.set_prop("no-such-prop", "x")
button = core.create("XMonitorButton", "XMonitorButton_001")
button.set_prop("check-type", "Port")
self.assertEqual(button.get_prop("check-type"), "2")
with self.assertRaises(ValueError):
button.set_prop("check-type", "Nope")
if __name__ == "__main__":
unittest.main()