Files
kernel-automation/tests/test_backup.py
T
patrickandClaude Sonnet 5.5 4365ed56e1 Add kernelwatch backup command
Uses SQLite's online backup API, so it is consistent while the server is
writing in WAL mode. Writes mode 0600 via a temp file and rename, and
refuses to overwrite the live database.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 20:37:54 -04:00

70 lines
2.8 KiB
Python

"""kernelwatch backup: consistent copy, permissions, and refusal to clobber the live DB."""
import contextlib
import io
import os
import sqlite3
import stat
import unittest
from helpers import temp_config, tempdir
from kernelwatch import auth, cli, db
class BackupTest(unittest.TestCase):
def setUp(self):
self.tmp = tempdir()
self.addCleanup(self.tmp.cleanup)
self.cfg = temp_config(self.tmp.name)
self.config_path = os.path.join(self.tmp.name, "server.toml")
with open(self.config_path, "w") as f:
f.write(f'db_path = "{self.cfg.db_path}"\n')
db.init(self.cfg.db_path)
self.conn = db.connect(self.cfg.db_path)
self.addCleanup(self.conn.close)
db.add_host(self.conn, "web01", auth.token_hash("tok"))
db.add_report(self.conn, "web01", {"kernel_running": "6.1.0-1"}, 30)
self.dest = os.path.join(self.tmp.name, "backup.db")
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, *args])
return code, err.getvalue()
def test_backup_contains_data_and_is_private(self):
# The reader holds an open WAL connection, so the data may only be in the -wal file.
self.assertEqual(self.run_cli("backup", self.dest)[0], 0)
self.assertEqual(stat.S_IMODE(os.stat(self.dest).st_mode), 0o600)
copy = db.connect(self.dest)
self.addCleanup(copy.close)
self.assertEqual([h["name"] for h in db.list_hosts(copy)], ["web01"])
self.assertEqual(db.host_for_token(copy, auth.token_hash("tok")), "web01")
self.assertEqual(copy.execute("PRAGMA integrity_check").fetchone()[0], "ok")
self.assertFalse([n for n in os.listdir(self.tmp.name) if ".tmp-" in n])
def test_replaces_an_existing_backup(self):
with open(self.dest, "w") as f:
f.write("old")
self.assertEqual(self.run_cli("backup", self.dest)[0], 0)
copy = sqlite3.connect(self.dest)
self.addCleanup(copy.close)
self.assertEqual(copy.execute("SELECT count(*) FROM hosts").fetchone()[0], 1)
def test_refuses_the_live_database(self):
code, err = self.run_cli("backup", self.cfg.db_path)
self.assertEqual(code, 1)
self.assertIn("live database", err)
self.assertEqual([h["name"] for h in db.list_hosts(self.conn)], ["web01"])
def test_failure_leaves_no_partial_file(self):
missing = os.path.join(self.tmp.name, "nope", "backup.db")
code, err = self.run_cli("backup", missing)
self.assertEqual(code, 1)
self.assertIn("backup failed", err)
self.assertFalse([n for n in os.listdir(self.tmp.name) if ".tmp-" in n])
if __name__ == "__main__":
unittest.main()