"""Registry persistence and liveness logic.""" from mcqemu.config import Config from mcqemu.models import VMRecord from mcqemu.registry import VMRegistry, pid_alive def make_config(dirs) -> Config: return Config(state_dir=dirs.state, runtime_dir=dirs.run) def record(name="vm1", **kw) -> VMRecord: defaults = dict(source="spawned", qmp_socket=f"/run/{name}/qmp.sock", pid=12345) defaults.update(kw) return VMRecord(name=name, **defaults) def test_round_trip(dirs): reg = VMRegistry(make_config(dirs)) reg.load() reg.add(record("alpha", arch="x86_64", config={"disks": ["/vms/a.qcow2"]})) reg.add(record("beta", source="attached", pid=None)) reg2 = VMRegistry(make_config(dirs)) reg2.load() assert sorted(reg2.names()) == ["alpha", "beta"] alpha = reg2.get("alpha") assert alpha.arch == "x86_64" assert alpha.config["disks"] == ["/vms/a.qcow2"] assert reg2.get("beta").source == "attached" def test_load_missing_file_is_empty(dirs): reg = VMRegistry(make_config(dirs)) reg.load() assert reg.all() == [] def test_from_dict_ignores_unknown_fields(): rec = VMRecord.from_dict( {"name": "x", "source": "spawned", "qmp_socket": "/s", "future_field": 1} ) assert rec.name == "x" def test_pid_alive_rejects_non_qemu_process(): import os # Our own PID exists but comm is python/pytest, not qemu-system — must be False. assert pid_alive(os.getpid()) is False def test_pid_alive_rejects_dead_and_bogus_pids(): assert pid_alive(2**22 + 12345) is False assert pid_alive(None) is False assert pid_alive(0) is False def test_disks_in_use_only_counts_live_vms(dirs, monkeypatch): reg = VMRegistry(make_config(dirs)) reg.load() reg.add(record("live", pid=111, config={"disks": ["/vms/live.qcow2"]})) reg.add(record("dead", pid=222, config={"disks": ["/vms/dead.qcow2"]})) monkeypatch.setattr("mcqemu.registry.pid_alive", lambda pid: pid == 111) # refresh_pid would overwrite from pidfile; none set, so pids stay put. used = reg.disks_in_use() assert "/vms/live.qcow2" in used assert used["/vms/live.qcow2"] == "live" assert "/vms/dead.qcow2" not in used