1#!/usr/bin/env python3
2import json
3import os
4from pathlib import Path
5import subprocess
6import tempfile
7from types import SimpleNamespace
8import unittest
9from unittest.mock import patch
10
11import release
12
13
14class HostConfiguration(unittest.TestCase):
15 def select(self, hostname, configurations):
16 with patch.object(release.os, "uname", return_value=SimpleNamespace(nodename=hostname)), patch.object(
17 release.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, json.dumps(configurations)),
18 ) as command:
19 result = release.host_configuration(Path("/release"))
20 command.assert_called_once_with(
21 ["nix", "--extra-experimental-features", "nix-command flakes", "eval", "--json", "path:/release#nixosConfigurations", "--apply", "builtins.attrNames"],
22 check=True, capture_output=True, text=True,
23 )
24 return result
25
26 def test_canonical_hostname(self):
27 for hostname in ("snowglobe", "snowglobe.paperclover.net"):
28 with self.subTest(hostname=hostname):
29 self.assertEqual(self.select(hostname, ["installer", "snowglobe", "vm"]), "snowglobe")
30
31 def test_rehearsal_stays_on_vm(self):
32 self.assertEqual(self.select("snowglobe-rehearsal", ["installer", "snowglobe", "vm"]), "vm")
33
34 def test_unrelated_host_is_not_retargeted(self):
35 self.assertEqual(self.select("fixture", ["fixture", "vm"]), "fixture")
36 for hostname in ("fixture", "snowglobe", "snowglobe-rehearsal"):
37 with self.subTest(hostname=hostname), self.assertRaisesRegex(ValueError, "no NixOS configuration"):
38 self.select(hostname, ["installer"])
39
40
41class ActivationEnvironment(unittest.TestCase):
42 def test_host_switch_refreshes_inherited_name_and_preserves_overrides(self):
43 for before, after, inherited, expected in (
44 ("fixture", "snowglobe", "fixture", "snowglobe"),
45 ("fixture", "snowglobe", None, "snowglobe"),
46 ("fixture", "snowglobe", "test-override", "test-override"),
47 ("snowglobe-rehearsal", "snowglobe-rehearsal", "snowglobe-rehearsal", "snowglobe-rehearsal"),
48 ):
49 with self.subTest(before=before, inherited=inherited), tempfile.TemporaryDirectory() as temporary:
50 root = Path(temporary)
51 source = root / "release"
52 source.mkdir()
53 (source / "tools").mkdir()
54 (source / "tools/snowglobe.py").touch()
55 (source / ".snowglobe-release.json").write_text('{"version":1}')
56 hostname = before
57 observed = []
58 calls = []
59 read_text = Path.read_text
60
61 def run(argv, **kwargs):
62 nonlocal hostname
63 calls.append(argv)
64 if argv[:3] == ["hostnamectl", "set-hostname", "--transient"]:
65 hostname = after
66 if argv[-1] == "deploy":
67 observed.append(kwargs["env"].get("SNOWGLOBE_NODE_NAME"))
68 return subprocess.CompletedProcess(argv, 0, '"leader"')
69
70 with patch.dict(os.environ), patch.object(release, "ROOT", root), patch.object(
71 release, "STATE", root,
72 ), patch.object(release, "check_release", return_value=source), patch.object(
73 release, "current_release", return_value=None,
74 ), patch.object(release, "host_digest", return_value="new"), patch.object(
75 release, "host_configuration", return_value="fixture",
76 ), patch.object(release, "jobs", return_value=set()), patch.object(
77 release.os, "uname", side_effect=lambda: SimpleNamespace(nodename=hostname),
78 ), patch.object(release.subprocess, "run", side_effect=run):
79 if inherited is None:
80 os.environ.pop("SNOWGLOBE_NODE_NAME", None)
81 else:
82 os.environ["SNOWGLOBE_NODE_NAME"] = inherited
83 with patch.object(
84 Path, "read_text", autospec=True,
85 side_effect=lambda path: after + "\n" if path == Path("/etc/hostname") else read_text(path),
86 ):
87 release.activate("0123456789abcdef", initial=True)
88 self.assertEqual(observed, [expected])
89 self.assertEqual(hostname, after)
90 changes = [argv for argv in calls if argv[0] == "hostnamectl"]
91 self.assertEqual(changes, [["hostnamectl", "set-hostname", "--transient", after]] if before != after else [])
92 if changes:
93 switch = next(i for i, argv in enumerate(calls) if argv[:2] == ["nixos-rebuild", "switch"])
94 rename = calls.index(changes[0])
95 deploy = next(i for i, argv in enumerate(calls) if argv[-1] == "deploy")
96 self.assertLess(switch, rename)
97 self.assertLess(rename, deploy)
98
99
100class BootPreparation(unittest.TestCase):
101 def test_installs_a_boot_entry_and_preserves_the_default_without_activation(self):
102 entries = [
103 [{"id": "previous.conf", "isDefault": True}],
104 [{"id": "candidate.conf", "options": "init=/candidate/init loglevel=4"}],
105 ]
106 calls = []
107
108 def run(argv, **kwargs):
109 calls.append(argv)
110 return subprocess.CompletedProcess(argv, 0, json.dumps(entries.pop(0)) if argv[:2] == ["bootctl", "list"] else "")
111
112 with patch.object(release, "check_release", return_value=Path("/candidate")), patch.object(
113 release, "host_configuration", return_value="snowglobe",
114 ), patch.object(release.subprocess, "run", side_effect=run), patch.object(
115 Path, "resolve", return_value=Path("/candidate"),
116 ):
117 release.prepare_boot("0123456789abcdef")
118 self.assertEqual(calls, [
119 ["bootctl", "list", "--json=short"],
120 ["nixos-rebuild", "boot", "--flake", "path:/candidate#snowglobe"],
121 ["bootctl", "set-default", "previous.conf"],
122 ["bootctl", "list", "--json=short"],
123 ])
124
125 def test_failed_build_restores_the_default_without_selecting_a_candidate(self):
126 with patch.object(release, "check_release", return_value=Path("/candidate")), patch.object(
127 release, "host_configuration", return_value="snowglobe",
128 ), patch.object(release.subprocess, "run", side_effect=[
129 subprocess.CompletedProcess([], 0, '[{"id":"previous.conf","isDefault":true}]'),
130 subprocess.CalledProcessError(1, "nixos-rebuild"),
131 subprocess.CompletedProcess([], 0),
132 ]) as command:
133 with self.assertRaises(subprocess.CalledProcessError):
134 release.prepare_boot("0123456789abcdef")
135 self.assertEqual(command.call_args.args[0], ["bootctl", "set-default", "previous.conf"])
136 self.assertEqual(command.call_count, 3)
137
138
139if __name__ == "__main__":
140 unittest.main()