Files
napalm-zyxel/tests/test_failed_reads.py
T
Christian Manivong ec76c1d6e8
driver / standard (pull_request) Failing after 15s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 59s
driver / test (3.13) (pull_request) Successful in 52s
driver / test (3.12) (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 25s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 54s
CI / driver (pull_request) Failing after 2m1s
driver / publish (pull_request) Skipped
fix(interfaces): read interfaces and addresses from the gateway's status page
get_interfaces reported a fixed set: wan, lan and two Wi-Fi radios, all
up at 1000 Mbit/s, the LAN with the WAN's MAC. get_interfaces_ip gave
both a /24, the LAN's address being the hostname the driver connected
to. getBasicInformation carries none of WanIp, LanIp or MacAddress on a
VMG4005-B50A, a VDSL bridge without Wi-Fi whose LAN is a /29, and the
gateway showed all of the invented values.

Both now read the DAL's cardpage_status, which a GET answers sealed like
a PUT: the IP interfaces in WanLanInfo (br0, atm0.1, ptm0.2) with their
status, MAC and netmask, the Ethernet ports in LanInfo (eth1) with their
speed. A speed or MTU the gateway does not report is 0, unknown. IPv6
addresses are not read yet: no gateway seen so far had IPv6 on.
2026-11-12 16:14:25 +01:00

148 lines
5.6 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
HOSTS_DAL = {"hosts": [{"MACAddress": "AA:BB:CC:DD:EE:01", "IPAddress": "192.168.1.33"}]}
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", "LAN_HOSTS", "dhcp.htm"),
("get_port_forwards", "NAT_PORTMAP", "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=LAN_HOSTS": _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=LAN_HOSTS": _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=LAN_HOSTS": _response(200, json.dumps(HOSTS_DAL))})
assert [h["ip"] for h in driver.get_hosts()] == ["192.168.1.33"]
def test_a_gateway_that_lists_no_hosts_has_none():
driver = _driver({"cgi-bin/DAL?oid=LAN_HOSTS": _response(200, '{"hosts": []}')})
assert driver.get_hosts() == []
def test_get_facts_raises_when_the_interfaces_cannot_be_read():
driver = _driver({})
driver.get_interfaces = MagicMock(side_effect=RuntimeError("no interfaces"))
with pytest.raises(RuntimeError, match="no interfaces"):
driver.get_facts()