Debian Codegraph @

tests/units/asynceapi/test_device.py

raw symbols SCIP
1 # Copyright (c) 2023-2026 Arista Networks, Inc.
2 # Use of this source code is governed by the Apache License 2.0
3 # that can be found in the LICENSE file.
4 """Unit tests for the asynceapi.device module."""
5
6 from __future__ import annotations
7
8 import asyncio
9 from typing import TYPE_CHECKING
10 from unittest.mock import ANY, AsyncMock, patch
11
12 import pytest
13 import respx
14 from httpx import ConnectError, HTTPStatusError, Response
15
16 from asynceapi import Device, EapiCommandError
17 from asynceapi._constants import EapiCommandFormat
18 from asynceapi.errors import EapiAuthenticationError
19
20 from .test_data import ERROR_EAPI_RESPONSE, JSONRPC_REQUEST_TEMPLATE, SUCCESS_EAPI_RESPONSE
21
22 _HOST = "192.0.2.1"
23 _PASSWORD = "test1234"
24 _SESSION_COOKIE = "aabbccdd11223344"
25 _BASE_URL = f"https://{_HOST}"
26
27
28 if TYPE_CHECKING:
29 from pytest_httpx import HTTPXMock
30
31 from asynceapi._types import EapiComplexCommand, EapiSimpleCommand, JsonRpc
32
33
34 def _jsonrpc_request() -> JsonRpc:
35 """Return a fresh JSON-RPC request for session-auth tests."""
36 return {
37 "jsonrpc": "2.0",
38 "method": "runCmds",
39 "params": {"version": 1, "cmds": ["show version"], "format": EapiCommandFormat.JSON},
40 "id": "EapiExplorer-1",
41 }
42
43
44 def _jsonrpc_response() -> dict[str, object]:
45 """Return a JSON-RPC response for session-auth tests."""
46 return {
47 "jsonrpc": "2.0",
48 "id": "EapiExplorer-1",
49 "result": [{"modelName": "pytest"}],
50 }
51
52
53 @pytest.mark.parametrize(
54 "cmds",
55 [
56 (["show version", "show clock"]),
57 ([{"cmd": "show version"}, {"cmd": "show clock"}]),
58 ([{"cmd": "show version"}, "show clock"]),
59 ],
60 ids=["simple_commands", "complex_commands", "mixed_commands"],
61 )
62 async def test_jsonrpc_exec_success(
63 asynceapi_device: Device,
64 httpx_mock: HTTPXMock,
65 cmds: list[EapiSimpleCommand | EapiComplexCommand],
66 ) -> None:
67 """Test the Device.jsonrpc_exec method with a successful response. Simple and complex commands are tested."""
68 jsonrpc_request = JSONRPC_REQUEST_TEMPLATE.copy()
69 jsonrpc_request["params"]["cmds"] = cmds
70
71 httpx_mock.add_response(json=SUCCESS_EAPI_RESPONSE)
72
73 result = await asynceapi_device.jsonrpc_exec(jsonrpc=jsonrpc_request)
74
75 assert result == SUCCESS_EAPI_RESPONSE["result"]
76
77
78 @pytest.mark.parametrize(
79 "cmds",
80 [
81 (["show version", "bad command", "show clock"]),
82 ([{"cmd": "show version"}, {"cmd": "bad command"}, {"cmd": "show clock"}]),
83 ([{"cmd": "show version"}, {"cmd": "bad command"}, "show clock"]),
84 ],
85 ids=["simple_commands", "complex_commands", "mixed_commands"],
86 )
87 async def test_jsonrpc_exec_eapi_command_error(
88 asynceapi_device: Device,
89 httpx_mock: HTTPXMock,
90 cmds: list[EapiSimpleCommand | EapiComplexCommand],
91 ) -> None:
92 """Test the Device.jsonrpc_exec method with an error response. Simple and complex commands are tested."""
93 jsonrpc_request = JSONRPC_REQUEST_TEMPLATE.copy()
94 jsonrpc_request["params"]["cmds"] = cmds
95
96 httpx_mock.add_response(json=ERROR_EAPI_RESPONSE)
97
98 with pytest.raises(EapiCommandError) as exc_info:
99 await asynceapi_device.jsonrpc_exec(jsonrpc=jsonrpc_request)
100
101 assert exc_info.value.passed == [ERROR_EAPI_RESPONSE["error"]["data"][0]]
102 assert exc_info.value.failed == "bad command"
103 assert exc_info.value.errors == ["Invalid input (at token 1: 'bad')"]
104 assert exc_info.value.errmsg == "CLI command 2 of 3 'bad command' failed: invalid command"
105 assert exc_info.value.not_exec == [jsonrpc_request["params"]["cmds"][2]]
106
107
108 async def test_jsonrpc_exec_http_status_error(asynceapi_device: Device, httpx_mock: HTTPXMock) -> None:
109 """Test the Device.jsonrpc_exec method with an HTTPStatusError."""
110 jsonrpc_request = JSONRPC_REQUEST_TEMPLATE.copy()
111 jsonrpc_request["params"]["cmds"] = ["show version"]
112
113 httpx_mock.add_response(status_code=500, text="Internal Server Error")
114
115 with pytest.raises(HTTPStatusError):
116 await asynceapi_device.jsonrpc_exec(jsonrpc=jsonrpc_request)
117
118
119 async def test_jsonrpc_exec_session_auth_concurrent_first_use_single_login() -> None:
120 """Test concurrent session-auth requests share a single login and cookie."""
121 with respx.mock as respx_mock:
122 login_route = respx_mock.post(f"{_BASE_URL}/login").respond(status_code=200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"})
123 command_route = respx_mock.post(f"{_BASE_URL}/command-api").respond(json=_jsonrpc_response())
124 logout_route = respx_mock.post(f"{_BASE_URL}/logout").respond(status_code=200)
125
126 device = Device(host=_HOST, username="admin", password=_PASSWORD, use_session_auth=True)
127 try:
128 await asyncio.gather(*(device.jsonrpc_exec(jsonrpc=_jsonrpc_request()) for _ in range(5)))
129 finally:
130 await device.aclose()
131
132 assert login_route.call_count == 1
133 assert command_route.call_count == 5
134 assert logout_route.call_count == 1
135 assert all(call.request.headers.get("cookie") == f"Session={_SESSION_COOKIE}" for call in command_route.calls)
136
137
138 async def test_jsonrpc_exec_session_auth_command_401_does_not_relogin() -> None:
139 """Test an expired session cookie raises and does not trigger a second login."""
140 with respx.mock(assert_all_called=False) as respx_mock:
141 login_route = respx_mock.post(f"{_BASE_URL}/login").respond(status_code=200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"})
142 command_route = respx_mock.post(f"{_BASE_URL}/command-api").mock(side_effect=[Response(200, json=_jsonrpc_response()), Response(401)])
143 logout_route = respx_mock.post(f"{_BASE_URL}/logout").respond(status_code=200)
144
145 device = Device(host=_HOST, username="admin", password=_PASSWORD, use_session_auth=True)
146 try:
147 await device.jsonrpc_exec(jsonrpc=_jsonrpc_request())
148 with pytest.raises(EapiAuthenticationError):
149 await device.jsonrpc_exec(jsonrpc=_jsonrpc_request())
150 finally:
151 await device.aclose()
152
153 assert login_route.call_count == 1
154 assert command_route.call_count == 2
155 # The 401 clears session_cookie → logged_in is False → So logout() is a no-op
156 assert logout_route.call_count == 0
157
158
159 async def test_aclose_calls_logout_when_session_enabled() -> None:
160 """Test that aclose() calls logout() exactly once when use_session_auth=True."""
161 device = Device(host="localhost", username="admin", password=_PASSWORD, use_session_auth=True)
162 with patch.object(device, "logout", new_callable=AsyncMock) as mock_logout:
163 await device.aclose()
164 mock_logout.assert_called_once()
165
166
167 async def test_aclose_skips_logout_when_session_disabled() -> None:
168 """Test that aclose() never calls logout() when use_session_auth=False."""
169 device = Device(host="localhost", username="admin", password=_PASSWORD, use_session_auth=False)
170 with patch.object(device, "logout", new_callable=AsyncMock) as mock_logout:
171 await device.aclose()
172 mock_logout.assert_not_called()
173
174
175 async def test_device_session_logout_sends_cookie_and_resets_state() -> None:
176 """Test that logout() POSTs /logout with the session cookie and resets session state."""
177 with respx.mock as respx_mock:
178 respx_mock.post(f"{_BASE_URL}/login").respond(status_code=200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"})
179 respx_mock.post(f"{_BASE_URL}/command-api").respond(json=_jsonrpc_response())
180 logout_route = respx_mock.post(f"{_BASE_URL}/logout").respond(status_code=200)
181
182 device = Device(host=_HOST, username="admin", password=_PASSWORD, use_session_auth=True)
183 await device.jsonrpc_exec(jsonrpc=_jsonrpc_request())
184
185 assert device._session_auth is not None
186 assert device._session_auth.logged_in is True
187
188 await device.aclose()
189
190 assert logout_route.called
191 assert logout_route.calls[0].request.headers.get("cookie") == f"Session={_SESSION_COOKIE}"
192 assert device._session_auth.logged_in is False
193 assert device._session_auth.session_cookie is None
194
195
196 async def test_device_session_context_manager_exit_triggers_logout() -> None:
197 """Test that context-manager exit triggers logout and resets session state."""
198 with respx.mock as respx_mock:
199 respx_mock.post(f"{_BASE_URL}/login").respond(status_code=200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"})
200 respx_mock.post(f"{_BASE_URL}/command-api").respond(json=_jsonrpc_response())
201 logout_route = respx_mock.post(f"{_BASE_URL}/logout").respond(status_code=200)
202
203 async with Device(host=_HOST, username="admin", password=_PASSWORD, use_session_auth=True) as device:
204 await device.jsonrpc_exec(jsonrpc=_jsonrpc_request())
205
206 assert logout_route.called
207 assert logout_route.calls[0].request.headers.get("cookie") == f"Session={_SESSION_COOKIE}"
208 assert device._session_auth is not None
209 assert device._session_auth.logged_in is False
210 assert device._session_auth.session_cookie is None
211
212
213 @pytest.mark.parametrize(
214 ("username", "password"),
215 [
216 (None, None),
217 ("admin", None),
218 (None, _PASSWORD),
219 ],
220 ids=["no_credentials", "username_only", "password_only"],
221 )
222 def test_device_init_session_raises_without_credentials(username: str | None, password: str | None) -> None:
223 """Test that Device raises ValueError when use_session_auth=True but credentials are incomplete."""
224 with pytest.raises(ValueError, match="username and password are required"):
225 Device(host=_HOST, username=username, password=password, use_session_auth=True)
226
227
228 def test_device_init_session_raises_without_host() -> None:
229 """Test that Device raises ValueError when use_session_auth=True but host is not provided."""
230 with pytest.raises(ValueError, match="host is required"):
231 Device(host=None, username="admin", password=_PASSWORD, use_session_auth=True)
232
233
234 async def test_logout_noop_when_session_auth_is_none() -> None:
235 """Test that logout() is a no-op when the device is not using session auth."""
236 device = Device(host=_HOST, username="admin", password=_PASSWORD, use_session_auth=False)
237 await device.logout()
238 assert device._session_auth is None
239
240
241 async def test_logout_noop_when_not_logged_in() -> None:
242 """Test that logout() is a no-op when session auth exists but no login has occurred yet."""
243 device = Device(host=_HOST, username="admin", password=_PASSWORD, use_session_auth=True)
244 assert device._session_auth is not None
245 await device.logout()
246 assert device._session_auth.logged_in is False
247
248
249 async def test_logout_warns_on_http_error() -> None:
250 """Test that logout() logs a warning and still resets state when the POST raises an HTTPError."""
251 with respx.mock as respx_mock:
252 respx_mock.post(f"{_BASE_URL}/login").respond(status_code=200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"})
253 respx_mock.post(f"{_BASE_URL}/command-api").respond(json=_jsonrpc_response())
254 respx_mock.post(f"{_BASE_URL}/logout").mock(side_effect=ConnectError("connection refused"))
255
256 device = Device(host=_HOST, username="admin", password=_PASSWORD, use_session_auth=True)
257 await device.jsonrpc_exec(jsonrpc=_jsonrpc_request())
258
259 with patch("asynceapi.device.LOGGER.warning") as mock_warn:
260 await device.logout()
261
262 mock_warn.assert_called_once_with("Logout HTTP error for %s: %s", _HOST, ANY)
263 assert device._session_auth is not None
264 assert device._session_auth.logged_in is False
265
266
267 async def test_logout_resets_state_on_non_success_response() -> None:
268 """Test that logout() silently resets state when the server returns a non-2xx status."""
269 with respx.mock as respx_mock:
270 respx_mock.post(f"{_BASE_URL}/login").respond(status_code=200, headers={"Set-Cookie": f"Session={_SESSION_COOKIE}; Path=/"})
271 respx_mock.post(f"{_BASE_URL}/command-api").respond(json=_jsonrpc_response())
272 respx_mock.post(f"{_BASE_URL}/logout").respond(status_code=503, text="Service Unavailable")
273
274 device = Device(host=_HOST, username="admin", password=_PASSWORD, use_session_auth=True)
275 await device.jsonrpc_exec(jsonrpc=_jsonrpc_request())
276 await device.logout()
277
278 assert device._session_auth is not None
279 assert device._session_auth.logged_in is False