Commit 250c1f85 by PLN (Algolia)

devname: put OS specifics behind one platform layer; launchd agent behind it

Tool discovery, state and log paths, and the agent live in a Platform
class (MacPlatform for launchd, a base for any other Unix that refuses
agent and points at devname serve). agent gains uninstall, restart,
and install --print to show the plist without writing or loading it.
parent 1c3ff048
...@@ -9,6 +9,7 @@ import tempfile ...@@ -9,6 +9,7 @@ import tempfile
import time import time
import unittest import unittest
from contextlib import redirect_stderr, redirect_stdout from contextlib import redirect_stderr, redirect_stdout
from unittest import mock
ROOT = pathlib.Path(__file__).resolve().parent.parent ROOT = pathlib.Path(__file__).resolve().parent.parent
...@@ -387,5 +388,125 @@ class DevnameTests(unittest.TestCase): ...@@ -387,5 +388,125 @@ class DevnameTests(unittest.TestCase):
self.assertIn("http://mac.local/CA", lan) self.assertIn("http://mac.local/CA", lan)
class FakeRun:
"""Stands in for subprocess.run: records every argv, answers from a {argv-prefix tuple: (rc, stdout)} table."""
def __init__(self, table=None, default=(0, "")):
self.table, self.default, self.calls = table or {}, default, []
def __call__(self, cmd, *args, **kw):
self.calls.append(list(cmd))
rc, out = self.default
best = -1
for prefix, answer in self.table.items():
if tuple(cmd[:len(prefix)]) == prefix and len(prefix) > best:
(rc, out), best = answer, len(prefix)
return mock.Mock(returncode=rc, stdout=out + ("\n" if out else ""), stderr="")
class PlatformTests(unittest.TestCase):
"""Every platform branch, driven by mocks: runs on any OS, no sudo, no caddy, no network."""
def setUp(self):
self._tmp = tempfile.TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
self.dn = load_module(os.path.join(self._tmp.name, "conf"))
self.home = os.path.join(self._tmp.name, "home")
os.makedirs(self.home)
patcher = mock.patch.object(self.dn, "HOME", self.home) # agent files land in the temp home, never the real one
patcher.start()
self.addCleanup(patcher.stop)
def use(self, plat, run=None):
self.run = run or FakeRun()
for target, value in ((self.dn, {"PLAT": plat}), (self.dn.subprocess, {"run": self.run})):
p = mock.patch.multiple(target, **value)
p.start()
self.addCleanup(p.stop)
return plat
def cli(self, *argv):
out, err = io.StringIO(), io.StringIO()
with redirect_stdout(out), redirect_stderr(err):
rc = self.dn.main(list(argv))
return rc, out.getvalue(), err.getvalue()
# detection
def test_detect_platform_by_sys_platform(self):
self.assertIsInstance(self.dn.detect_platform("darwin"), self.dn.MacPlatform)
other = self.dn.detect_platform("freebsd13", os_release={})
self.assertEqual(type(other), self.dn.Platform)
self.assertIsNone(other.supervisor)
def test_os_release_parsing(self):
p = pathlib.Path(self._tmp.name) / "os-release"
p.write_text('NAME="Ubuntu"\nID=ubuntu\nID_LIKE=debian\n# comment\nVERSION_ID="24.04"\n')
rel = self.dn.read_os_release(str(p))
self.assertEqual((rel["ID"], rel["ID_LIKE"], rel["VERSION_ID"]), ("ubuntu", "debian", "24.04"))
self.assertEqual(self.dn.read_os_release(str(p) + ".absent"), {})
def test_find_tool_env_override_then_path_then_dirs(self):
plat = self.dn.Platform({})
with mock.patch.dict(os.environ, {"DEVNAME_CADDY": "/opt/x/caddy"}):
self.assertEqual(plat.find_tool("caddy"), "/opt/x/caddy")
tool_dir = pathlib.Path(self._tmp.name) / "bin"
tool_dir.mkdir()
exe = tool_dir / "caddy"
exe.write_text("#!/bin/sh\n")
exe.chmod(0o755)
plat.tool_dirs = (str(tool_dir),)
with mock.patch.dict(os.environ, {"DEVNAME_CADDY": ""}), mock.patch.object(self.dn.shutil, "which", return_value=None):
self.assertEqual(plat.find_tool("caddy"), str(exe))
self.assertIsNone(plat.find_tool("absent-tool"))
def test_missing_caddy_is_a_clear_error_not_a_crash(self):
self.use(self.dn.Platform({}))
with mock.patch.object(self.dn, "CADDY", None):
rc, _, err = self.cli("serve")
self.assertEqual(rc, 2)
self.assertIn("caddy not found", err)
# macOS: launchd (mocked: launchctl never runs here)
def test_mac_agent_print_writes_nothing(self):
plat = self.use(self.dn.MacPlatform())
rc, out, err = self.cli("agent", "install", "--print")
self.assertEqual(rc, 0)
self.assertIn("<key>Label</key><string>pl.nech.devname</string>", out)
self.assertIn("<string>serve</string>", out)
self.assertIn("Library/Logs/devname/caddy.log", out)
self.assertIn("would write", err)
self.assertFalse(os.path.exists(plat.agent_path()))
self.assertEqual(self.run.calls, [])
def test_mac_agent_install_status_restart_uninstall(self):
plat = self.use(self.dn.MacPlatform())
self.assertEqual(self.cli("agent", "install")[0], 0)
self.assertTrue(os.path.exists(plat.agent_path()))
verbs = [c[1] for c in self.run.calls]
self.assertEqual(verbs, ["bootout", "bootstrap"])
self.assertEqual(self.cli("agent", "status")[1].strip(), "loaded")
self.assertEqual(self.cli("agent", "restart")[0], 0)
self.assertEqual(self.run.calls[-1][:3], ["launchctl", "kickstart", "-k"])
self.assertEqual(self.cli("agent", "uninstall")[0], 0)
self.assertFalse(os.path.exists(plat.agent_path()))
def test_mac_bootstrap_failure_is_reported(self):
self.use(self.dn.MacPlatform(), FakeRun({("launchctl", "bootstrap"): (5, "")}))
rc, _, err = self.cli("agent", "install")
self.assertEqual(rc, 2)
self.assertIn("launchctl bootstrap failed", err)
self.assertEqual(sum(1 for c in self.run.calls if c[1] == "bootstrap"), 2) # the known transient: one retry
# any other Unix: no supervisor, a clear refusal
def test_other_platform_refuses_agent_and_points_at_serve(self):
self.use(self.dn.Platform({}))
for verb in ("install", "status", "restart", "uninstall"):
rc, _, err = self.cli("agent", verb)
self.assertEqual(rc, 2, verb)
self.assertIn("devname serve", err)
self.assertEqual(self.cli("agent", "install", "--print")[0], 2)
self.assertEqual(self.cli("agent", "status", "--print")[0], 2) # --print only goes with install
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment