Files
napalm-zyxel/tests/test_facts.py
T
Christian Manivong b6668eddbd
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m5s
driver / test (3.13) (pull_request) Successful in 1m10s
driver / test (3.12) (pull_request) Successful in 1m12s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 31s
driver / security (pull_request) Successful in 1m5s
CI / driver (pull_request) Successful in 2m35s
driver / publish (pull_request) Skipped
test(facts): check get_facts against the gateway's recorded answers (#24)
get_facts read SerialNumber, HostName, SystemUpTime and MacAddress
from getBasicInformation, which a VMG4005-B50A (V5.17(ABQA.3.1)C0)
answers with model, firmware and language settings only. The code
was fixed by #26 (host name and domain from the System page) and #28
(serial number and uptime from cardpage_status); the tests still fed
it an invented getBasicInformation (MOCK_BASIC_INFO) that carried
those fields, with an invented serial number and firmware.

MOCK_BASIC_INFO is now the recorded answer, and a new test reads the
facts from the recorded, sealed status page and the System page: it
fails against the driver before #26 with the symptoms of this issue
(serial "", uptime 0, host name the connection address). The README
names the sources get_facts reads.

Closes #24
2026-11-12 19:06:53 +01:00

204 lines
7.1 KiB
Python

"""The gateway's host name comes from its System page.
``get_facts`` read ``HostName`` from ``getBasicInformation``, which a VMG4005-B50A
(V5.17(ABQA.3.1)C0) does not send, and fell back to the address the driver connects
to: netOrk kept the device named ``192.168.1.1``. The gateway's own Maintenance >
System page reads the name with ``GET /cgi-bin/System?oid=snmp``, sealed like a DAL
answer; the driver now reads it there too.
Serial number and uptime are not in ``getBasicInformation`` either; they come from
``DeviceInfo`` in the DAL's ``cardpage_status``, the answer the interfaces are read
from (#27).
``BASIC_INFO`` and ``SYSTEM`` are those two answers from that gateway (the SNMP
community strings the System answer can carry are left out), ``STATUS`` its
``cardpage_status`` cut down to ``DeviceInfo`` and one interface, with the serial
number replaced by a placeholder.
"""
from __future__ import annotations
import json
from typing import Any
from unittest.mock import MagicMock
import pytest
import requests
from napalm_zyxel import ZyxelVMGDriver
from tests import gateway
BASIC_INFO: dict[str, Any] = {
"result": "ZCFG_SUCCESS",
"ModelName": "VMG4005-B50A",
"SoftwareVersion": "V5.17(ABQA.3.1)C0",
"CurrentLanguage": "de",
"AvailableLanguages": "en,cz,it,nl,pt,ru,tr,fr,de,es",
"RememberPassword": 0,
"FWUpgradeProgressST": 0,
}
SYSTEM: list[dict[str, Any]] = [
{"HostName": "VMG4005-B50A", "DomainName": "home", "Location": "Taiwan", "Contact": ""}
]
STATUS: dict[str, Any] = {
"result": "ZCFG_SUCCESS",
"Object": [
{
"DeviceInfo": {
"ModelName": "VMG4005-B50A",
"SerialNumber": "S000Y00000001",
"SoftwareVersion": "V5.17(ABQA.3.1)C0",
"UpTime": 13544274,
},
"WanLanInfo": [{"X_ZYXEL_IfName": "br0", "Name": "LAN", "Status": "Up"}],
"LanInfo": [],
}
],
}
SYSTEM_PATH = "cgi-bin/System?oid=snmp"
STATUS_PATH = "cgi-bin/DAL?oid=cardpage_status"
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(system: Any = SYSTEM, status: Any = STATUS) -> ZyxelVMGDriver:
"""A logged-in driver whose gateway answers the System page with *system* and
``cardpage_status`` with *status*, each sealed the way the gateway sends it, or
with the answer itself when it is a response."""
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]
answers = {SYSTEM_PATH: system, STATUS_PATH: status}
def get(url: str, params: dict[str, Any] | None = None, **_: Any) -> requests.Response:
for path, answer in answers.items():
if url.endswith(path):
if isinstance(answer, requests.Response):
return answer
return _response(200, json.dumps({"content": path, "iv": "IV"}))
return _response(404)
def decrypt(data: dict[str, Any]) -> Any:
if data.get("content") not in answers:
pytest.fail(f"decrypted {data!r}")
return answers[data["content"]]
session = MagicMock(spec=requests.Session)
session.get.side_effect = get
driver._session = session
driver._sessionkey = "1"
driver._crypto = MagicMock()
driver._crypto.decrypt_response.side_effect = decrypt
driver._device_info = BASIC_INFO
return driver
def _status_reads(driver: ZyxelVMGDriver) -> int:
return sum(
call.args[0].endswith(STATUS_PATH)
for call in driver._session.get.call_args_list # type: ignore[union-attr]
)
def test_the_host_name_is_the_one_on_the_system_page():
assert _driver().get_facts()["hostname"] == "VMG4005-B50A"
def test_the_fqdn_joins_the_host_name_and_the_domain():
assert _driver().get_facts()["fqdn"] == "VMG4005-B50A.home"
def test_without_a_domain_the_fqdn_is_the_host_name():
facts = _driver(system=[{**SYSTEM[0], "DomainName": ""}]).get_facts()
assert facts["fqdn"] == "VMG4005-B50A"
def test_a_gateway_without_a_name_reports_none_not_its_address():
facts = _driver(system=[{**SYSTEM[0], "HostName": "", "DomainName": ""}]).get_facts()
assert (facts["hostname"], facts["fqdn"]) == ("", "")
def test_the_page_is_also_read_unsealed():
facts = _driver(system=_response(200, json.dumps(SYSTEM))).get_facts()
assert facts["hostname"] == "VMG4005-B50A"
def test_get_facts_raises_when_the_system_page_cannot_be_read():
with pytest.raises(RuntimeError, match="System"):
_driver(system=_response(500)).get_facts()
@pytest.mark.parametrize("answer", [[], {"result": "ZCFG_SUCCESS"}, ["VMG4005-B50A"]])
def test_get_facts_raises_on_a_system_page_it_cannot_read(answer: Any):
with pytest.raises(RuntimeError, match="System"):
_driver(system=_response(200, json.dumps(answer))).get_facts()
# --- serial number and uptime (#27) ---------------------------------------------------
def test_the_serial_number_is_the_one_on_the_status_page():
assert _driver().get_facts()["serial_number"] == "S000Y00000001"
def test_the_uptime_is_the_one_on_the_status_page():
assert _driver().get_facts()["uptime"] == 13544274
def test_model_and_firmware_still_come_from_the_basic_information():
facts = _driver().get_facts()
assert (facts["model"], facts["os_version"]) == ("VMG4005-B50A", "V5.17(ABQA.3.1)C0")
def test_a_status_page_without_device_info_reports_them_unknown():
status = {"result": "ZCFG_SUCCESS", "Object": [{"WanLanInfo": [], "LanInfo": []}]}
facts = _driver(status=status).get_facts()
assert (facts["serial_number"], facts["uptime"]) == ("", 0)
def test_get_facts_reads_the_status_page_once():
driver = _driver()
facts = driver.get_facts()
assert facts["interface_list"] == ["br0"]
assert _status_reads(driver) == 1
def test_get_facts_raises_when_the_status_page_cannot_be_read():
with pytest.raises(RuntimeError, match="cardpage_status"):
_driver(status=_response(500)).get_facts()
# --- the recorded answers (#24) ---------------------------------------------------------
def test_the_facts_of_the_recorded_gateway():
"""``getBasicInformation`` gives model and firmware only; nothing else is read from
it. The status page is the full recorded one, sealed (``tests/gateway.py``)."""
drv = gateway.driver(
{gateway.dal("cardpage_status"): gateway.fixture("cardpage_status"), SYSTEM_PATH: SYSTEM}
)
assert drv._device_info == gateway.fixture("getBasicInformation")
assert drv.get_facts() == {
"vendor": "Zyxel",
"model": "VMG4005-B50A",
"serial_number": "S000Y00000001",
"os_version": "V5.17(ABQA.3.1)C0",
"hostname": "VMG4005-B50A",
"fqdn": "VMG4005-B50A.home",
"uptime": 13554213,
"interface_list": ["br0", "atm0.1", "ptm0.2", "eth1"],
}
def test_basic_information_is_the_recorded_answer():
assert BASIC_INFO == gateway.fixture("getBasicInformation")