"""``get_dhcp_leases``: dnsmasq's lease file (NetOrk/netork#695). The text is dnsmasq 2.90's lease file on OpenWrt 23.05, anonymised: two DHCPv4 leases (one without a hostname, one that does not end), then the DHCPv6 part after its ``duid`` line. """ from __future__ import annotations import pytest from napalm.base.exceptions import CommandErrorException from napalm_device_types import CommandResult from napalm_openwrt.dhcp_leases_mixin import LEASES_COMMAND, parse_dnsmasq_leases from tests.unit.test_wireless_writes import _driver LEASES = """\ 1764432000 00:00:5e:00:53:01 192.0.2.42 laptop 01:00:00:5e:00:53:01 1764435600 00:00:5E:00:53:02 192.0.2.43 * * 0 00:00:5e:00:53:03 192.0.2.44 printer * duid 00:01:00:01:2c:5e:9a:10:00:00:5e:00:53:ff 1764432000 1234567 2001:db8::42 laptop 00:01:00:01:2c:5e:9a:11:00:00:5e:00:53:01 """ def test_each_v4_lease_in_order(): assert parse_dnsmasq_leases(LEASES) == [ { "mac": "00:00:5e:00:53:01", "ip": "192.0.2.42", "hostname": "laptop", "lease_end": 1764432000, "state": "active", }, { "mac": "00:00:5e:00:53:02", "ip": "192.0.2.43", "hostname": "", "lease_end": 1764435600, "state": "active", }, { "mac": "00:00:5e:00:53:03", "ip": "192.0.2.44", "hostname": "printer", "lease_end": 0, "state": "active", }, ] @pytest.mark.parametrize("text", ["", "\n", "garbage\n", "x 00:00:5e:00:53:01 192.0.2.1 a *\n"]) def test_nothing_that_is_no_lease(text): assert parse_dnsmasq_leases(text) == [] class _Ap: def __init__(self, answer: CommandResult) -> None: self.answer = answer self.commands: list[str] = [] def __call__(self, command: str, **_: object) -> CommandResult: self.commands.append(command) return self.answer def test_the_driver_reads_the_lease_file_dnsmasq_is_set_to(): ap = _Ap(CommandResult(LEASES, "", 0)) leases = _driver(ap).get_dhcp_leases() # type: ignore[arg-type] assert ap.commands == [LEASES_COMMAND] assert "uci -q get dhcp.@dnsmasq[0].leasefile" in LEASES_COMMAND assert [lease["ip"] for lease in leases] == ["192.0.2.42", "192.0.2.43", "192.0.2.44"] def test_an_ap_that_serves_no_leases_has_none(): """No lease file is no dnsmasq run since boot: an answer, not a failed read.""" assert _driver(_Ap(CommandResult("", "", 0))).get_dhcp_leases() == [] # type: ignore[arg-type] def test_a_failed_read_raises(): ap = _Ap(CommandResult("", "cat: can't open '/tmp/dhcp.leases': Permission denied\n", 1)) with pytest.raises(CommandErrorException, match="Permission denied"): _driver(ap).get_dhcp_leases() # type: ignore[arg-type]