aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_vm.py
blob: b84ec97b1391a055ccc06c7481d135eb30bc0b26 (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
# 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
  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

    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 = "clean\nworking\n\n" if cmd[2] == "alpha" else ""
        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"}
    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["ip"], "192.0.2.5")
        self.assertEqual(a["snapshots"], ["clean", "working"])
        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_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()