Merge pull request 'fix: twelve open bugs, set_vlan uplink first (#37, #30, #23, #22, #21, #20, #19, #18, #17, #15, #12, #3)' (#40) from fix/bugs-2026-11 into main
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 14s
driver / types (push) Successful in 1m27s
driver / test (3.12) (push) Successful in 1m43s
driver / lowest (push) Successful in 37s
driver / test (3.13) (push) Successful in 1m24s
driver / build (push) Successful in 28s
driver / security (push) Successful in 1m17s
CI / driver (push) Successful in 3m33s
driver / publish (push) Skipped

This commit was merged in pull request #40.
This commit is contained in:
christianmanivong committed 2026-11-01 22:50:18 +00:00
commit a8d73d95b4
19 files changed
+1067 -145

No files matched your search

+3 -5
View File
@@ -16,7 +16,6 @@
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan": 13,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 22,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_packages": 16,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_users": 15,
"napalm_proxmox/utils.py::addresses_from_node_network": 15,
"napalm_proxmox/vm_contract_mixin.py::parse_vm_config": 16,
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin._get_vm_disk_and_boot": 16,
@@ -35,13 +34,12 @@
"napalm_proxmox/sdn_mixin.py::ProxmoxSDNMixin.set_vlan": 70,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 74,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_packages": 66,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_users": 51,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 124,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 114,
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 179,
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin._download_cloud_image": 61,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin._download_cloud_image": 56,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 232,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.destroy_vm": 65,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.destroy_vm": 56,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 92
},
"mypy_relaxed": [
+34
View File
@@ -10,6 +10,7 @@ contract's ``install_package``. Every step reads its exit status.
from __future__ import annotations
import re
import subprocess
import pytest
@@ -36,6 +37,18 @@ class _Node:
return f"{out}\n__PVE_RC={rc}" if "__PVE_RC" in command else out
def _shell_driver(prelude: str) -> ProxmoxDriver:
"""A driver whose node shell is a real local ``sh``, *prelude* run first."""
def shell(command: str) -> str:
run = subprocess.run(["sh", "-c", prelude + command], capture_output=True, text=True)
return run.stdout
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = shell
return d
@pytest.fixture
def node():
return _Node()
@@ -87,6 +100,27 @@ class TestSnmpAgent:
assert result["success"] is False
assert not any("/etc/snmp/snmpd.conf" in c for c in node.ran)
def test_the_written_config_reports_success_through_a_real_shell(self, tmp_path):
"""The configure step's own exit status must reach ``_rc`` (#30).
``_Node`` answers ``__PVE_RC=0`` on its own; a real ``sh`` shows whether the
wrapped command still prints it. ``install`` is a function writing to tmp_path.
"""
target = tmp_path / "snmpd.conf"
d = _shell_driver(f'install() {{ cat "$7" > {target}; }}; ')
step = d._write_snmp_agent_config(SETTINGS)
assert step == {"ok": True, "output": "wrote /etc/snmp/snmpd.conf"}
assert "rocommunity c0mm 10.7.224.20/32" in target.read_text()
def test_a_refused_write_reports_failure_through_a_real_shell(self):
d = _shell_driver('install() { echo "install: read-only file system"; return 1; }; ')
step = d._write_snmp_agent_config(SETTINGS)
assert step == {"ok": False, "output": "install: read-only file system"}
def test_the_management_peer(self, driver):
assert driver.get_management_peer() == "10.7.224.20"
+65
View File
@@ -0,0 +1,65 @@
"""LLDP neighbours read from lldpd's ``lldpcli show neighbors``."""
from __future__ import annotations
from napalm_proxmox import ProxmoxDriver
# lldpd 1.0 output: one "Interface:" block per neighbour, so a port with two
# neighbours (a switch and a phone behind it) appears twice. The phone sends
# no SysName.
TWO_NEIGHBOURS_ON_ONE_PORT = """\
-------------------------------------------------------------------------------
LLDP neighbors:
-------------------------------------------------------------------------------
Interface: eno1, via: LLDP, RID: 1, Time: 0 day, 00:10:12
Chassis:
ChassisID: mac 00:11:22:33:44:55
SysName: sw1
Port:
PortID: ifname gi1/0/1
PortDescr: GigabitEthernet1/0/1
-------------------------------------------------------------------------------
Interface: eno1, via: LLDP, RID: 2, Time: 0 day, 00:01:02
Chassis:
ChassisID: mac aa:bb:cc:dd:ee:ff
Port:
PortID: mac aa:bb:cc:dd:ee:ff
-------------------------------------------------------------------------------
Interface: eno2, via: LLDP, RID: 3, Time: 0 day, 00:10:12
Chassis:
ChassisID: mac 00:11:22:33:44:66
SysName: sw2
Port:
PortID: ifname gi1/0/2
-------------------------------------------------------------------------------
"""
def _driver(output: str) -> ProxmoxDriver:
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = lambda command: output
return d
class TestGetLldpNeighbors:
def test_every_neighbour_on_a_port_is_its_own_entry(self):
result = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors()
assert result == {
"eno1": [
{"hostname": "sw1", "port": "gi1/0/1"},
{"hostname": "", "port": "aa:bb:cc:dd:ee:ff"},
],
"eno2": [{"hostname": "sw2", "port": "gi1/0/2"}],
}
def test_no_lldpd_output_is_no_neighbour(self):
assert _driver("").get_lldp_neighbors() == {}
class TestGetLldpNeighborsDetail:
def test_every_neighbour_on_a_port_is_its_own_entry(self):
result = _driver(TWO_NEIGHBOURS_ON_ONE_PORT).get_lldp_neighbors_detail()
assert [e["remote_system_name"] for e in result["eno1"]] == ["sw1", ""]
assert result["eno1"][1]["remote_chassis_id"] == "aa:bb:cc:dd:ee:ff"
+25
View File
@@ -175,6 +175,31 @@ class TestPing:
assert result["success"]["packet_loss"] == 0
assert result["success"]["rtt_min"] == pytest.approx(10.5, abs=0.01)
def test_every_reply_is_a_result(self, driver):
"""iputils puts "from <ip>" before icmp_seq (napalm-proxmox#12)."""
driver._node_api().execute.post.return_value = {"data": self.PING_SUCCESS}
result = driver.ping("8.8.8.8")
assert result["success"]["results"] == [
{"ip_address": "8.8.8.8", "rtt": 10.5},
{"ip_address": "8.8.8.8", "rtt": 11.2},
]
def test_a_reply_by_name_and_over_ipv6(self, driver):
output = (
"PING dns.google (8.8.4.4) 56(84) bytes of data.\n"
"64 bytes from dns.google (8.8.4.4): icmp_seq=1 ttl=118 time=123 ms\n"
"64 bytes from 2001:db8::1: icmp_seq=2 ttl=64 time=0.045 ms\n"
"--- dns.google ping statistics ---\n"
"2 packets transmitted, 2 received, 0% packet loss, time 1001ms\n"
"rtt min/avg/max/mdev = 0.045/61.5/123.0/61.4 ms\n"
)
driver._node_api().execute.post.return_value = {"data": output}
result = driver.ping("dns.google")
assert result["success"]["results"] == [
{"ip_address": "8.8.4.4", "rtt": 123.0},
{"ip_address": "2001:db8::1", "rtt": 0.045},
]
def test_failure(self, driver):
driver._node_api().execute.post.return_value = {"data": self.PING_FAIL}
result = driver.ping("badhost")
+86
View File
@@ -0,0 +1,86 @@
"""get_ntp_stats on chrony (Proxmox VE's default) and on ntpd (#18)."""
from __future__ import annotations
from unittest.mock import patch
import pytest
# chrony 4.x, ``chronyc -n -c sources`` then ``chronyc -n -c sourcestats``,
# behind the markers the driver's command prints.
CHRONY = """\
CHRONY_SOURCES
^,*,192.168.1.1,2,6,377,8,-0.000012345,-0.000013000,0.012345678
^,+,10.0.0.2,3,10,17,301,0.000250000,0.000251000,0.020000000
^,?,10.0.0.3,0,6,0,-,0.000000000,0.000000000,0.000000000
CHRONY_SOURCESTATS
192.168.1.1,10,6,320,-0.012,0.150,-0.000001234,0.000045678
10.0.0.2,6,4,1200,0.003,0.400,0.000200000,0.000500000
"""
# ntpd's ``ntpq -pn``: a candidate without tally mark keeps its leading space.
NTPQ = """\
remote refid st t when poll reach delay offset jitter
==============================================================================
*192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123
192.168.1.5 10.0.0.1 3 u 40 64 377 2.000 0.100 0.050
"""
def _stats(driver, output):
with patch.object(driver, "_exec_ssh_command", return_value=output):
return driver.get_ntp_stats()
class TestChrony:
def test_every_source_is_reported(self, driver):
assert [s["remote"] for s in _stats(driver, CHRONY)] == [
"192.168.1.1",
"10.0.0.2",
"10.0.0.3",
]
def test_the_selected_source_is_synchronized(self, driver):
stats = _stats(driver, CHRONY)
assert [s["synchronized"] for s in stats] == [True, False, False]
def test_fields_in_ntpq_units(self, driver):
first = _stats(driver, CHRONY)[0]
assert first == {
"remote": "192.168.1.1",
"referenceid": "",
"synchronized": True,
"stratum": 2,
"type": "u",
"when": "8",
"hostpoll": 64,
"reachability": 377,
"delay": 0.0,
"offset": pytest.approx(-0.013),
"jitter": pytest.approx(0.045678),
}
def test_a_source_without_statistics_has_no_jitter(self, driver):
last = _stats(driver, CHRONY)[2]
assert last["jitter"] == 0.0
assert last["when"] == "-"
assert last["reachability"] == 0
def test_the_command_asks_chrony_first(self, driver):
with patch.object(driver, "_exec_ssh_command", return_value="") as exec_:
driver.get_ntp_stats()
assert "chronyc -n -c sources" in exec_.call_args[0][0]
assert "ntpq -pn" in exec_.call_args[0][0]
class TestNtpd:
def test_a_peer_without_tally_mark_is_kept(self, driver):
stats = _stats(driver, NTPQ)
assert [s["remote"] for s in stats] == ["192.168.1.1", "192.168.1.5"]
assert [s["synchronized"] for s in stats] == [True, False]
assert stats[1]["stratum"] == 3
+107
View File
@@ -0,0 +1,107 @@
"""set_hostname: what it writes to /etc/hosts, and that it leaves a clustered node alone
(napalm-proxmox#21)."""
from __future__ import annotations
import base64
import re
import pytest
from napalm.base.exceptions import CommandErrorException
from napalm_proxmox import ProxmoxDriver
HOSTS = """\
127.0.0.1 localhost.localdomain localhost
# pve is the node; pve-backup its backup target
10.0.0.1 pve.old.lan pve
10.0.0.2 pve-backup.old.lan pve-backup
"""
class _Node:
"""The node's shell: /etc/hostname reads "pve", /etc/hosts reads HOSTS.
*cluster_check* is what the test for a corosync.conf prints: exit status 1
(no corosync.conf, a single node) unless a test says otherwise.
"""
def __init__(self) -> None:
self.ran: list[str] = []
self.cluster_check = "__PVE_RC=1"
def __call__(self, command: str) -> str:
self.ran.append(command)
if "corosync.conf" in command:
return self.cluster_check
if command.startswith("cat /etc/hostname"):
return "pve\n"
if command.startswith("cat /etc/hosts"):
return HOSTS
return ""
def written_hosts(self) -> str:
write = next(c for c in self.ran if c.rstrip().endswith("chmod 644 /etc/hosts"))
return base64.b64decode(re.match(r"echo (\S+) \| base64 -d", write).group(1)).decode()
@pytest.fixture
def node() -> _Node:
return _Node()
@pytest.fixture
def driver(node: _Node) -> ProxmoxDriver:
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = node
return d
def test_an_fqdn_renames_the_nodes_names_and_nothing_else(driver, node):
driver.set_hostname("new.dom.lan")
assert node.written_hosts() == (
"127.0.0.1 localhost.localdomain localhost\n"
"# pve is the node; pve-backup its backup target\n"
"10.0.0.1 new.dom.lan new\n"
"10.0.0.2 pve-backup.old.lan pve-backup\n"
)
def test_a_short_name_keeps_the_old_domain(driver, node):
driver.set_hostname("new")
assert "10.0.0.1 new.old.lan new\n" in node.written_hosts()
assert "10.0.0.2 pve-backup.old.lan pve-backup\n" in node.written_hosts()
def test_the_same_name_leaves_hosts_alone(driver, node):
driver.set_hostname("pve")
assert not any("/etc/hosts" in c and "base64 -d" in c for c in node.ran)
def test_a_clustered_node_is_refused_before_anything_changes(driver, node):
node.cluster_check = "__PVE_RC=0"
with pytest.raises(CommandErrorException, match="part of a cluster"):
driver.set_hostname("new")
assert [c for c in node.ran if "corosync.conf" not in c] == []
def test_the_cluster_check_looks_at_both_corosync_confs(driver, node):
driver.set_hostname("new")
check = next(c for c in node.ran if "corosync.conf" in c)
assert "/etc/pve/corosync.conf" in check
assert "/etc/corosync/corosync.conf" in check
def test_an_unreadable_cluster_check_refuses_too(driver, node):
node.cluster_check = ""
with pytest.raises(CommandErrorException, match="could not tell"):
driver.set_hostname("new")
assert [c for c in node.ran if "corosync.conf" not in c] == []
+79
View File
@@ -0,0 +1,79 @@
"""The node's SSH login takes any key type, and a key wins over the API password (#17)."""
from __future__ import annotations
import io
import paramiko
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
from napalm_proxmox.driver import ProxmoxDriver
from tests.test_ssh_host_key import client # noqa: F401 - the fake paramiko client fixture
def _ed25519_pem() -> str:
key = ed25519.Ed25519PrivateKey.generate()
return key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.OpenSSH,
serialization.NoEncryption(),
).decode()
def _paramiko_pem(key: paramiko.PKey) -> str:
out = io.StringIO()
key.write_private_key(out)
return out.getvalue()
def _driver(key: str, ssh_password: str | None = None) -> ProxmoxDriver:
args = {"ssh_private_key_str": key}
if ssh_password is not None:
args["ssh_password"] = ssh_password
return ProxmoxDriver("10.0.0.9", "root", "api-s3cret", optional_args=args)
@pytest.mark.parametrize(
("pem", "kind"),
[
(_ed25519_pem(), paramiko.Ed25519Key),
(_paramiko_pem(paramiko.ECDSAKey.generate()), paramiko.ECDSAKey),
(_paramiko_pem(paramiko.RSAKey.generate(1024)), paramiko.RSAKey),
],
)
def test_any_key_type_logs_in_although_an_api_password_is_set(client, pem, kind): # noqa: F811
_driver(pem)._node_ssh()
assert isinstance(client.connected_with["pkey"], kind)
def test_the_password_stays_as_the_fallback(client): # noqa: F811
_driver(_ed25519_pem(), ssh_password="ssh-pw")._node_ssh()
assert client.connected_with["password"] == "ssh-pw"
def test_without_key_the_password_logs_in(client): # noqa: F811
ProxmoxDriver("10.0.0.9", "root", "api-s3cret")._node_ssh()
assert client.connected_with["password"] == "api-s3cret"
assert "pkey" not in client.connected_with
def test_a_key_that_cannot_be_read_leaves_the_password(client, caplog): # noqa: F811
_driver("not a key")._node_ssh()
assert "pkey" not in client.connected_with
assert client.connected_with["password"] == "api-s3cret"
assert "not a key" not in caplog.text
assert "could not be read" in caplog.text
def test_a_token_only_login_sends_no_empty_password(client): # noqa: F811
ProxmoxDriver(
"10.0.0.9", "root", "", optional_args={"ssh_private_key_str": _ed25519_pem()}
)._node_ssh()
assert "password" not in client.connected_with
+58
View File
@@ -0,0 +1,58 @@
"""The physical port set_vlan configures: _find_switch_uplink / _is_physical_uplink."""
from __future__ import annotations
from unittest.mock import MagicMock
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
NETWORK = [
{"iface": "eno1", "type": "eth"},
{"iface": "vmbr0", "type": "bridge", "bridge_ports": "eno1"},
]
def _mixin(detail: dict, basic: dict) -> ProxmoxSDNMixin:
m = ProxmoxSDNMixin()
m._get_node_network = MagicMock(return_value=NETWORK)
m.get_lldp_neighbors_detail = MagicMock(return_value=detail)
m.get_lldp_neighbors = MagicMock(return_value=basic)
return m
class TestFindSwitchUplink:
def test_physical_port_with_a_bridge_neighbour_is_the_uplink(self):
m = _mixin(
detail={
"tap100i0": [{"remote_system_capab": ["bridge"]}],
"eno1": [{"remote_system_capab": ["bridge", "router"]}],
},
basic={},
)
assert m._find_switch_uplink() == "eno1"
def test_basic_lldp_fallback_skips_a_virtual_port(self):
m = _mixin(
detail={},
basic={"fwpr100p0": [{"hostname": "sw"}], "eno1": [{"hostname": "sw"}]},
)
assert m._find_switch_uplink() == "eno1"
def test_no_physical_neighbour_is_none(self):
m = _mixin(detail={"tap100i0": [{"remote_system_capab": ["bridge"]}]}, basic={})
assert m._find_switch_uplink() is None
class TestIsPhysicalUplink:
def test_eth_in_the_network_config_is_physical(self):
assert ProxmoxSDNMixin()._is_physical_uplink("eno1", {"eno1": {"type": "eth"}})
def test_virtual_prefix_is_never_physical(self):
network = {"tap100i0": {"type": ""}}
assert not ProxmoxSDNMixin()._is_physical_uplink("tap100i0", network)
def test_port_missing_from_the_network_config_is_not_physical(self):
assert not ProxmoxSDNMixin()._is_physical_uplink("eno9", {})
def test_bridge_is_not_physical(self):
assert not ProxmoxSDNMixin()._is_physical_uplink("vmbr0", {"vmbr0": {"type": "bridge"}})
+29
View File
@@ -104,6 +104,35 @@ class TestRefresh:
assert result == {"success": False, "output": "403 Permission check failed"}
class TestApplyUpdates:
def test_a_clean_upgrade_succeeds(self, driver):
with patch.object(driver, "_exec_ssh_command", return_value="Done.\n__PVE_RC=0") as exec_:
result = driver.apply_updates(["curl"])
assert "apt-get install --only-upgrade -y curl" in exec_.call_args[0][0]
assert result == {"success": True, "output": "Done."}
def test_a_failed_upgrade_is_a_failure(self, driver):
out = "E: Could not get lock /var/lib/dpkg/lock-frontend\n__PVE_RC=100"
with patch.object(driver, "_exec_ssh_command", return_value=out):
result = driver.apply_updates(["curl"])
assert result["success"] is False
assert result["output"] == "E: Could not get lock /var/lib/dpkg/lock-frontend"
assert result["error"] == "apt-get exited with status 100"
def test_an_unread_exit_status_is_no_success(self, driver):
with patch.object(driver, "_exec_ssh_command", return_value=""):
result = driver.apply_updates(["curl"])
assert result["success"] is False
assert result["error"] == "apt-get's exit status could not be read"
def test_a_name_that_is_no_package_name_is_refused(self, driver):
with pytest.raises(ValueError):
driver.apply_updates(["curl;reboot"])
class TestHostStatus:
def test_the_node_is_read_over_the_exec_path(self, driver):
report = (
+66
View File
@@ -0,0 +1,66 @@
"""get_users: Proxmox users with their level, and the node's login accounts (#19)."""
from __future__ import annotations
from unittest.mock import patch
PASSWD = """\
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
alice:x:1000:1000:Alice:/home/alice:/bin/bash
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
"""
# GET /access/acl: who holds which role where.
ACL = [
{"path": "/", "roleid": "Administrator", "type": "user", "ugid": "admin@pve", "propagate": 1},
{"path": "/", "roleid": "Administrator", "type": "group", "ugid": "ops", "propagate": 1},
{"path": "/vms/100", "roleid": "Administrator", "type": "user", "ugid": "vm@pve"},
{"path": "/", "roleid": "PVEAuditor", "type": "user", "ugid": "audit@pve", "propagate": 1},
]
USERS = [
{"userid": "root@pam", "groups": ""},
{"userid": "admin@pve", "groups": ""},
{"userid": "bob@pve", "groups": "ops,dev"},
{"userid": "vm@pve", "groups": ""},
{"userid": "audit@pve", "groups": ""},
]
def _users(driver, passwd=PASSWD):
driver._api.access.users.get.return_value = USERS
driver._api.access.acl.get.return_value = ACL
with patch.object(driver, "_exec_ssh_command", return_value=passwd):
return driver.get_users()
class TestLocalAccounts:
def test_root_and_real_users_not_system_accounts(self, driver):
result = _users(driver)
assert result["root"]["level"] == 15
assert "alice" in result
for system in ("daemon", "bin", "www-data", "nobody"):
assert system not in result
class TestProxmoxUsers:
def test_administrator_on_the_whole_datacenter_is_level_15(self, driver):
result = _users(driver)
assert result["admin@pve"]["level"] == 15
def test_administrator_through_a_group_is_level_15(self, driver):
assert _users(driver)["bob@pve"]["level"] == 15
def test_root_at_pam_is_always_level_15(self, driver):
assert _users(driver)["root@pam"]["level"] == 15
def test_another_role_or_a_narrower_path_is_level_1(self, driver):
result = _users(driver)
assert result["audit@pve"]["level"] == 1
assert result["vm@pve"]["level"] == 1
+133
View File
@@ -484,6 +484,42 @@ def test_destroy_vm_already_stopped():
assert mock_vm.delete.called
def _destroy_mixin(delete_task: dict) -> tuple[ProxmoxVMProvisionMixin, MagicMock]:
mixin = ProxmoxVMProvisionMixin()
node = MagicMock()
mixin._node_api = MagicMock(return_value=node)
vm = node.qemu.return_value
vm.status.stop.post.return_value = "UPID:pve1:125:stop"
vm.config.get.return_value = {}
vm.delete.return_value = "UPID:pve1:126:qmdestroy"
tasks = {
"UPID:pve1:125:stop": {"status": "stopped", "exitstatus": "OK"},
"UPID:pve1:126:qmdestroy": delete_task,
}
node.tasks.side_effect = lambda upid: MagicMock(**{"status.get.return_value": tasks[upid]})
return mixin, node
def test_destroy_vm_waits_for_the_delete_task():
"""destroy_vm returns once the VM is gone, not when its delete was queued (#15)."""
mixin, node = _destroy_mixin({"status": "stopped", "exitstatus": "OK"})
with patch("time.sleep"):
mixin.destroy_vm("101")
assert [c.args[0] for c in node.tasks.call_args_list] == [
"UPID:pve1:125:stop",
"UPID:pve1:126:qmdestroy",
]
def test_destroy_vm_raises_when_the_delete_task_fails():
mixin, _ = _destroy_mixin({"status": "stopped", "exitstatus": "VM is locked (backup)"})
with patch("time.sleep"), pytest.raises(RuntimeError, match="VM is locked"):
mixin.destroy_vm("101")
# ---------------------------------------------------------------------------
# get_network_targets
# ---------------------------------------------------------------------------
@@ -1280,3 +1316,100 @@ def test_create_vm_cloudinit_drive_uses_image_storage_not_snippet_storage():
cloud_init_call = next(c for c in mock_vm.config.post.call_args_list if "ide2" in c[1])
assert cloud_init_call[1]["ide2"] == "local-zfs:cloudinit"
assert cloud_init_call[1]["cicustom"].startswith("user=local:snippets/")
def test_create_vm_passes_every_ssh_key_one_per_line():
"""Proxmox's sshkeys is one key per line, URL-encoded (napalm-proxmox#23).
Joined with ";", only the first key worked. Base64 keys carry "/" and "+",
which Proxmox's urlencoded format refuses unescaped.
"""
import re
from urllib.parse import unquote
mixin = ProxmoxVMProvisionMixin()
mixin._node_name = "pve1"
mock_api = MagicMock()
mock_api.cluster.nextid.get.return_value = 110
mock_api.storage.return_value.get.return_value = {"path": "/var/lib/vz"}
mock_node = MagicMock()
mock_node.storage.get.return_value = [
{"storage": "local", "type": "dir", "content": "images,snippets", "enabled": 1},
]
mixin._api = mock_api
mixin._node_api = MagicMock(return_value=mock_node)
mixin._download_cloud_image = MagicMock(return_value="/var/lib/vz/x.qcow2")
mixin._run_node_command = MagicMock(return_value="")
mock_vm = mock_node.qemu.return_value
mock_vm.config.get.return_value = {"unused0": "local:vm-110-disk-0"}
mock_vm.status.start.post.return_value = "UPID:pve1:136:start"
mock_node.tasks.return_value.status.get.return_value = {"status": "stopped", "exitstatus": "OK"}
keys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI/+k1 alice@example",
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB/+k2 bob@example",
]
with patch("time.sleep"):
mixin.create_vm_from_cloud_init(
name="keys-vm",
image_url="https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2",
cpu=1,
memory=512,
nics=[{"bridge": "vmbr0"}],
cloud_init_config={},
ssh_public_keys=keys,
)
call = next(c for c in mock_vm.config.post.call_args_list if "sshkeys" in c[1])
sshkeys = call[1]["sshkeys"]
assert unquote(sshkeys) == "\n".join(keys)
assert re.fullmatch(r"[-%a-zA-Z0-9_.!~*'()]*", sshkeys)
class _LocalShell:
"""The node's SSH session as a local ``sh``, *prelude* run before each command."""
def __init__(self, prelude: str) -> None:
self.prelude = prelude
def exec_command(self, command: str, timeout: int | None = None):
import subprocess
run = subprocess.run(
["sh", "-c", self.prelude + command], capture_output=True, timeout=timeout
)
return _mock_ssh_exec(run.returncode, run.stdout.decode(), run.stderr.decode())
# wget as it fails on a full disk: part of the file written, the reason on stderr.
_WGET_DISK_FULL = (
"wget() { "
'while [ $# -gt 0 ]; do [ "$1" = -O ] && o=$2; shift; done; '
'echo partial > "$o"; '
'echo "$o: No space left on device" >&2; return 3; }; '
)
def test_download_cloud_image_failure_says_why_and_leaves_no_tmp(tmp_path, monkeypatch):
"""A failed download names wget's reason and removes its .tmp (napalm-proxmox#3)."""
import napalm_proxmox.vm_provision_mixin as module
monkeypatch.setattr(module, "_IMAGE_CACHE_DIR", str(tmp_path))
mixin = ProxmoxVMProvisionMixin()
mixin._node_ssh = MagicMock(return_value=_LocalShell(_WGET_DISK_FULL))
with pytest.raises(RuntimeError, match="No space left on device") as err:
mixin._download_cloud_image("https://example.org/img/debian.qcow2", None, timeout=10)
assert "exit 3" in str(err.value)
assert list(tmp_path.iterdir()) == []
def test_download_cloud_image_does_not_silence_wget():
mixin = ProxmoxVMProvisionMixin()
mixin._run_node_command = MagicMock(side_effect=["MISSING", ""])
mixin._download_cloud_image("https://example.org/img/debian.qcow2", None, timeout=10)
download = mixin._run_node_command.call_args_list[1][0][0]
assert download.startswith("wget -nv ")