aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_vm.py
blob: 10791dc3fd849da123156e1a71a06ca5c24f832e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# deck-it - tests for the libvirt VM module
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import sys
import tempfile
from pathlib import Path
from types import SimpleNamespace

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import unittest

import deckit.modules.vm as vm
from deckit.module import ModuleError

DOMSTATS = """Domain: 'alpha'
  state.state=1
  state.reason=1
  cpu.time={ns}
  balloon.current=4194304
  balloon.available=4000000
  balloon.usable=3000000
  vcpu.current=2

Domain: 'beta'
  state.state=5
  state.reason=1
  cpu.time=0
  balloon.current=2097152
  vcpu.current=1
"""


class Fake:
    """virsh/kitty/hyprctl stand-in: records commands, answers by verb."""

    def __init__(self):
        self.cmds = []
        self.ns = 1_000_000_000
        self.fail = None
        self.kitty_ok = True
        self.listening = set()

    def __call__(self, cmd, timeout=10):
        self.cmds.append(cmd)
        out, code, err = "", 0, ""
        if cmd[:2] == ["virsh", "domstats"]:
            out = DOMSTATS.format(ns=self.ns)
        elif cmd[:2] == ["virsh", "dominfo"]:
            out = "Managed save:   yes\n" if cmd[2] == "beta" else "Managed save:   no\n"
        elif cmd[:2] == ["virsh", "snapshot-list"]:
            out = (" Name    Creation Time               State\n----\n"
                   " clean   2026-03-06 10:27:47 +0100   shutoff\n"
                   " working 2026-04-04 16:00:51 +0200   running\n\n") if cmd[2] == "alpha" else ""
        elif cmd[:2] == ["virsh", "snapshot-current"]:
            out, code = ("working\n", 0) if cmd[-1] == "alpha" else ("", 1)
        elif cmd[:2] == ["ssh", "-G"]:
            out = "user root\nhostname 192.0.2.9\nport 2290\n" if cmd[2] == "alpha" else f"hostname {cmd[2]}\nport 22\n"
        elif cmd[:2] == ["virsh", "screenshot"]:
            Path(cmd[cmd.index("--file") + 1]).write_bytes(b"P6 1 1 255 ...")
        elif cmd[0] == "ffmpeg":
            Path(cmd[-1]).write_bytes(b"JPEG")
        elif cmd[:2] == ["virsh", "domifaddr"]:
            out = (" Name   MAC address   Protocol   Address\n---\n"
                   " lo     00:00:00:00:00:00   ipv4   127.0.0.1/8\n"
                   " eth0   52:54:00:aa:bb:cc   ipv4   192.0.2.5/24\n")
        elif cmd[:2] == ["kitty", "@"]:
            code = 0 if self.kitty_ok else 1
        if self.fail and self.fail in cmd:
            code, err = 1, "error: boom"
        return SimpleNamespace(returncode=code, stdout=out, stderr=err)


def make(fake, now, **extra):
    cfg = {"run": fake, "clock": lambda: now[0], "spawn": lambda f: f(), "hyprland": "classic",
           "probe": lambda host, port: (host, port) in fake.listening}
    cfg.update(extra)
    return vm.make(cfg)


class VmTest(unittest.TestCase):
    def setUp(self):
        self.fake = Fake()
        self.now = [100.0]
        self.spawned = []
        self.mod = make(self.fake, self.now, popen=self.spawned.append)

    def test_state_and_cpu_delta(self):
        st = self.mod.state()
        a, b = st["vms"]
        self.assertEqual((a["name"], a["state"], a["vcpus"]), ("alpha", "running", 2))
        self.assertIsNone(a["cpu"])                      # one sample: no rate yet
        self.assertEqual(a["mem"], 4194304 * 1024)
        self.assertEqual(a["used"], 1000000 * 1024)
        self.assertIsNone(b["used"])
        self.assertEqual(a["ip"], "192.0.2.5")
        self.assertEqual([s["name"] for s in a["snapshots"]], ["clean", "working"])
        self.assertEqual(a["snapshots"][0]["created"], 1772789267)
        self.assertEqual([s["current"] for s in a["snapshots"]], [False, True])
        self.assertEqual((b["state"], b["saved"], b["ip"]), ("shut off", True, ""))
        self.fake.ns += 1_000_000_000                    # 1 s of CPU over 2 s, 2 vCPUs
        self.now[0] += 2
        self.assertAlmostEqual(self.mod.state()["vms"][0]["cpu"], 25.0)

    def test_ssh_ready_from_ssh_alias(self):
        st = self.mod.state()
        self.assertEqual((st["vms"][0]["ready"], st["vms"][1]["ready"]), (False, None))
        self.fake.listening.add(("192.0.2.9", 2290))     # alias host and port, not the agent IP
        self.now[0] += 2                                  # booting: re-probed within seconds
        self.mod.state()
        self.assertTrue(self.mod.state()["vms"][0]["ready"])

    def test_screenshot_only_for_running_vm(self):
        self.mod.state()
        self.assertEqual(self.mod.image("alpha"), (b"JPEG", "image/jpeg"))
        self.assertIsNone(self.mod.image("beta"))         # shut off
        self.assertIsNone(self.mod.image("../etc"))

    def test_offline(self):
        self.fake.fail = "domstats"
        st = self.mod.state()
        self.assertTrue(st["offline"])
        self.assertIn("boom", st["reason"])

    def test_actions_validated(self):
        self.mod.state()
        act = self.mod.actions
        with self.assertRaises(ModuleError):
            act["start"]({"vm": "gamma"})
        with self.assertRaises(ModuleError):
            act["revert"]({"vm": "alpha", "snap": "nope"})
        act["start"]({"vm": "beta"})
        self.assertIn(["virsh", "start", "beta"], self.fake.cmds)
        act["revert"]({"vm": "alpha", "snap": "clean"})
        self.assertIn(["virsh", "snapshot-revert", "alpha", "clean"], self.fake.cmds)
        act["snapshot"]({"vm": "alpha"})
        create = next(c for c in self.fake.cmds if "snapshot-create-as" in c)
        self.assertRegex(create[-1], r"^alpha_\d{8}_\d{6}$")
        self.fake.fail = "destroy"
        with self.assertRaisesRegex(ModuleError, "boom"):
            act["destroy"]({"vm": "alpha"})

    def test_ssh_attaches_to_kitty_or_spawns(self):
        self.mod.state()
        with tempfile.TemporaryDirectory() as d:
            (Path(d) / "kitty-4242").touch()
            mod = make(self.fake, self.now, popen=self.spawned.append, runtime=d)
            mod.state()
            mod.actions["ssh"]({"vm": "alpha"})
            self.assertIn(["kitty", "@", "--to", f"unix:{d}/kitty-4242", "launch", "--type=tab", "ssh", "alpha"],
                          self.fake.cmds)
            self.assertIn(["hyprctl", "dispatch", "focuswindow", "pid:4242"], self.fake.cmds)
            self.fake.kitty_ok = False
            mod.actions["ssh"]({"vm": "alpha"})
            self.assertEqual(self.spawned, [["kitty", "ssh", "alpha"]])


if __name__ == "__main__":
    unittest.main()