Files
napalm-hpe-aruba-procurve/tests/unit/test_rest_failed_reads.py
T
Christian Manivong e0ff997d1b
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 25s
driver / types (pull_request) Successful in 1m15s
driver / test (3.12) (pull_request) Successful in 1m8s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m9s
CI / driver (pull_request) Successful in 2m54s
driver / publish (pull_request) Skipped
fix(config): read what retrieve asks in the REST-to-SSH fallback
A switch whose REST API has no configuration is read over a temporary
SSH session. That path read the running config only, whatever retrieve
asked for, and returned an empty startup config. It now reads through
the same code as the SSH transport: running and/or startup as asked,
"show config" where "show startup-config" is unknown, and a part that
could not be read raises.

Closes #25
2026-11-02 09:15:03 +01:00

227 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_ntp_servers", "ntp/server"),
("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"])