With an API key and a known MAC, opening sent no request at all: a refused key, a redirect or a device the controller does not know showed only at the first getter. Open now reads the device and closes again when that fails.
268 lines
8.9 KiB
Python
268 lines
8.9 KiB
Python
"""What a UniFi switch or access point driver does with its arguments and its source.
|
|
|
|
The controller and the SSH shell are replaced at the seams ``open_controller`` and
|
|
``SshShell``; the record comes from the fixtures.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import pathlib
|
|
from typing import Any
|
|
|
|
import pytest
|
|
from conftest import load
|
|
from napalm.base.exceptions import ConnectionException
|
|
|
|
from napalm_ubiquiti import device
|
|
from napalm_ubiquiti.client import UnifiError
|
|
from napalm_ubiquiti.device import UnifiDevice
|
|
from napalm_ubiquiti.sources import DUMP_COMMAND
|
|
|
|
|
|
class FakeClient:
|
|
def __init__(self, data: dict[str, list[Any]]) -> None:
|
|
self.data = data
|
|
self.asked: list[tuple[str, str]] = []
|
|
self.session = FakeSession()
|
|
|
|
def classic_get(self, site: str, endpoint: str) -> list[Any]:
|
|
self.asked.append((site, endpoint))
|
|
return self.data.get(endpoint, [])
|
|
|
|
|
|
class FakeSession:
|
|
closed = False
|
|
|
|
def close(self) -> None:
|
|
self.closed = True
|
|
|
|
|
|
class FakeShell:
|
|
def __init__(self, host: str, **kwargs: Any) -> None:
|
|
self.host = host
|
|
self.kwargs = kwargs
|
|
self.answers: dict[str, str] = {}
|
|
self.opened = False
|
|
self.closed = False
|
|
|
|
def open(self) -> None:
|
|
self.opened = True
|
|
|
|
def run(self, command: str) -> str:
|
|
return self.answers[command]
|
|
|
|
def close(self) -> None:
|
|
self.closed = True
|
|
|
|
|
|
class Driver(UnifiDevice):
|
|
"""The mixin alone, as a concrete driver puts it before its role base."""
|
|
|
|
|
|
@pytest.fixture
|
|
def controller(monkeypatch: pytest.MonkeyPatch, us16: dict[str, Any]) -> dict[str, Any]:
|
|
opened: dict[str, Any] = {}
|
|
mac = us16["mac"]
|
|
|
|
def fake_open(url: str, login: Any, args: Any, timeout: float) -> FakeClient:
|
|
opened.update(url=url, login=login, timeout=timeout)
|
|
opened["client"] = FakeClient({f"stat/device/{mac}": [us16], "stat/device": [us16]})
|
|
return opened["client"]
|
|
|
|
monkeypatch.setattr(device, "open_controller", fake_open)
|
|
return opened
|
|
|
|
|
|
@pytest.fixture
|
|
def shells(monkeypatch: pytest.MonkeyPatch, us24_dump: dict[str, Any]) -> list[FakeShell]:
|
|
made: list[FakeShell] = []
|
|
|
|
def factory(host: str, **kwargs: Any) -> FakeShell:
|
|
shell = FakeShell(host, **kwargs)
|
|
shell.answers[DUMP_COMMAND] = json.dumps(us24_dump)
|
|
made.append(shell)
|
|
return shell
|
|
|
|
monkeypatch.setattr(device, "SshShell", factory)
|
|
return made
|
|
|
|
|
|
class TestTransport:
|
|
def test_a_controller_url_means_the_controller(
|
|
self, controller: dict[str, Any], us16: dict[str, Any]
|
|
) -> None:
|
|
args = {"controller_url": "https://192.0.2.1", "token_value": "k", "mac": us16["mac"]}
|
|
driver = Driver("192.0.2.20", "", "", optional_args=args)
|
|
|
|
driver.open()
|
|
|
|
assert controller["url"] == "https://192.0.2.1"
|
|
assert controller["login"].api_key == "k"
|
|
assert driver.get_facts()["model"] == "US16P150"
|
|
|
|
def test_without_a_mac_the_device_is_found_by_its_address(
|
|
self, controller: dict[str, Any], us16: dict[str, Any]
|
|
) -> None:
|
|
args = {"controller_url": "https://192.0.2.1", "token_value": "k"}
|
|
driver = Driver(us16["ip"], "", "", optional_args=args)
|
|
|
|
driver.open()
|
|
|
|
assert driver.get_facts()["serial_number"] == us16["serial"].upper()
|
|
assert controller["client"].asked == [("default", "stat/device")]
|
|
|
|
def test_an_address_the_controller_does_not_know(self, controller: dict[str, Any]) -> None:
|
|
args = {"controller_url": "https://192.0.2.1", "token_value": "k"}
|
|
|
|
with pytest.raises(UnifiError, match="192.0.2.99"):
|
|
Driver("192.0.2.99", "", "", optional_args=args).open()
|
|
|
|
def test_another_site(self, controller: dict[str, Any], us16: dict[str, Any]) -> None:
|
|
args = {
|
|
"controller_url": "https://c",
|
|
"token_value": "k",
|
|
"site": "branch",
|
|
"mac": us16["mac"],
|
|
}
|
|
driver = Driver("192.0.2.20", "", "", optional_args=args)
|
|
driver.open()
|
|
driver.get_facts()
|
|
|
|
assert controller["client"].asked == [("branch", f"stat/device/{us16['mac']}")]
|
|
|
|
def test_without_a_controller_the_device_is_read_over_ssh(
|
|
self, shells: list[FakeShell]
|
|
) -> None:
|
|
driver = Driver("192.0.2.30", "ubnt", "pw")
|
|
|
|
driver.open()
|
|
|
|
assert shells[0].host == "192.0.2.30"
|
|
assert shells[0].kwargs["username"] == "ubnt"
|
|
assert shells[0].kwargs["password"] == "pw"
|
|
assert shells[0].kwargs["port"] == 22
|
|
assert driver.get_facts()["hostname"] == "usw-1"
|
|
|
|
def test_a_separate_ssh_profile_wins(self, shells: list[FakeShell]) -> None:
|
|
args = {"ssh_username": "admin", "ssh_password": "pw2", "ssh_port": 2222}
|
|
|
|
Driver("192.0.2.30", "ubnt", "pw", optional_args=args).open()
|
|
|
|
assert shells[0].kwargs["username"] == "admin"
|
|
assert shells[0].kwargs["password"] == "pw2"
|
|
assert shells[0].kwargs["port"] == 2222
|
|
|
|
def test_an_ssh_key_from_a_file(self, shells: list[FakeShell], tmp_path: pathlib.Path) -> None:
|
|
key = tmp_path / "id"
|
|
key.write_text("KEY")
|
|
|
|
Driver("192.0.2.30", "ubnt", "", optional_args={"key_file": str(key)}).open()
|
|
|
|
assert shells[0].kwargs["private_key"] == "KEY"
|
|
|
|
def test_an_ssh_key_as_text(self, shells: list[FakeShell]) -> None:
|
|
Driver("h", "u", "", optional_args={"ssh_private_key_str": "KEY"}).open()
|
|
|
|
assert shells[0].kwargs["private_key"] == "KEY"
|
|
|
|
def test_an_unknown_transport(self) -> None:
|
|
with pytest.raises(ConnectionException, match="transport"):
|
|
Driver("h", "u", "p", optional_args={"transport": "telnet"})
|
|
|
|
def test_the_controller_transport_needs_its_url(self) -> None:
|
|
with pytest.raises(ConnectionException, match="controller_url"):
|
|
Driver("h", "u", "p", optional_args={"transport": "controller"})
|
|
|
|
def test_a_controller_url_without_scheme_is_https(
|
|
self, controller: dict[str, Any], us16: dict[str, Any]
|
|
) -> None:
|
|
Driver(
|
|
"h", "", "", optional_args={"controller_url": "unifi.lan:8443", "mac": us16["mac"]}
|
|
).open()
|
|
|
|
assert controller["url"] == "https://unifi.lan:8443"
|
|
|
|
|
|
class TestSession:
|
|
def test_open_reads_the_device_once(self, shells: list[FakeShell]) -> None:
|
|
driver = Driver("h", "u", "p")
|
|
driver.open()
|
|
driver.get_facts()
|
|
driver.get_interfaces()
|
|
|
|
assert driver.is_alive() == {"is_alive": True}
|
|
|
|
def test_a_device_that_cannot_be_read_fails_open_and_closes(
|
|
self, shells: list[FakeShell], monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
monkeypatch.setattr(FakeShell, "run", lambda self, command: "not json")
|
|
driver = Driver("h", "u", "p")
|
|
|
|
with pytest.raises(Exception, match="mca-dump"):
|
|
driver.open()
|
|
|
|
assert shells[0].closed is True
|
|
assert driver.is_alive() == {"is_alive": False}
|
|
|
|
def test_getters_before_open(self) -> None:
|
|
with pytest.raises(ConnectionException, match="not open"):
|
|
Driver("h", "u", "p").get_facts()
|
|
|
|
def test_close_closes_the_shell(self, shells: list[FakeShell]) -> None:
|
|
driver = Driver("h", "u", "p")
|
|
driver.open()
|
|
|
|
driver.close()
|
|
|
|
assert shells[0].closed is True
|
|
assert driver.is_alive() == {"is_alive": False}
|
|
|
|
def test_close_closes_the_controller_session(
|
|
self, controller: dict[str, Any], us16: dict[str, Any]
|
|
) -> None:
|
|
driver = Driver(
|
|
"h", "", "", optional_args={"controller_url": "https://c", "mac": us16["mac"]}
|
|
)
|
|
driver.open()
|
|
assert driver.is_alive() == {"is_alive": True}
|
|
|
|
driver.close()
|
|
|
|
assert controller["client"].session.closed is True
|
|
|
|
def test_close_without_open(self) -> None:
|
|
Driver("h", "u", "p").close()
|
|
|
|
|
|
class TestReadings:
|
|
@pytest.fixture
|
|
def opened(self, shells: list[FakeShell]) -> Driver:
|
|
driver = Driver("192.0.2.30", "ubnt", "pw")
|
|
driver.open()
|
|
return driver
|
|
|
|
def test_interfaces_and_addresses(self, opened: Driver) -> None:
|
|
assert "Port 1" in opened.get_interfaces()
|
|
assert "Management" in opened.get_interfaces_ip()
|
|
|
|
def test_lldp_both_ways(self, opened: Driver) -> None:
|
|
neighbours = opened.get_lldp_neighbors()
|
|
detail = opened.get_lldp_neighbors_detail()
|
|
|
|
assert neighbours
|
|
assert set(detail) == set(neighbours)
|
|
|
|
def test_lldp_for_one_port(self, opened: Driver) -> None:
|
|
port = next(iter(opened.get_lldp_neighbors()))
|
|
|
|
assert set(opened.get_lldp_neighbors_detail(port)) == {port}
|
|
|
|
def test_mac_table(self, opened: Driver) -> None:
|
|
assert isinstance(opened.get_mac_address_table(), list)
|
|
|
|
|
|
def test_the_fixture_record_has_lldp() -> None:
|
|
"""The SSH fixture carries LLDP neighbours, or the LLDP tests above prove nothing."""
|
|
assert load("ssh/us24-7.1.26-mca-dump.json").get("lldp_table")
|