Files
napalm-hpe-aruba-procurve/tests/unit/test_rest_failed_reads.py
T
Christian Manivong 6bd3372933
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 12s
driver / types (pull_request) Successful in 56s
driver / test (3.12) (pull_request) Successful in 53s
driver / test (3.13) (pull_request) Successful in 51s
driver / lowest (pull_request) Successful in 25s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 57s
CI / driver (pull_request) Successful in 2m16s
driver / publish (pull_request) Skipped
feat(time-sync): the switch's NTP servers and zone through TimeSyncMixin
netOrk aligns every device's NTP servers and time zone with its site's
(NetOrk/netork#2360, #2366). A ProCurve keeps them as configuration
lines: sntp server priority <1-3> (or ntp server lines when 16.x runs
timesync ntp), time timezone <minutes> and time daylight-time-rule.

get_time_sync() reads those lines from show running-config, over REST
through the /cli endpoint, and the zone as None: the switch keeps
minutes and a rule, no name. configure_time_sync() writes the servers
in the protocol the switch runs (SNTP unless it runs NTP, switching
TimeP to sntp unicast), keeping those already in place from the first
on; the zone as minutes and the switch's own US/EU rule, or user-defined
dates for other Sunday rules, from the zone's POSIX rule. What the switch
cannot take is refused before anything is sent: more than 3 SNTP or 8
NTP servers, host names, half an hour of summer time, a change on a
weekday. A change is saved with write memory; values already in place
are not sent again, so the alignment on every poll does not churn.

Over REST the writes need the CLI, so the temporary SSH session
configure_snmp_agent opened is now the _config_cli() context manager
both use. get_ntp_servers() reads through get_time_sync() on every
transport; it and get_ntp_stats() move to time_sync.py with the rest of
the clock, so procurve.py shrinks (1383 -> 1339 lines). The unused
parse_ntp_servers() and ProcurveApiClient.get_ntp_servers() are gone.
2026-11-11 15:25:06 +01:00

226 lines
7.9 KiB
Python

"""A failed REST read raises; it is not reported as an empty switch (#22).
``ProcurveApiClient.get()`` answered ``{}`` for a timeout, an expired session or an
HTTP 500, and every REST getter built its answer from that: a switch with no
hostname, no ports, no VLANs and no neighbours. A 404 is an empty answer only
where the getter expects the resource to be missing on some firmware.
"""
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_procurve.api_client import ProcurveApiClient
from napalm_procurve.procurve import ProcurveDriver
BASE = "https://10.0.0.40/rest/v7/"
def _response(status: int, body: Any = None, *, text: str | None = None) -> requests.Response:
resp = requests.Response()
resp.status_code = status
if text is not None:
resp._content = text.encode()
resp.headers["Content-Type"] = "text/html"
else:
resp._content = json.dumps({} if body is None else body).encode()
resp.headers["Content-Type"] = "application/json"
return resp
class FakeSession:
"""A REST session that answers each endpoint as told; 200 ``{}`` otherwise."""
def __init__(self, answers: dict[str, requests.Response | Exception]) -> None:
self.answers = answers
def _answer(self, url: str) -> requests.Response:
answer = self.answers.get(url.removeprefix(BASE), _response(200))
if isinstance(answer, Exception):
raise answer
return answer
def request(self, method: str, url: str, timeout: float, **kwargs: Any) -> requests.Response:
return self._answer(url)
def _client(answers: dict[str, requests.Response | Exception]) -> ProcurveApiClient:
client = ProcurveApiClient("10.0.0.40", "manager", "s3cret")
client.setup("v7", "https")
client._session = FakeSession(answers) # type: ignore[assignment]
return client
def _rest_driver(answers: dict[str, requests.Response | Exception]) -> ProcurveDriver:
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
driver._transport = "api"
driver._api = _client(answers)
return driver
PORTS = {"port_element": [{"id": "1", "name": "uplink", "is_port_up": True}]}
# --- get() -------------------------------------------------------------------
def test_get_returns_the_parsed_answer():
assert _client({"ports": _response(200, PORTS)}).get("ports") == PORTS
def test_get_raises_on_a_server_error():
with pytest.raises(RuntimeError, match="HTTP 500"):
_client({"ports": _response(500)}).get("ports")
@pytest.mark.parametrize("status", [401, 403])
def test_get_raises_connection_exception_for_a_refused_session(status):
with pytest.raises(ConnectionException, match=f"HTTP {status}"):
_client({"ports": _response(status)}).get("ports")
def test_get_raises_connection_exception_when_the_switch_does_not_answer():
timeout = requests.exceptions.ReadTimeout("read timed out")
with pytest.raises(ConnectionException, match="read timed out"):
_client({"ports": timeout}).get("ports")
def test_get_raises_on_a_404_unless_the_caller_expects_one():
client = _client({"dns": _response(404)})
with pytest.raises(RuntimeError, match="HTTP 404"):
client.get("dns")
assert client.get("dns", missing_ok=True) == {}
def test_get_raises_on_an_answer_that_is_not_json():
with pytest.raises(RuntimeError, match="not JSON"):
_client({"ports": _response(200, text="<html>session timed out</html>")}).get("ports")
# --- the getters ---------------------------------------------------------------
def test_get_interfaces_raises_when_ports_answers_500():
with pytest.raises(RuntimeError, match="ports"):
_rest_driver({"ports": _response(500)}).get_interfaces()
@pytest.mark.parametrize(
("getter", "endpoint"),
[
("get_facts", "system/status"),
("get_interfaces", "port-statistics"),
("get_interfaces", "system/status/switch"),
("get_interfaces_ip", "vlans"),
("get_arp_table", "arp"),
("get_mac_address_table", "mac-table"),
("get_lldp_neighbors", "lldp/remote-device"),
("get_lldp_neighbors_detail", "lldp/remote-device"),
("get_vlans", "vlans"),
("get_vlans", "vlans-ports"),
("get_poe_status", "poe/ports"),
],
)
def test_a_getter_raises_when_its_read_fails(getter, endpoint):
with pytest.raises(RuntimeError, match="HTTP 500"):
getattr(_rest_driver({endpoint: _response(500)}), getter)()
def test_get_facts_falls_back_to_global_info_when_system_status_is_missing():
driver = _rest_driver(
{
"system/status": _response(404),
"system/status/global_info": _response(200, {"name": "stack-1"}),
}
)
assert driver.get_facts()["hostname"] == "stack-1"
def test_get_facts_without_a_dns_resource_has_no_domain():
driver = _rest_driver({"system/status": _response(200, {"name": "sw1"}), "dns": _response(404)})
facts = driver.get_facts()
assert (facts["hostname"], facts["fqdn"]) == ("sw1", "sw1")
def test_get_interfaces_without_port_statistics_reports_the_ports():
driver = _rest_driver({"ports": _response(200, PORTS), "port-statistics": _response(404)})
assert driver.get_interfaces()["1"]["speed"] == 0.0
def test_get_interfaces_ip_skips_a_vlan_without_an_ipv4_resource():
driver = _rest_driver(
{
"vlans": _response(200, {"vlan_element": [{"vlan_id": 1}, {"vlan_id": 10}]}),
"vlans/1/ipv4": _response(404),
"vlans/10/ipv4": _response(
200, {"ipv4_element": [{"address": "10.0.10.2", "mask": "255.255.255.0"}]}
),
}
)
assert driver.get_interfaces_ip() == {
"VLAN10": {"ipv4": {"10.0.10.2": {"prefix_length": 24}}, "ipv6": {}}
}
def test_get_poe_status_of_a_switch_without_poe_is_empty():
assert _rest_driver({"poe/ports": _response(404)}).get_poe_status() == {}
# --- get_config ----------------------------------------------------------------
def test_get_config_raises_when_neither_rest_nor_ssh_reads_it():
driver = _rest_driver({"running-config": _response(500)})
driver._ssh_connect = MagicMock(side_effect=OSError("connection refused"))
with pytest.raises(ConnectionException, match="connection refused"):
driver.get_config()
def test_get_config_reads_over_ssh_when_the_firmware_has_no_config_resource():
driver = _rest_driver({"running-config": _response(404)})
ssh = MagicMock(base_prompt="sw1")
ssh.send_command.return_value = "hostname sw1"
driver._ssh_connect = MagicMock(return_value=ssh)
assert driver.get_config()["running"] == "hostname sw1"
def test_get_config_over_rest_reads_running_and_startup():
running = requests.Response()
running.status_code, running._content = 200, b"hostname sw1"
startup = requests.Response()
startup.status_code, startup._content = 200, b"hostname sw0"
driver = _rest_driver({"running-config": running, "startup-config": startup})
assert driver.get_config() == {
"running": "hostname sw1",
"startup": "hostname sw0",
"candidate": "",
}
# --- cli() -----------------------------------------------------------------------
def test_cli_over_rest_raises_on_a_server_error():
with pytest.raises(RuntimeError, match="HTTP 500"):
_rest_driver({"cli": _response(500)}).cli(["show version"])
def test_cli_over_rest_raises_connection_exception_for_a_refused_session():
with pytest.raises(ConnectionException, match="HTTP 401"):
_rest_driver({"cli": _response(401)}).cli(["show version"])
def test_cli_over_rest_raises_connection_exception_when_the_switch_does_not_answer():
refused = requests.exceptions.ConnectionError("connection refused")
with pytest.raises(ConnectionException, match="connection refused"):
_rest_driver({"cli": refused}).cli(["show version"])