Files
napalm-hpe-aruba-procurve/tests/unit/test_connect_reasons.py
T
Christian Manivong 586632efe0 Merge remote-tracking branch 'origin/main' into fix/rest-cert-tofu-17
The REST login now checks the certificate before it posts the password
(#17) and then tells a web page from a refused login (#13); the two
login-answer checks moved into _require_login so connect() stays within
the function-length limit. #13's REST tests stand in for the switch's
certificate, since connect() fetches it before the login.
2026-11-02 00:37:11 +01:00

157 lines
5.6 KiB
Python

"""A failed connection names what the switch actually said (#13).
A switch whose Telnet sessions are all taken, a REST API that answers with the
web UI's HTML page, and an SSH key exchange that found no common algorithm were
all reported as a wrong password or a timeout, which sends the operator after
the credentials instead of the session table.
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import paramiko
import pytest
from napalm.base.exceptions import ConnectAuthError, ConnectionException
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
from napalm_procurve.api_client import ProcurveApiClient
from napalm_procurve.procurve import ProcurveDriver
HANDLER = "napalm_procurve.procurve.ConnectHandler"
PROBE = "napalm_procurve.procurve.ProcurveApiClient.probe"
FETCH_CERTIFICATE = "napalm_device_types.tls_certificates.fetch_certificate"
# What a ProCurve 2520G prints instead of a login prompt when every session is taken.
NO_FREE_SESSION = "Sorry, the maximum number of telnet sessions are active. Try again later.\r\n"
def _telnet_refused(greeting: str):
def connect(**kwargs):
if kwargs["device_type"] != ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET:
raise OSError("no route to host")
kwargs["session_log"].write(greeting)
raise NetmikoAuthenticationException(f"Login failed: {kwargs['host']}")
return connect
def _open(connect, **optional_args) -> ConnectionException:
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret", optional_args=optional_args)
with patch(PROBE, return_value=(None, None)), patch(HANDLER, side_effect=connect):
with pytest.raises(ConnectionException) as exc_info:
driver.open()
return exc_info.value
# --- Telnet -----------------------------------------------------------------
def test_no_free_telnet_session_is_a_connection_error_not_a_wrong_password():
error = _open(_telnet_refused(NO_FREE_SESSION))
msg = str(error)
assert "Authentication failed" not in msg
assert "telnet: the switch has no free session (maximum number of telnet sessions" in msg
def test_a_refused_telnet_login_is_still_an_authentication_failure():
error = _open(_telnet_refused("Password: \r\nInvalid password\r\n"))
assert "Authentication failed for 10.0.0.40 via telnet" in str(error)
def test_the_telnet_transcript_records_what_the_switch_sent_not_the_password():
sessions: list = []
def connect(**kwargs):
sessions.append(kwargs["session_log"])
return MagicMock()
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret", optional_args={"transport": "telnet"})
with patch(HANDLER, side_effect=connect):
driver.open()
assert sessions[0].record_writes is False
# --- SSH --------------------------------------------------------------------
def _wrapped(cause: Exception) -> NetmikoTimeoutException:
"""What netmiko raises: its own exception, the paramiko or socket error as context."""
exc = NetmikoTimeoutException("A paramiko SSHException occurred during connection creation")
exc.__context__ = cause
return exc
def test_an_ssh_key_exchange_failure_is_named_not_reported_as_a_timeout():
no_kex = paramiko.ssh_exception.IncompatiblePeer(
"Incompatible ssh peer (no acceptable kex algorithm)"
)
def connect(**kwargs):
if kwargs["device_type"] == ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET:
raise OSError("no route to host")
raise _wrapped(no_kex)
msg = str(_open(connect))
assert "ssh: Incompatible ssh peer (no acceptable kex algorithm)" in msg
assert "ssh: timed out" not in msg
def test_an_ssh_timeout_is_still_reported_as_one():
def connect(**kwargs):
if kwargs["device_type"] == ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET:
raise OSError("no route to host")
raise _wrapped(TimeoutError("timed out"))
assert "ssh: timed out" in str(_open(connect))
# --- REST -------------------------------------------------------------------
def _client_answering(status: int, content_type: str) -> ProcurveApiClient:
client = ProcurveApiClient("10.0.0.40", "manager", "s3cret")
client.setup("v7", "https")
response = MagicMock(status_code=status, headers={"Content-Type": content_type})
session = MagicMock()
session.post.return_value = response
session.headers = {}
with (
patch("napalm_procurve.api_client.requests.Session", return_value=session),
# The certificate is checked before the login (#17); this is the switch's own.
patch(FETCH_CERTIFICATE, return_value=b"the switch's certificate"),
):
client.connect()
return client
def test_a_web_page_instead_of_a_rest_answer_is_not_a_login_failure():
with pytest.raises(ConnectionException) as exc_info:
_client_answering(200, "text/html; charset=utf-8")
assert not isinstance(exc_info.value, ConnectAuthError)
assert str(exc_info.value) == (
"REST API on 10.0.0.40 answered with a web page instead of JSON (HTTP 200)"
)
def test_a_refused_rest_login_is_still_an_authentication_failure():
with pytest.raises(ConnectAuthError, match=r"REST API login failed \(HTTP 401\)"):
_client_answering(401, "application/json")
def test_the_transcript_keeps_the_greeting_not_the_whole_session():
from napalm_procurve.connect_reasons import TelnetTranscript
transcript = TelnetTranscript()
transcript.write(NO_FREE_SESSION)
for _ in range(1000):
transcript.write("show running-config output\r\n" * 10)
assert transcript.no_free_session
assert len(transcript.text) < 10_000