A GET of the DAL answers sealed ({"content", "iv"}), like a PUT does.
_read_dal_or_page parsed the envelope as it came, so hosts, the ARP
table, port forwards and the Wi-Fi getters found nothing on every
gateway, and since nothing raised the HTML fallback never ran either.
Every DAL GET now goes through one helper that decrypts the answer,
checks for ZCFG_SUCCESS and returns its Object list; the status page
and the System page share the decryption. Hosts are read from
lanhosts and port forwards from nat, the names the gateway's web
interface uses: LAN_HOSTS and NAT_PORTMAP are answered like any
unknown name, with an empty Object. The new parsers live in
napalm_zyxel/parsers.py, under strict mypy.
Tests seal recorded, anonymised answers of a VMG4005-B50A
(V5.17(ABQA.3.1)C0) with a real ZyxelCrypto, so the driver decrypts
them. The Wi-Fi DAL names stay unverified: that gateway has no Wi-Fi.
Closes #25
148 lines
5.5 KiB
Python
148 lines
5.5 KiB
Python
"""A failed request to the gateway raises; it is not read as "nothing configured" (#15).
|
|
|
|
``_dal_query`` and ``_fetch_page`` returned ``None`` for any failure, and the getters
|
|
turned that into empty data: a timeout or an expired session read as a gateway with
|
|
no hosts, port forwards, SSIDs or Wi-Fi clients. Empty data is now the answer of a
|
|
gateway that answered with none; a getter whose DAL request fails still reads the
|
|
HTML page, and raises when that fails too.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Any
|
|
from unittest.mock import MagicMock
|
|
|
|
import pytest
|
|
import requests
|
|
from napalm.base.exceptions import ConnectionException
|
|
|
|
from napalm_zyxel import ZyxelVMGDriver
|
|
from tests.gateway import fixture
|
|
|
|
HOSTS_DAL = fixture("lanhosts") # tests/gateway.py
|
|
HOSTS_PAGE = "192.168.1.34 aa:bb:cc:dd:ee:02 tablet"
|
|
|
|
|
|
def _response(status: int, text: str = "") -> requests.Response:
|
|
resp = requests.Response()
|
|
resp.status_code = status
|
|
resp._content = text.encode()
|
|
resp.url = "http://192.168.1.1/"
|
|
return resp
|
|
|
|
|
|
def _driver(answers: dict[str, requests.Response | Exception]) -> ZyxelVMGDriver:
|
|
"""A logged-in driver whose session answers each path as told; 404 otherwise."""
|
|
driver = ZyxelVMGDriver("192.168.1.1", "admin", "password")
|
|
# NAPALM's __del__ asks is_alive(), which opens a TCP connection: not in a test.
|
|
driver.is_alive = lambda: {"is_alive": False} # type: ignore[method-assign]
|
|
session = MagicMock(spec=requests.Session)
|
|
|
|
def answer(url: str, params: dict[str, Any] | None = None, **_: Any) -> requests.Response:
|
|
path = url.removeprefix("http://192.168.1.1:80/")
|
|
oid = (params or {}).get("oid")
|
|
reply = answers.get(f"{path}?oid={oid}" if oid else path, _response(404))
|
|
if isinstance(reply, Exception):
|
|
raise reply
|
|
return reply
|
|
|
|
session.get.side_effect = answer
|
|
session.put.side_effect = answer
|
|
driver._session = session
|
|
driver._sessionkey = "1"
|
|
driver._crypto = MagicMock()
|
|
driver._crypto.decrypt_response.side_effect = lambda data: data
|
|
driver._device_info = {"ModelName": "VMG4005-B50A"}
|
|
return driver
|
|
|
|
|
|
# --- _dal_query --------------------------------------------------------------------
|
|
|
|
|
|
def test_dal_query_returns_the_gateways_answer():
|
|
driver = _driver({"cgi-bin/DAL?oid=DIAGNOSTICS": _response(200, '{"result": "ZCFG_SUCCESS"}')})
|
|
assert driver._dal_query("DIAGNOSTICS") == {"result": "ZCFG_SUCCESS"}
|
|
|
|
|
|
def test_dal_query_raises_when_the_gateway_does_not_answer():
|
|
driver = _driver({"cgi-bin/DAL?oid=DIAGNOSTICS": requests.ConnectTimeout("timed out")})
|
|
with pytest.raises(ConnectionException, match="timed out"):
|
|
driver._dal_query("DIAGNOSTICS")
|
|
|
|
|
|
@pytest.mark.parametrize("status", [401, 403])
|
|
def test_dal_query_raises_connection_exception_for_a_refused_session(status):
|
|
driver = _driver({"cgi-bin/DAL?oid=DIAGNOSTICS": _response(status)})
|
|
with pytest.raises(ConnectionException, match=str(status)):
|
|
driver._dal_query("DIAGNOSTICS")
|
|
|
|
|
|
@pytest.mark.parametrize("reply", [_response(500), _response(200, "<html>busy</html>")])
|
|
def test_dal_query_names_the_endpoint_of_any_other_failure(reply):
|
|
driver = _driver({"cgi-bin/DAL?oid=DIAGNOSTICS": reply})
|
|
with pytest.raises(RuntimeError, match="DIAGNOSTICS"):
|
|
driver._dal_query("DIAGNOSTICS")
|
|
|
|
|
|
def test_get_diagnostics_raises_when_the_dal_request_fails():
|
|
driver = _driver({"cgi-bin/DAL?oid=DIAGNOSTICS": _response(500)})
|
|
with pytest.raises(RuntimeError):
|
|
driver.get_diagnostics()
|
|
|
|
|
|
def test_a_reboot_that_fails_to_reach_the_gateway_raises():
|
|
driver = _driver({"cgi-bin/DAL?oid=REBOOT": requests.ConnectionError("refused")})
|
|
with pytest.raises(ConnectionException):
|
|
driver.reboot_host()
|
|
|
|
|
|
# --- the getters ---------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("getter", "oid", "page"),
|
|
[
|
|
("get_hosts", "lanhosts", "dhcp.htm"),
|
|
("get_port_forwards", "nat", "Status.htm"),
|
|
("get_wireless_clients", "WIFI_CLIENTS", "wireless.htm"),
|
|
("get_ssids", "WIFI_SSIDS", "wireless.htm"),
|
|
("get_radio_status", "WIFI_RADIO", "wireless.htm"),
|
|
],
|
|
)
|
|
def test_a_getter_raises_when_neither_the_dal_nor_the_page_can_be_read(getter, oid, page):
|
|
driver = _driver(
|
|
{f"cgi-bin/DAL?oid={oid}": requests.ReadTimeout("read timed out"), page: _response(500)}
|
|
)
|
|
with pytest.raises((ConnectionException, RuntimeError)):
|
|
getattr(driver, getter)()
|
|
|
|
|
|
def test_get_arp_table_raises_when_the_hosts_cannot_be_read():
|
|
driver = _driver({"cgi-bin/DAL?oid=lanhosts": _response(500), "dhcp.htm": _response(500)})
|
|
with pytest.raises(RuntimeError):
|
|
driver.get_arp_table()
|
|
|
|
|
|
def test_a_failed_dal_request_falls_back_to_the_page():
|
|
driver = _driver(
|
|
{"cgi-bin/DAL?oid=lanhosts": _response(500), "dhcp.htm": _response(200, HOSTS_PAGE)}
|
|
)
|
|
assert [h["ip"] for h in driver.get_hosts()] == ["192.168.1.34"]
|
|
|
|
|
|
def test_the_dal_answer_is_used_when_there_is_one():
|
|
driver = _driver({"cgi-bin/DAL?oid=lanhosts": _response(200, json.dumps(HOSTS_DAL))})
|
|
assert [h["ip"] for h in driver.get_hosts()] == ["192.0.2.2", "192.0.2.3"]
|
|
|
|
|
|
def test_a_gateway_that_lists_no_hosts_has_none():
|
|
answer = {"result": "ZCFG_SUCCESS", "Object": [{"lanhosts": []}]}
|
|
driver = _driver({"cgi-bin/DAL?oid=lanhosts": _response(200, json.dumps(answer))})
|
|
assert driver.get_hosts() == []
|
|
|
|
|
|
def test_get_facts_raises_when_the_interfaces_cannot_be_read():
|
|
with pytest.raises(RuntimeError, match="cardpage_status"):
|
|
_driver({}).get_facts()
|