Files
napalm-ubiquiti/tests/test_network_driver.py
T
Christian Manivong cad167389e
driver / standard (pull_request) Failing after 19s
driver / lint (pull_request) Successful in 16s
driver / test (3.12) (pull_request) Failing after 17s
driver / test (3.13) (pull_request) Failing after 15s
driver / types (pull_request) Failing after 32s
driver / lowest (pull_request) Failing after 22s
driver / build (pull_request) Successful in 39s
driver / security (pull_request) Failing after 45s
CI / driver (pull_request) Failing after 1m27s
driver / publish (pull_request) Skipped
feat: the controller names each device's driver and the way to it
An adopted switch or access point carries driver (unifi_switch, unifi_ap)
and driver_args (controller transport, URL, site, MAC; no secret), so netOrk
can add it with the controller's credential. A device waiting for adoption
and a gateway get none. The end-to-end test opens an access point with
exactly what the controller reported.
2026-12-05 17:17:49 +01:00

210 lines
8.0 KiB
Python

"""The UniFi Network controller as a device: what it is, and the devices it manages."""
from __future__ import annotations
from typing import Any
import pytest
from conftest import load
from napalm.base.exceptions import ConnectionException
from napalm_device_types import NetworkControllerDriver
from napalm_device_types.roles import primary_role_of
from napalm_ubiquiti import UnifiNetworkDriver, controller
from napalm_ubiquiti.client import NotFound
SITE_ID = "88f7af54-98f8-306a-a1c7-c9349722b1f6"
class FakeController:
"""Integration API and classic API, as far as the recorded answers reach."""
def __init__(self, integration: dict[str, Any], classic: dict[tuple[str, str], list[Any]]):
self.integration = integration
self.classic = classic
self.sites = [{"name": site} for site, _ in classic]
self.session = type(
"S", (), {"closed": False, "close": lambda s: setattr(s, "closed", True)}
)()
def integration_get(self, endpoint: str, params: Any = None) -> Any:
if endpoint not in self.integration:
raise NotFound(endpoint)
return self.integration[endpoint]
def integration_list(self, endpoint: str) -> list[Any]:
return list(self.integration_get(endpoint)["data"])
def classic_sites(self) -> list[Any]:
return [dict(s) for s in {s["name"]: s for s in self.sites}.values()]
def classic_get(self, site: str, endpoint: str) -> list[Any]:
return self.classic.get((site, endpoint), [])
def _integration(version: str = "10.6.106", pending: bool = True) -> dict[str, Any]:
answers = {
"info": {"applicationVersion": version},
"sites": load("integration/v10.6.106-sites.json"),
f"sites/{SITE_ID}/devices": load("integration/v10.6.106-devices.json"),
}
if pending:
answers["pending-devices"] = load("integration/v10.6.106-pending-devices.json")
return answers
@pytest.fixture
def opened(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
seen: dict[str, Any] = {}
def fake_open(url: str, login: Any, args: Any, timeout: float) -> FakeController:
seen.update(url=url, login=login)
return seen["controller"] # type: ignore[no-any-return]
monkeypatch.setattr(controller, "open_controller", fake_open)
return seen
def _driver(seen: dict[str, Any], fake: FakeController, **args: Any) -> UnifiNetworkDriver:
seen["controller"] = fake
driver = UnifiNetworkDriver("192.0.2.1", "", "", optional_args={"token_value": "k", **args})
driver.open()
return driver
def test_its_role() -> None:
assert issubclass(UnifiNetworkDriver, NetworkControllerDriver)
assert primary_role_of(UnifiNetworkDriver) == "network_controller"
assert UnifiNetworkDriver.DRIVER_NAME == "unifi_network"
assert UnifiNetworkDriver.USES_SSH is False
class TestConnection:
def test_unifi_os_on_443(self, opened: dict[str, Any]) -> None:
_driver(opened, FakeController(_integration(), {}))
assert opened["url"] == "https://192.0.2.1:443"
assert opened["login"].api_key == "k"
def test_a_standalone_controller_on_8443(self, opened: dict[str, Any]) -> None:
_driver(opened, FakeController({}, {}), port=8443)
assert opened["url"] == "https://192.0.2.1:8443"
def test_an_ipv6_controller(self, opened: dict[str, Any]) -> None:
opened["controller"] = FakeController({}, {})
UnifiNetworkDriver("2001:db8::1", "a", "b").open()
assert opened["url"] == "https://[2001:db8::1]:443"
def test_close(self, opened: dict[str, Any]) -> None:
fake = FakeController({}, {})
driver = _driver(opened, fake)
assert driver.is_alive() == {"is_alive": True}
driver.close()
assert fake.session.closed is True
assert driver.is_alive() == {"is_alive": False}
def test_reading_before_open(self) -> None:
with pytest.raises(ConnectionException, match="not open"):
UnifiNetworkDriver("h", "u", "p").get_managed_devices()
class TestFacts:
def test_the_application_version_from_the_integration_api(self, opened: dict[str, Any]) -> None:
facts = _driver(opened, FakeController(_integration(), {})).get_facts()
assert facts["vendor"] == "Ubiquiti"
assert facts["model"] == "UniFi Network"
assert facts["os_version"] == "10.6.106"
assert facts["hostname"] == "192.0.2.1"
assert facts["interface_list"] == []
def test_a_standalone_controller_reports_its_version_in_sysinfo(
self, opened: dict[str, Any]
) -> None:
fake = FakeController({}, {("default", "stat/sysinfo"): [{"version": "8.0.24"}]})
assert _driver(opened, fake).get_facts()["os_version"] == "8.0.24"
def test_its_own_interfaces_are_none_of_its_devices(self, opened: dict[str, Any]) -> None:
driver = _driver(opened, FakeController(_integration(), {}))
assert driver.get_interfaces() == {}
assert driver.get_interfaces_ip() == {}
assert driver.get_lldp_neighbors() == {}
class TestManagedDevices:
def test_through_the_integration_api_with_pending_ones(self, opened: dict[str, Any]) -> None:
devices = _driver(opened, FakeController(_integration(), {})).get_managed_devices()
pending = [d for d in devices if d["state"] == "pending"]
assert {d["site"] for d in devices} == {"default"}
assert [d["mac"] for d in pending] == ["f4:92:bf:00:00:aa"]
assert len(devices) == len(load("integration/v10.6.106-devices.json")["data"]) + 1
def test_without_pending_devices_on_9_1(self, opened: dict[str, Any]) -> None:
fake = FakeController(_integration("9.1.120", pending=False), {})
devices = _driver(opened, fake).get_managed_devices()
assert all(d["state"] != "pending" for d in devices)
def test_each_adopted_device_names_its_driver_and_the_way_in(
self, opened: dict[str, Any]
) -> None:
devices = _driver(opened, FakeController(_integration(), {})).get_managed_devices()
switch = next(d for d in devices if d["role"] == "switch")
ap = next(d for d in devices if d["role"] == "access_point" and d["state"] != "pending")
assert switch["driver"] == "unifi_switch"
assert ap["driver"] == "unifi_ap"
assert switch["driver_args"] == {
"transport": "controller",
"controller_url": "https://192.0.2.1:443",
"site": "default",
"mac": switch["mac"],
}
def test_no_driver_for_a_pending_device_or_a_gateway(
self, opened: dict[str, Any], us16: dict[str, Any]
) -> None:
gateway = load("controller/ugw3-4.4.44-stat-device.json")
fake = FakeController({}, {("default", "stat/device"): [gateway]})
pending = _driver(opened, FakeController(_integration(), {})).get_managed_devices()
assert "driver" not in _driver(opened, fake).get_managed_devices()[0]
assert all("driver" not in d for d in pending if d["state"] == "pending")
def test_one_site_only(self, opened: dict[str, Any]) -> None:
driver = _driver(opened, FakeController(_integration(), {}), site="branch")
assert driver.get_managed_devices() == []
def test_through_the_classic_api_without_integration(
self, opened: dict[str, Any], us16: dict[str, Any], uap: dict[str, Any]
) -> None:
fake = FakeController(
{}, {("default", "stat/device"): [us16], ("branch", "stat/device"): [uap]}
)
devices = _driver(opened, fake).get_managed_devices()
assert [(d["mac"], d["site"], d["role"]) for d in devices] == [
(us16["mac"], "default", "switch"),
(uap["mac"], "branch", "access_point"),
]
assert devices[0]["serial"] == us16["serial"].upper()
def test_classic_one_site(self, opened: dict[str, Any], us16: dict[str, Any]) -> None:
fake = FakeController(
{}, {("default", "stat/device"): [us16], ("branch", "stat/device"): []}
)
devices = _driver(opened, fake, site="branch").get_managed_devices()
assert devices == []