Files
kernel-automation/tests/test_cli_status.py
T
patrickandClaude Opus 5.5 6d29197cfc
CI / tests (Python 3.10) (pull_request) Successful in 26s
CI / tests (Python 3.11) (pull_request) Successful in 25s
CI / tests (Python 3.12) (pull_request) Successful in 25s
CI / tests (Python 3.13) (pull_request) Successful in 25s
CI / lint (pull_request) Failing after 3s
Report a failed apt simulation instead of reading it as "no updates"
The agent ran `apt-get -s dist-upgrade 2>/dev/null || true`, so when apt
failed (unmet dependencies, a broken sources entry, a damaged package cache)
the empty output counted as zero updates and the host could show ok while
nothing could be installed. The agent now keeps apt's exit status and stderr,
reports apt_simulation_ok and the first "E:" line as apt_simulation_error,
and sends the update counts as null. The server puts such a host in update
with "apt can't work out pending updates: ...", and the host page shows the
result. Agents before 0.5.0 don't send the field and are judged as before.

Also show "–" rather than "None" for an unknown count in a host's history,
and stop hard-coding the agent version in the status CLI tests. Agent 0.5.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 23:22:24 -04:00

159 lines
7.8 KiB
Python

"""kernelwatch status [--json]: the fleet as the dashboard sees it, for scripts."""
import calendar
import contextlib
import io
import json
import os
import unittest
from unittest import mock
from helpers import tempdir
from kernelwatch import AGENT_VERSION, auth, cli, db
from kernelwatch.status import evaluate
NOW = calendar.timegm((2026, 11, 20, 12, 0, 0))
GOOD = {"kernel_running": "6.12.57", "kernel_newest_installed": "6.12.57", "needrestart_ksta": 1,
"apt_lists_age_seconds": 60, "upgradable_count": 0, "security_count": 0,
"os_pretty_name": "Debian 13", "agent_version": AGENT_VERSION}
class StatusCommandTest(unittest.TestCase):
def setUp(self):
self.tmp = tempdir()
self.addCleanup(self.tmp.cleanup)
self.config_path = os.path.join(self.tmp.name, "server.toml")
self.db_path = os.path.join(self.tmp.name, "kw.db")
with open(self.config_path, "w") as f:
f.write(f'db_path = "{self.db_path}"\n')
db.init(self.db_path)
self.conn = db.connect(self.db_path)
self.addCleanup(self.conn.close)
self.add("app01", GOOD)
self.add("db01", dict(GOOD, security_count=3, upgradable_count=7))
self.add("web01", dict(GOOD, kernel_running="6.8.0-136", kernel_newest_installed="6.8.0-138",
needrestart_ksta=None))
self.add("old01", GOOD, age=10 * 3600)
db.add_host(self.conn, "new01", auth.token_hash("tok-new01"))
clock = mock.patch("kernelwatch.cli.time.time", return_value=NOW)
clock.start()
self.addCleanup(clock.stop)
def add(self, name, payload, age=60):
db.add_host(self.conn, name, auth.token_hash("tok-" + name))
db.add_report(self.conn, name, payload, 30)
self.conn.execute("UPDATE reports SET received_at = ? WHERE host = ?", (NOW - age, name))
def run_cli(self, *args):
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = cli.main(["-c", self.config_path, "status", *args])
return code, out.getvalue(), err.getvalue()
def fleet(self, *args):
code, out, err = self.run_cli("--json", *args)
self.assertEqual((code, err), (0, ""))
return json.loads(out)
def names(self, fleet):
return [h["name"] for h in fleet["hosts"]]
def test_worst_first_then_by_name_like_the_dashboard(self):
fleet = self.fleet()
self.assertEqual(self.names(fleet), ["new01", "old01", "web01", "db01", "app01"])
self.assertEqual([h["status"] for h in fleet["hosts"]], ["stale", "stale", "reboot", "update", "ok"])
self.assertEqual(fleet["counts"], {"stale": 2, "reboot": 1, "update": 1, "ok": 1})
self.assertEqual(fleet["generated_at"], "2026-11-20T12:00:00Z")
def test_status_and_reasons_are_exactly_what_evaluate_says(self):
from kernelwatch.config import Config
for row, entry in zip(sorted(db.latest_reports(self.conn), key=lambda r: r["host"]),
sorted(self.fleet()["hosts"], key=lambda h: h["name"])):
expected = evaluate(row["received_at"], row["report"], NOW, Config(db_path=self.db_path), row["host"])
self.assertEqual((entry["status"], entry["reasons"]), (expected.level, expected.reasons), row["host"])
def test_host_fields(self):
web = next(h for h in self.fleet()["hosts"] if h["name"] == "web01")
self.assertEqual(web["last_report_at"], "2026-11-20T11:59:00Z")
self.assertEqual(web["last_report_age_seconds"], 60)
self.assertEqual((web["kernel_running"], web["kernel_newest_installed"]), ("6.8.0-136", "6.8.0-138"))
self.assertEqual((web["os"], web["agent_version"]), ("Debian 13", AGENT_VERSION))
db_host = next(h for h in self.fleet()["hosts"] if h["name"] == "db01")
self.assertEqual((db_host["updates_pending"], db_host["security_updates"]), (7, 3))
self.assertEqual(db_host["reasons"], ["3 security updates pending"])
self.assertIsNone(db_host["livepatch"])
def test_a_host_that_never_reported_has_nulls_not_missing_keys(self):
new = next(h for h in self.fleet()["hosts"] if h["name"] == "new01")
self.assertEqual(new["reasons"], ["never reported"])
keys = set(next(h for h in self.fleet()["hosts"] if h["name"] == "app01"))
self.assertEqual(set(new), keys)
self.assertIsNone(new["last_report_at"])
self.assertIsNone(new["last_report_age_seconds"])
self.assertIsNone(new["kernel_running"])
def test_livepatch_is_included_when_reported(self):
self.add("lp01", dict(GOOD, livepatch_state="applied", livepatch_supported="supported",
livepatch_upgrade_required="2027-10-14", livepatch_fix_count=2))
lp = next(h for h in self.fleet()["hosts"] if h["name"] == "lp01")
self.assertEqual(lp["livepatch"], {"state": "applied", "supported": "supported",
"upgrade_required": "2027-10-14", "fixes": 2})
def test_hostname_mismatch_note_matches_the_dashboard(self):
self.add("iris", dict(GOOD, reported_hostname="web.beane.me"))
iris = next(h for h in self.fleet()["hosts"] if h["name"] == "iris")
self.assertTrue(any("registered as iris but reports itself as web.beane.me" in r
for r in iris["reasons"]))
def test_nothing_secret_is_printed(self):
_, out, _ = self.run_cli("--json")
text = self.run_cli()[1]
for secret in ("tok-", auth.token_hash("tok-web01"), "token_hash", "pw_hash"):
self.assertNotIn(secret, out + text)
def test_level_filter_trims_hosts_but_not_counts(self):
fleet = self.fleet("--level", "reboot")
self.assertEqual(self.names(fleet), ["web01"])
self.assertEqual(fleet["counts"], {"stale": 2, "reboot": 1, "update": 1, "ok": 1})
self.assertEqual(self.names(self.fleet("--level", "reboot", "--level", "update")), ["web01", "db01"])
self.assertEqual(self.names(self.fleet("--level", "ok")), ["app01"])
def test_host_filter(self):
self.assertEqual(self.names(self.fleet("--host", "db01")), ["db01"])
code, out, err = self.run_cli("--json", "--host", "nope")
self.assertEqual((code, out), (1, ""))
self.assertIn("no such host 'nope'", err)
def test_filters_combine(self):
self.assertEqual(self.names(self.fleet("--host", "db01", "--level", "reboot")), [])
def test_bad_arguments_are_rejected_by_argparse(self):
for args in (("--level", "broken"), ("--host", "bad host!"), ("--bogus",)):
with self.subTest(args=args), contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as raised:
self.run_cli(*args)
self.assertEqual(raised.exception.code, 2)
def test_empty_fleet(self):
for table in ("reports", "hosts"):
self.conn.execute(f"DELETE FROM {table}")
fleet = self.fleet()
self.assertEqual((fleet["hosts"], sum(fleet["counts"].values())), ([], 0))
self.assertEqual(self.run_cli()[1], "0 hosts: 0 stale, 0 reboot, 0 update, 0 ok\n")
def test_text_output(self):
code, out, err = self.run_cli()
self.assertEqual((code, err), (0, ""))
lines = out.splitlines()
self.assertEqual(lines[-1], "5 hosts: 2 stale, 1 reboot, 1 update, 1 ok")
self.assertIn("reboot web01 6.8.0-136 -> 6.8.0-138 (last seen 1m ago)", lines)
self.assertIn(" - 3 security updates pending", lines)
self.assertIn("stale new01 ? (last seen never)", lines)
self.assertIn("ok app01 6.12.57 (last seen 1m ago)", lines)
self.assertEqual(self.run_cli("--host", "db01", "--level", "update")[1].count("\n"), 3)
if __name__ == "__main__":
unittest.main()