| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""test anta.device.py.""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import asyncio |
| 9 |
import logging |
| 10 |
from contextlib import AbstractContextManager |
| 11 |
from contextlib import nullcontext as does_not_raise |
| 12 |
from pathlib import Path |
| 13 |
from typing import TYPE_CHECKING, Any |
| 14 |
from unittest.mock import AsyncMock, MagicMock, patch |
| 15 |
|
| 16 |
import pytest |
| 17 |
from asyncssh import SSHClientConnection, SSHClientConnectionOptions |
| 18 |
from httpx import ConnectError, ConnectTimeout, HTTPError, TimeoutException |
| 19 |
from rich import print as rprint |
| 20 |
|
| 21 |
from anta.device import AntaDevice, AntaDeviceCapabilities, AsyncEOSDevice |
| 22 |
from anta.models import AntaCommand |
| 23 |
from asynceapi import EapiCommandError |
| 24 |
from asynceapi._models import EAPIClientConnectionOptions |
| 25 |
from asynceapi.errors import EapiAuthenticationError |
| 26 |
from tests.units.conftest import COMMAND_OUTPUT |
| 27 |
|
| 28 |
if TYPE_CHECKING: |
| 29 |
from _pytest.mark.structures import ParameterSet |
| 30 |
|
| 31 |
INIT_PARAMS: list[ParameterSet] = [ |
| 32 |
pytest.param({"host": "42.42.42.42", "username": "anta", "password": "anta"}, {"name": "42.42.42.42"}, does_not_raise(), id="no name, no port"), |
| 33 |
pytest.param({"host": "42.42.42.42", "username": "anta", "password": "anta", "port": 666}, {"name": "42.42.42.42:666"}, does_not_raise(), id="no name, port"), |
| 34 |
pytest.param( |
| 35 |
{"host": "42.42.42.42", "username": "anta", "password": "anta", "name": "test.anta.ninja", "disable_cache": True}, |
| 36 |
{"name": "test.anta.ninja"}, |
| 37 |
does_not_raise(), |
| 38 |
id="name", |
| 39 |
), |
| 40 |
pytest.param( |
| 41 |
{"host": "42.42.42.42", "username": "anta", "password": "anta", "name": "test.anta.ninja", "insecure": True}, |
| 42 |
{"name": "test.anta.ninja"}, |
| 43 |
does_not_raise(), |
| 44 |
id="insecure", |
| 45 |
), |
| 46 |
pytest.param( |
| 47 |
{"host": None, "username": "anta", "password": "anta", "name": "test.anta.ninja"}, |
| 48 |
None, |
| 49 |
pytest.raises(ValueError, match=r"'host' is required to create an AsyncEOSDevice"), |
| 50 |
id="host is None", |
| 51 |
), |
| 52 |
pytest.param( |
| 53 |
{"host": "42.42.42.42", "username": None, "password": "anta", "name": "test.anta.ninja"}, |
| 54 |
None, |
| 55 |
pytest.raises(ValueError, match=r"'username' is required to instantiate device 'test.anta.ninja'"), |
| 56 |
id="username is None", |
| 57 |
), |
| 58 |
pytest.param( |
| 59 |
{"host": "42.42.42.42", "username": "anta", "password": None, "name": "test.anta.ninja"}, |
| 60 |
None, |
| 61 |
pytest.raises(ValueError, match=r"'password' is required to instantiate device 'test.anta.ninja'"), |
| 62 |
id="password is None", |
| 63 |
), |
| 64 |
] |
| 65 |
EQUALITY_PARAMS: list[ParameterSet] = [ |
| 66 |
pytest.param({"host": "42.42.42.42", "username": "anta", "password": "anta"}, {"host": "42.42.42.42", "username": "anta", "password": "blah"}, True, id="equal"), |
| 67 |
pytest.param( |
| 68 |
{"host": "42.42.42.42", "username": "anta", "password": "anta", "name": "device1"}, |
| 69 |
{"host": "42.42.42.42", "username": "plop", "password": "anta", "name": "device2"}, |
| 70 |
True, |
| 71 |
id="equals-name", |
| 72 |
), |
| 73 |
pytest.param( |
| 74 |
{"host": "42.42.42.42", "username": "anta", "password": "anta"}, |
| 75 |
{"host": "42.42.42.42", "username": "anta", "password": "anta", "port": 666}, |
| 76 |
False, |
| 77 |
id="not-equal-port", |
| 78 |
), |
| 79 |
pytest.param( |
| 80 |
{"host": "42.42.42.41", "username": "anta", "password": "anta"}, |
| 81 |
{"host": "42.42.42.42", "username": "anta", "password": "anta"}, |
| 82 |
False, |
| 83 |
id="not-equal-host", |
| 84 |
), |
| 85 |
] |
| 86 |
ASYNCEAPI_COLLECT_PARAMS: list[ParameterSet] = [ |
| 87 |
pytest.param( |
| 88 |
{}, |
| 89 |
{ |
| 90 |
"command": "show version", |
| 91 |
"patch_kwargs": { |
| 92 |
"return_value": [ |
| 93 |
{ |
| 94 |
"mfgName": "Arista", |
| 95 |
"modelName": "DCS-7280CR3-32P4-F", |
| 96 |
"hardwareRevision": "11.00", |
| 97 |
"serialNumber": "JPE19500066", |
| 98 |
"systemMacAddress": "fc:bd:67:3d:13:c5", |
| 99 |
"hwMacAddress": "fc:bd:67:3d:13:c5", |
| 100 |
"configMacAddress": "00:00:00:00:00:00", |
| 101 |
"version": "4.31.1F-34361447.fraserrel (engineering build)", |
| 102 |
"architecture": "x86_64", |
| 103 |
"internalVersion": "4.31.1F-34361447.fraserrel", |
| 104 |
"internalBuildId": "4940d112-a2fc-4970-8b5a-a16cd03fd08c", |
| 105 |
"imageFormatVersion": "3.0", |
| 106 |
"imageOptimization": "Default", |
| 107 |
"bootupTimestamp": 1700729434.5892005, |
| 108 |
"uptime": 20666.78, |
| 109 |
"memTotal": 8099732, |
| 110 |
"memFree": 4989568, |
| 111 |
"isIntlVersion": False, |
| 112 |
} |
| 113 |
] |
| 114 |
}, |
| 115 |
}, |
| 116 |
{ |
| 117 |
"output": { |
| 118 |
"mfgName": "Arista", |
| 119 |
"modelName": "DCS-7280CR3-32P4-F", |
| 120 |
"hardwareRevision": "11.00", |
| 121 |
"serialNumber": "JPE19500066", |
| 122 |
"systemMacAddress": "fc:bd:67:3d:13:c5", |
| 123 |
"hwMacAddress": "fc:bd:67:3d:13:c5", |
| 124 |
"configMacAddress": "00:00:00:00:00:00", |
| 125 |
"version": "4.31.1F-34361447.fraserrel (engineering build)", |
| 126 |
"architecture": "x86_64", |
| 127 |
"internalVersion": "4.31.1F-34361447.fraserrel", |
| 128 |
"internalBuildId": "4940d112-a2fc-4970-8b5a-a16cd03fd08c", |
| 129 |
"imageFormatVersion": "3.0", |
| 130 |
"imageOptimization": "Default", |
| 131 |
"bootupTimestamp": 1700729434.5892005, |
| 132 |
"uptime": 20666.78, |
| 133 |
"memTotal": 8099732, |
| 134 |
"memFree": 4989568, |
| 135 |
"isIntlVersion": False, |
| 136 |
}, |
| 137 |
"errors": [], |
| 138 |
}, |
| 139 |
id="command", |
| 140 |
), |
| 141 |
pytest.param( |
| 142 |
{"enable": True}, |
| 143 |
{ |
| 144 |
"command": "show version", |
| 145 |
"patch_kwargs": { |
| 146 |
"return_value": [ |
| 147 |
{}, |
| 148 |
{ |
| 149 |
"mfgName": "Arista", |
| 150 |
"modelName": "DCS-7280CR3-32P4-F", |
| 151 |
"hardwareRevision": "11.00", |
| 152 |
"serialNumber": "JPE19500066", |
| 153 |
"systemMacAddress": "fc:bd:67:3d:13:c5", |
| 154 |
"hwMacAddress": "fc:bd:67:3d:13:c5", |
| 155 |
"configMacAddress": "00:00:00:00:00:00", |
| 156 |
"version": "4.31.1F-34361447.fraserrel (engineering build)", |
| 157 |
"architecture": "x86_64", |
| 158 |
"internalVersion": "4.31.1F-34361447.fraserrel", |
| 159 |
"internalBuildId": "4940d112-a2fc-4970-8b5a-a16cd03fd08c", |
| 160 |
"imageFormatVersion": "3.0", |
| 161 |
"imageOptimization": "Default", |
| 162 |
"bootupTimestamp": 1700729434.5892005, |
| 163 |
"uptime": 20666.78, |
| 164 |
"memTotal": 8099732, |
| 165 |
"memFree": 4989568, |
| 166 |
"isIntlVersion": False, |
| 167 |
}, |
| 168 |
] |
| 169 |
}, |
| 170 |
}, |
| 171 |
{ |
| 172 |
"output": { |
| 173 |
"mfgName": "Arista", |
| 174 |
"modelName": "DCS-7280CR3-32P4-F", |
| 175 |
"hardwareRevision": "11.00", |
| 176 |
"serialNumber": "JPE19500066", |
| 177 |
"systemMacAddress": "fc:bd:67:3d:13:c5", |
| 178 |
"hwMacAddress": "fc:bd:67:3d:13:c5", |
| 179 |
"configMacAddress": "00:00:00:00:00:00", |
| 180 |
"version": "4.31.1F-34361447.fraserrel (engineering build)", |
| 181 |
"architecture": "x86_64", |
| 182 |
"internalVersion": "4.31.1F-34361447.fraserrel", |
| 183 |
"internalBuildId": "4940d112-a2fc-4970-8b5a-a16cd03fd08c", |
| 184 |
"imageFormatVersion": "3.0", |
| 185 |
"imageOptimization": "Default", |
| 186 |
"bootupTimestamp": 1700729434.5892005, |
| 187 |
"uptime": 20666.78, |
| 188 |
"memTotal": 8099732, |
| 189 |
"memFree": 4989568, |
| 190 |
"isIntlVersion": False, |
| 191 |
}, |
| 192 |
"errors": [], |
| 193 |
}, |
| 194 |
id="enable", |
| 195 |
), |
| 196 |
pytest.param( |
| 197 |
{"enable": True, "enable_password": "anta"}, |
| 198 |
{ |
| 199 |
"command": "show version", |
| 200 |
"patch_kwargs": { |
| 201 |
"return_value": [ |
| 202 |
{}, |
| 203 |
{ |
| 204 |
"mfgName": "Arista", |
| 205 |
"modelName": "DCS-7280CR3-32P4-F", |
| 206 |
"hardwareRevision": "11.00", |
| 207 |
"serialNumber": "JPE19500066", |
| 208 |
"systemMacAddress": "fc:bd:67:3d:13:c5", |
| 209 |
"hwMacAddress": "fc:bd:67:3d:13:c5", |
| 210 |
"configMacAddress": "00:00:00:00:00:00", |
| 211 |
"version": "4.31.1F-34361447.fraserrel (engineering build)", |
| 212 |
"architecture": "x86_64", |
| 213 |
"internalVersion": "4.31.1F-34361447.fraserrel", |
| 214 |
"internalBuildId": "4940d112-a2fc-4970-8b5a-a16cd03fd08c", |
| 215 |
"imageFormatVersion": "3.0", |
| 216 |
"imageOptimization": "Default", |
| 217 |
"bootupTimestamp": 1700729434.5892005, |
| 218 |
"uptime": 20666.78, |
| 219 |
"memTotal": 8099732, |
| 220 |
"memFree": 4989568, |
| 221 |
"isIntlVersion": False, |
| 222 |
}, |
| 223 |
] |
| 224 |
}, |
| 225 |
}, |
| 226 |
{ |
| 227 |
"output": { |
| 228 |
"mfgName": "Arista", |
| 229 |
"modelName": "DCS-7280CR3-32P4-F", |
| 230 |
"hardwareRevision": "11.00", |
| 231 |
"serialNumber": "JPE19500066", |
| 232 |
"systemMacAddress": "fc:bd:67:3d:13:c5", |
| 233 |
"hwMacAddress": "fc:bd:67:3d:13:c5", |
| 234 |
"configMacAddress": "00:00:00:00:00:00", |
| 235 |
"version": "4.31.1F-34361447.fraserrel (engineering build)", |
| 236 |
"architecture": "x86_64", |
| 237 |
"internalVersion": "4.31.1F-34361447.fraserrel", |
| 238 |
"internalBuildId": "4940d112-a2fc-4970-8b5a-a16cd03fd08c", |
| 239 |
"imageFormatVersion": "3.0", |
| 240 |
"imageOptimization": "Default", |
| 241 |
"bootupTimestamp": 1700729434.5892005, |
| 242 |
"uptime": 20666.78, |
| 243 |
"memTotal": 8099732, |
| 244 |
"memFree": 4989568, |
| 245 |
"isIntlVersion": False, |
| 246 |
}, |
| 247 |
"errors": [], |
| 248 |
}, |
| 249 |
id="enable password", |
| 250 |
), |
| 251 |
pytest.param( |
| 252 |
{}, |
| 253 |
{ |
| 254 |
"command": "show version", |
| 255 |
"revision": 3, |
| 256 |
"patch_kwargs": { |
| 257 |
"return_value": [ |
| 258 |
{}, |
| 259 |
{ |
| 260 |
"mfgName": "Arista", |
| 261 |
"modelName": "DCS-7280CR3-32P4-F", |
| 262 |
"hardwareRevision": "11.00", |
| 263 |
"serialNumber": "JPE19500066", |
| 264 |
"systemMacAddress": "fc:bd:67:3d:13:c5", |
| 265 |
"hwMacAddress": "fc:bd:67:3d:13:c5", |
| 266 |
"configMacAddress": "00:00:00:00:00:00", |
| 267 |
"version": "4.31.1F-34361447.fraserrel (engineering build)", |
| 268 |
"architecture": "x86_64", |
| 269 |
"internalVersion": "4.31.1F-34361447.fraserrel", |
| 270 |
"internalBuildId": "4940d112-a2fc-4970-8b5a-a16cd03fd08c", |
| 271 |
"imageFormatVersion": "3.0", |
| 272 |
"imageOptimization": "Default", |
| 273 |
"bootupTimestamp": 1700729434.5892005, |
| 274 |
"uptime": 20666.78, |
| 275 |
"memTotal": 8099732, |
| 276 |
"memFree": 4989568, |
| 277 |
"isIntlVersion": False, |
| 278 |
}, |
| 279 |
] |
| 280 |
}, |
| 281 |
}, |
| 282 |
{ |
| 283 |
"output": { |
| 284 |
"mfgName": "Arista", |
| 285 |
"modelName": "DCS-7280CR3-32P4-F", |
| 286 |
"hardwareRevision": "11.00", |
| 287 |
"serialNumber": "JPE19500066", |
| 288 |
"systemMacAddress": "fc:bd:67:3d:13:c5", |
| 289 |
"hwMacAddress": "fc:bd:67:3d:13:c5", |
| 290 |
"configMacAddress": "00:00:00:00:00:00", |
| 291 |
"version": "4.31.1F-34361447.fraserrel (engineering build)", |
| 292 |
"architecture": "x86_64", |
| 293 |
"internalVersion": "4.31.1F-34361447.fraserrel", |
| 294 |
"internalBuildId": "4940d112-a2fc-4970-8b5a-a16cd03fd08c", |
| 295 |
"imageFormatVersion": "3.0", |
| 296 |
"imageOptimization": "Default", |
| 297 |
"bootupTimestamp": 1700729434.5892005, |
| 298 |
"uptime": 20666.78, |
| 299 |
"memTotal": 8099732, |
| 300 |
"memFree": 4989568, |
| 301 |
"isIntlVersion": False, |
| 302 |
}, |
| 303 |
"errors": [], |
| 304 |
}, |
| 305 |
id="revision", |
| 306 |
), |
| 307 |
pytest.param( |
| 308 |
{}, |
| 309 |
{ |
| 310 |
"command": "show version", |
| 311 |
"patch_kwargs": { |
| 312 |
"side_effect": EapiCommandError( |
| 313 |
passed=[], |
| 314 |
failed="show version", |
| 315 |
errors=["Authorization denied for command 'show version'"], |
| 316 |
errmsg="Invalid command", |
| 317 |
not_exec=[], |
| 318 |
) |
| 319 |
}, |
| 320 |
}, |
| 321 |
{"output": None, "errors": ["Authorization denied for command 'show version'"]}, |
| 322 |
id="asynceapi.EapiCommandError - Authorization denied", |
| 323 |
), |
| 324 |
pytest.param( |
| 325 |
{}, |
| 326 |
{ |
| 327 |
"command": "show version", |
| 328 |
"patch_kwargs": { |
| 329 |
"side_effect": EapiCommandError( |
| 330 |
passed=[], |
| 331 |
failed="show version", |
| 332 |
errors=["not supported on this hardware platform"], |
| 333 |
errmsg="Invalid command", |
| 334 |
not_exec=[], |
| 335 |
) |
| 336 |
}, |
| 337 |
}, |
| 338 |
{"output": None, "errors": ["not supported on this hardware platform"]}, |
| 339 |
id="asynceapi.EapiCommandError - not supported", |
| 340 |
), |
| 341 |
pytest.param( |
| 342 |
{}, |
| 343 |
{ |
| 344 |
"command": "show version", |
| 345 |
"patch_kwargs": { |
| 346 |
"side_effect": EapiCommandError( |
| 347 |
passed=[], |
| 348 |
failed="show version", |
| 349 |
errors=["BGP inactive"], |
| 350 |
errmsg="Invalid command", |
| 351 |
not_exec=[], |
| 352 |
) |
| 353 |
}, |
| 354 |
}, |
| 355 |
{"output": None, "errors": ["BGP inactive"]}, |
| 356 |
id="asynceapi.EapiCommandError - known EOS error", |
| 357 |
), |
| 358 |
pytest.param( |
| 359 |
{}, |
| 360 |
{ |
| 361 |
"command": "show version", |
| 362 |
"patch_kwargs": { |
| 363 |
"side_effect": EapiCommandError( |
| 364 |
passed=[], |
| 365 |
failed="show version", |
| 366 |
errors=["Invalid input (privileged mode required)"], |
| 367 |
errmsg="Invalid command", |
| 368 |
not_exec=[], |
| 369 |
) |
| 370 |
}, |
| 371 |
}, |
| 372 |
{"output": None, "errors": ["Invalid input (privileged mode required)"]}, |
| 373 |
id="asynceapi.EapiCommandError - requires privileges", |
| 374 |
), |
| 375 |
pytest.param( |
| 376 |
{}, |
| 377 |
{ |
| 378 |
"command": "session peer-supervisor show file systems", |
| 379 |
"patch_kwargs": { |
| 380 |
"side_effect": EapiCommandError( |
| 381 |
passed=[], |
| 382 |
failed="session peer-supervisor show file systems", |
| 383 |
errors=[""], |
| 384 |
errmsg="CLI command 2 of 2 'session peer-supervisor show file systems' failed: could not run command", |
| 385 |
not_exec=[], |
| 386 |
) |
| 387 |
}, |
| 388 |
}, |
| 389 |
{"output": None, "errors": ["could not run command"]}, |
| 390 |
id="asynceapi.EapiCommandError - empty error list", |
| 391 |
), |
| 392 |
pytest.param( |
| 393 |
{}, |
| 394 |
{"command": "show version", "patch_kwargs": {"side_effect": HTTPError("404")}}, |
| 395 |
{"output": None, "errors": ["HTTPError: 404"]}, |
| 396 |
id="httpx.HTTPError", |
| 397 |
), |
| 398 |
pytest.param( |
| 399 |
{}, |
| 400 |
{"command": "show version", "patch_kwargs": {"side_effect": ConnectError("Cannot open port")}}, |
| 401 |
{"output": None, "errors": ["ConnectError: Cannot open port"]}, |
| 402 |
id="httpx.ConnectError", |
| 403 |
), |
| 404 |
pytest.param( |
| 405 |
{}, |
| 406 |
{"command": "show version", "patch_kwargs": {"side_effect": TimeoutException("Test")}}, |
| 407 |
{"output": None, "errors": ["TimeoutException: Test"]}, |
| 408 |
id="httpx.TimeoutException", |
| 409 |
), |
| 410 |
pytest.param( |
| 411 |
{}, |
| 412 |
{"command": "show version", "patch_kwargs": {"side_effect": EapiAuthenticationError("42.42.42.42")}}, |
| 413 |
{"output": None, "errors": ["EapiAuthenticationError: Authentication failed for '42.42.42.42' (HTTP 401)."]}, |
| 414 |
id="asynceapi.EapiAuthenticationError", |
| 415 |
), |
| 416 |
pytest.param( |
| 417 |
{}, |
| 418 |
{"command": "show version", "patch_kwargs": {"side_effect": EapiAuthenticationError("42.42.42.42", session_expired=True)}}, |
| 419 |
{ |
| 420 |
"output": None, |
| 421 |
"errors": ["EapiAuthenticationError: Session cookie expired. Consider increasing 'session timeout' under 'management api http-commands' on the device."], |
| 422 |
}, |
| 423 |
id="asynceapi.EapiAuthenticationError.session_expired", |
| 424 |
), |
| 425 |
] |
| 426 |
ASYNCEAPI_COPY_PARAMS: list[ParameterSet] = [ |
| 427 |
pytest.param({}, {"sources": [Path("/mnt/flash"), Path("/var/log/agents")], "destination": Path(), "direction": "from"}, id="from"), |
| 428 |
pytest.param({}, {"sources": [Path("/mnt/flash"), Path("/var/log/agents")], "destination": Path(), "direction": "to"}, id="to"), |
| 429 |
pytest.param({}, {"sources": [Path("/mnt/flash"), Path("/var/log/agents")], "destination": Path(), "direction": "wrong"}, id="wrong"), |
| 430 |
] |
| 431 |
REFRESH_PARAMS: list[ParameterSet] = [ |
| 432 |
pytest.param( |
| 433 |
{}, |
| 434 |
( |
| 435 |
{"return_value": True}, |
| 436 |
{ |
| 437 |
"return_value": [ |
| 438 |
{ |
| 439 |
"mfgName": "Arista", |
| 440 |
"modelName": "DCS-7280CR3-32P4-F", |
| 441 |
"hardwareRevision": "11.00", |
| 442 |
"serialNumber": "JPE19500066", |
| 443 |
"systemMacAddress": "fc:bd:67:3d:13:c5", |
| 444 |
"hwMacAddress": "fc:bd:67:3d:13:c5", |
| 445 |
"configMacAddress": "00:00:00:00:00:00", |
| 446 |
"version": "4.31.1F-34361447.fraserrel (engineering build)", |
| 447 |
"architecture": "x86_64", |
| 448 |
"internalVersion": "4.31.1F-34361447.fraserrel", |
| 449 |
"internalBuildId": "4940d112-a2fc-4970-8b5a-a16cd03fd08c", |
| 450 |
"imageFormatVersion": "3.0", |
| 451 |
"imageOptimization": "Default", |
| 452 |
"bootupTimestamp": 1700729434.5892005, |
| 453 |
"uptime": 20666.78, |
| 454 |
"memTotal": 8099732, |
| 455 |
"memFree": 4989568, |
| 456 |
"isIntlVersion": False, |
| 457 |
} |
| 458 |
] |
| 459 |
}, |
| 460 |
), |
| 461 |
{"is_online": True, "established": True, "hw_model": "DCS-7280CR3-32P4-F"}, |
| 462 |
id="established", |
| 463 |
), |
| 464 |
pytest.param( |
| 465 |
{}, |
| 466 |
( |
| 467 |
{"side_effect": HTTPError(message="Unauthorized")}, |
| 468 |
{}, |
| 469 |
), |
| 470 |
{"is_online": False, "established": False, "hw_model": None}, |
| 471 |
id="is not online - HTTPError", |
| 472 |
), |
| 473 |
pytest.param( |
| 474 |
{}, |
| 475 |
( |
| 476 |
{"side_effect": EapiAuthenticationError("42.42.42.42", response_text="Bad username/password combination")}, |
| 477 |
{}, |
| 478 |
), |
| 479 |
{"is_online": False, "established": False, "hw_model": None}, |
| 480 |
id="is not online - EapiAuthenticationError", |
| 481 |
), |
| 482 |
pytest.param( |
| 483 |
{}, |
| 484 |
( |
| 485 |
{"return_value": True}, |
| 486 |
{ |
| 487 |
"return_value": [ |
| 488 |
{ |
| 489 |
"mfgName": "Arista", |
| 490 |
"hardwareRevision": "11.00", |
| 491 |
"serialNumber": "JPE19500066", |
| 492 |
"systemMacAddress": "fc:bd:67:3d:13:c5", |
| 493 |
"hwMacAddress": "fc:bd:67:3d:13:c5", |
| 494 |
"configMacAddress": "00:00:00:00:00:00", |
| 495 |
"version": "4.31.1F-34361447.fraserrel (engineering build)", |
| 496 |
"architecture": "x86_64", |
| 497 |
"internalVersion": "4.31.1F-34361447.fraserrel", |
| 498 |
"internalBuildId": "4940d112-a2fc-4970-8b5a-a16cd03fd08c", |
| 499 |
"imageFormatVersion": "3.0", |
| 500 |
"imageOptimization": "Default", |
| 501 |
"bootupTimestamp": 1700729434.5892005, |
| 502 |
"uptime": 20666.78, |
| 503 |
"memTotal": 8099732, |
| 504 |
"memFree": 4989568, |
| 505 |
"isIntlVersion": False, |
| 506 |
} |
| 507 |
] |
| 508 |
}, |
| 509 |
), |
| 510 |
{"is_online": True, "established": False, "hw_model": None}, |
| 511 |
id="cannot parse command", |
| 512 |
), |
| 513 |
pytest.param( |
| 514 |
{}, |
| 515 |
( |
| 516 |
{"return_value": True}, |
| 517 |
{ |
| 518 |
"side_effect": EapiCommandError( |
| 519 |
passed=[], |
| 520 |
failed="show version", |
| 521 |
errors=["Authorization denied for command 'show version'"], |
| 522 |
errmsg="Invalid command", |
| 523 |
not_exec=[], |
| 524 |
) |
| 525 |
}, |
| 526 |
), |
| 527 |
{"is_online": True, "established": False, "hw_model": None}, |
| 528 |
id="asynceapi.EapiCommandError", |
| 529 |
), |
| 530 |
pytest.param( |
| 531 |
{}, |
| 532 |
({"return_value": True}, {"side_effect": HTTPError("404")}), |
| 533 |
{"is_online": True, "established": False, "hw_model": None}, |
| 534 |
id="httpx.HTTPError", |
| 535 |
), |
| 536 |
pytest.param( |
| 537 |
{}, |
| 538 |
({"return_value": True}, {"side_effect": ConnectError("Cannot open port")}), |
| 539 |
{"is_online": True, "established": False, "hw_model": None}, |
| 540 |
id="httpx.ConnectError", |
| 541 |
), |
| 542 |
pytest.param( |
| 543 |
{}, |
| 544 |
( |
| 545 |
{"return_value": True}, |
| 546 |
{ |
| 547 |
"return_value": [ |
| 548 |
{ |
| 549 |
"mfgName": "Arista", |
| 550 |
"modelName": "", |
| 551 |
} |
| 552 |
] |
| 553 |
}, |
| 554 |
), |
| 555 |
{"is_online": True, "established": False, "hw_model": ""}, |
| 556 |
id="modelName empty string", |
| 557 |
), |
| 558 |
] |
| 559 |
COLLECT_PARAMS: list[ParameterSet] = [ |
| 560 |
pytest.param( |
| 561 |
{"disable_cache": False}, |
| 562 |
{"command": "show version", "use_cache": True}, |
| 563 |
{"cache_hit": False}, |
| 564 |
id="device cache enabled, command cache enabled, no cache hit", |
| 565 |
), |
| 566 |
pytest.param( |
| 567 |
{"disable_cache": False}, |
| 568 |
{"command": "show version", "use_cache": True}, |
| 569 |
{"cache_hit": True}, |
| 570 |
id="device cache enabled, command cache enabled, cache hit", |
| 571 |
), |
| 572 |
pytest.param({"disable_cache": True}, {"command": "show version", "use_cache": True}, {}, id="device cache disabled, command cache enabled"), |
| 573 |
pytest.param( |
| 574 |
{"disable_cache": False}, |
| 575 |
{"command": "show version", "use_cache": False}, |
| 576 |
{"cache_hit": True}, |
| 577 |
id="device cache enabled, command cache disabled, cache has command", |
| 578 |
), |
| 579 |
pytest.param( |
| 580 |
{"disable_cache": False}, |
| 581 |
{"command": "show version", "use_cache": False}, |
| 582 |
{"cache_hit": False}, |
| 583 |
id="device cache enabled, command cache disabled, cache does not have data", |
| 584 |
), |
| 585 |
pytest.param({"disable_cache": True}, {"command": "show version", "use_cache": False}, {}, id="device cache disabled, command cache disabled"), |
| 586 |
] |
| 587 |
CACHE_STATS_PARAMS: list[ParameterSet] = [ |
| 588 |
pytest.param({"disable_cache": False}, {"total_commands_sent": 0, "cache_hits": 0, "cache_hit_ratio": "0.00%"}, id="with_cache"), |
| 589 |
pytest.param({"disable_cache": True}, None, id="without_cache"), |
| 590 |
] |
| 591 |
|
| 592 |
|
| 593 |
class TestAntaDevice: |
| 594 |
"""Test for anta.device.AntaDevice Abstract class.""" |
| 595 |
|
| 596 |
@pytest.mark.parametrize(("device", "command", "expected"), COLLECT_PARAMS, indirect=["device"]) |
| 597 |
async def test_collect(self, device: AntaDevice, command: dict[str, Any], expected: dict[str, Any]) -> None: |
| 598 |
"""Test AntaDevice.collect behavior.""" |
| 599 |
cmd = AntaCommand(command=command["command"], use_cache=command["use_cache"]) |
| 600 |
|
| 601 |
|
| 602 |
cached_output = "cached_value" |
| 603 |
|
| 604 |
if device.cache is not None and expected["cache_hit"] is True: |
| 605 |
await device.cache.set(cmd.uid, cached_output) |
| 606 |
|
| 607 |
await device.collect(cmd) |
| 608 |
|
| 609 |
if device.cache is not None: |
| 610 |
current_cached_data = await device.cache.get(cmd.uid) |
| 611 |
if cmd.use_cache is True: |
| 612 |
if expected["cache_hit"] is True: |
| 613 |
assert cmd.output == cached_output |
| 614 |
assert current_cached_data == cached_output |
| 615 |
assert device.cache.stats["hits"] == 2 |
| 616 |
else: |
| 617 |
assert cmd.output == COMMAND_OUTPUT |
| 618 |
assert current_cached_data == COMMAND_OUTPUT |
| 619 |
assert device.cache.stats["hits"] == 1 |
| 620 |
else: |
| 621 |
device._collect.assert_called_once_with(command=cmd, collection_id=None) |
| 622 |
assert cmd.output == COMMAND_OUTPUT |
| 623 |
if expected["cache_hit"] is True: |
| 624 |
assert current_cached_data == cached_output |
| 625 |
else: |
| 626 |
assert current_cached_data is None |
| 627 |
else: |
| 628 |
assert device.cache is None |
| 629 |
device._collect.assert_called_once_with(command=cmd, collection_id=None) |
| 630 |
|
| 631 |
@pytest.mark.parametrize(("device", "expected"), CACHE_STATS_PARAMS, indirect=["device"]) |
| 632 |
def test_cache_statistics(self, device: AntaDevice, expected: dict[str, Any] | None) -> None: |
| 633 |
"""Verify that when cache statistics attribute does not exist. |
| 634 |
|
| 635 |
TODO add a test where cache has some value. |
| 636 |
""" |
| 637 |
assert device.cache_statistics == expected |
| 638 |
|
| 639 |
def test_max_connections(self, device: AntaDevice) -> None: |
| 640 |
"""Test max_connections property.""" |
| 641 |
assert device.max_connections is None |
| 642 |
|
| 643 |
def test_capabilities_default(self, device: AntaDevice) -> None: |
| 644 |
"""Verify the base AntaDevice capabilities default to all-False.""" |
| 645 |
assert device.capabilities == AntaDeviceCapabilities() |
| 646 |
assert device.capabilities.supports_session_auth is False |
| 647 |
|
| 648 |
|
| 649 |
|
| 650 |
class TestAsyncEOSDevice: |
| 651 |
"""Test for anta.device.AsyncEOSDevice.""" |
| 652 |
|
| 653 |
def test_capabilities(self) -> None: |
| 654 |
"""Verify AsyncEOSDevice advertises session auth support.""" |
| 655 |
assert AsyncEOSDevice.capabilities.supports_session_auth is True |
| 656 |
|
| 657 |
@pytest.mark.parametrize(("device", "expected", "expected_raise"), INIT_PARAMS) |
| 658 |
def test__init__(self, device: dict[str, Any], expected: dict[str, Any] | None, expected_raise: AbstractContextManager[Exception]) -> None: |
| 659 |
"""Test the AsyncEOSDevice constructor.""" |
| 660 |
with expected_raise: |
| 661 |
dev = AsyncEOSDevice(**device) |
| 662 |
|
| 663 |
assert expected is not None |
| 664 |
assert dev.name == expected["name"] |
| 665 |
if device.get("disable_cache") is True: |
| 666 |
assert dev.cache is None |
| 667 |
assert dev.cache_locks is None |
| 668 |
else: |
| 669 |
assert dev.cache is not None |
| 670 |
assert dev.cache_locks is not None |
| 671 |
hash(dev) |
| 672 |
|
| 673 |
with patch("anta.device.__DEBUG__", new=True): |
| 674 |
rprint(dev) |
| 675 |
|
| 676 |
def test__init__stores_eapi_client_connection_options(self) -> None: |
| 677 |
"""Test the AsyncEOSDevice eAPI client connection options.""" |
| 678 |
dev = AsyncEOSDevice(host="42.42.42.42", username="anta", password="anta", port=8443, timeout=12.0, proto="https") |
| 679 |
|
| 680 |
assert dev._eapi_opts == EAPIClientConnectionOptions( |
| 681 |
host="42.42.42.42", |
| 682 |
username="anta", |
| 683 |
password="anta", |
| 684 |
port=8443, |
| 685 |
proto="https", |
| 686 |
timeout=12.0, |
| 687 |
) |
| 688 |
|
| 689 |
def test__rich_repr_debug_sanitizes_client_details(self, async_device: AsyncEOSDevice) -> None: |
| 690 |
"""Test the debug Rich repr does not expose internal client state.""" |
| 691 |
with patch("anta.device.__DEBUG__", new=True): |
| 692 |
rich_repr = dict(async_device.__rich_repr__()) |
| 693 |
|
| 694 |
assert rich_repr["_client"] == { |
| 695 |
"host": async_device._client.host, |
| 696 |
"port": async_device._client.port, |
| 697 |
"base_url": str(async_device._client.base_url), |
| 698 |
"is_closed": async_device._client.is_closed, |
| 699 |
} |
| 700 |
assert "auth" not in rich_repr["_client"] |
| 701 |
assert "_auth" not in rich_repr["_client"] |
| 702 |
|
| 703 |
@pytest.mark.parametrize(("device1", "device2", "expected"), EQUALITY_PARAMS) |
| 704 |
def test__eq(self, device1: dict[str, Any], device2: dict[str, Any], expected: bool) -> None: |
| 705 |
"""Test the AsyncEOSDevice equality.""" |
| 706 |
dev1 = AsyncEOSDevice(**device1) |
| 707 |
dev2 = AsyncEOSDevice(**device2) |
| 708 |
if expected: |
| 709 |
assert dev1 == dev2 |
| 710 |
else: |
| 711 |
assert dev1 != dev2 |
| 712 |
|
| 713 |
def test_max_connections(self, async_device: AsyncEOSDevice) -> None: |
| 714 |
"""Test max_connections property.""" |
| 715 |
|
| 716 |
assert async_device.max_connections == 100 |
| 717 |
|
| 718 |
def test_max_connections_none(self, async_device: AsyncEOSDevice) -> None: |
| 719 |
"""Test max_connections property when not available in the session object.""" |
| 720 |
with patch.object(async_device, "_client", None): |
| 721 |
assert async_device.max_connections is None |
| 722 |
|
| 723 |
@pytest.mark.parametrize( |
| 724 |
("async_device", "patch_kwargs", "expected"), |
| 725 |
REFRESH_PARAMS, |
| 726 |
indirect=["async_device"], |
| 727 |
) |
| 728 |
async def test_refresh(self, async_device: AsyncEOSDevice, patch_kwargs: list[dict[str, Any]], expected: dict[str, Any]) -> None: |
| 729 |
"""Test AsyncEOSDevice.refresh().""" |
| 730 |
with patch.object(async_device._client, "check_api_endpoint", **patch_kwargs[0]), patch.object(async_device._client, "cli", **patch_kwargs[1]): |
| 731 |
await async_device.refresh() |
| 732 |
async_device._client.check_api_endpoint.assert_called_once() |
| 733 |
if expected["is_online"]: |
| 734 |
async_device._client.cli.assert_called_once() |
| 735 |
assert async_device.is_online == expected["is_online"] |
| 736 |
assert async_device.established == expected["established"] |
| 737 |
assert async_device.hw_model == expected["hw_model"] |
| 738 |
|
| 739 |
async def test_refresh_timeout_without_message_in_exception(self, async_device: AsyncEOSDevice, caplog: pytest.LogCaptureFixture) -> None: |
| 740 |
"""Test when a timeout occurs in AsyncEOSDevice.refresh() without a message in the HTTPX exception.""" |
| 741 |
caplog.set_level(logging.WARNING) |
| 742 |
|
| 743 |
|
| 744 |
with patch.object(async_device._client, "check_api_endpoint", side_effect=ConnectTimeout(message=str(asyncio.TimeoutError()))): |
| 745 |
await async_device.refresh() |
| 746 |
|
| 747 |
assert not async_device.is_online |
| 748 |
assert not async_device.established |
| 749 |
assert "An error occurred while attempting to connect to device pytest: ConnectTimeout" in caplog.messages |
| 750 |
|
| 751 |
async def test_refresh_timeout_with_message_in_exception(self, async_device: AsyncEOSDevice, caplog: pytest.LogCaptureFixture) -> None: |
| 752 |
"""Test when a timeout occurs in AsyncEOSDevice.refresh() with a message in the HTTPX exception.""" |
| 753 |
caplog.set_level(logging.WARNING) |
| 754 |
|
| 755 |
with patch.object(async_device._client, "check_api_endpoint", side_effect=ConnectTimeout(message="Timeout!")): |
| 756 |
await async_device.refresh() |
| 757 |
|
| 758 |
assert not async_device.is_online |
| 759 |
assert not async_device.established |
| 760 |
assert "An error occurred while attempting to connect to device pytest: ConnectTimeout: Timeout!" in caplog.messages |
| 761 |
|
| 762 |
@pytest.mark.parametrize( |
| 763 |
("async_device", "command", "expected"), |
| 764 |
ASYNCEAPI_COLLECT_PARAMS, |
| 765 |
indirect=["async_device"], |
| 766 |
) |
| 767 |
async def test__collect(self, async_device: AsyncEOSDevice, command: dict[str, Any], expected: dict[str, Any]) -> None: |
| 768 |
"""Test AsyncEOSDevice._collect().""" |
| 769 |
cmd = AntaCommand(command=command["command"], revision=command["revision"]) if "revision" in command else AntaCommand(command=command["command"]) |
| 770 |
with patch.object(async_device._client, "cli", **command["patch_kwargs"]): |
| 771 |
collection_id = "pytest" |
| 772 |
await async_device.collect(cmd, collection_id=collection_id) |
| 773 |
commands: list[dict[str, Any]] = [] |
| 774 |
if async_device.enable and async_device._enable_password is not None: |
| 775 |
commands.append( |
| 776 |
{ |
| 777 |
"cmd": "enable", |
| 778 |
"input": str(async_device._enable_password), |
| 779 |
}, |
| 780 |
) |
| 781 |
elif async_device.enable: |
| 782 |
|
| 783 |
commands.append({"cmd": "enable"}) |
| 784 |
if cmd.revision: |
| 785 |
commands.append({"cmd": cmd.command, "revision": cmd.revision}) |
| 786 |
else: |
| 787 |
commands.append({"cmd": cmd.command}) |
| 788 |
async_device._client.cli.assert_called_once_with(commands=commands, ofmt=cmd.ofmt, version=cmd.version, req_id=f"ANTA-{collection_id}-{id(cmd)}") |
| 789 |
assert cmd.output == expected["output"] |
| 790 |
assert cmd.errors == expected["errors"] |
| 791 |
|
| 792 |
@pytest.mark.parametrize( |
| 793 |
("async_device", "copy"), |
| 794 |
ASYNCEAPI_COPY_PARAMS, |
| 795 |
indirect=["async_device"], |
| 796 |
) |
| 797 |
async def test_copy(self, async_device: AsyncEOSDevice, copy: dict[str, Any]) -> None: |
| 798 |
"""Test AsyncEOSDevice.copy().""" |
| 799 |
conn = SSHClientConnection(asyncio.get_event_loop(), SSHClientConnectionOptions()) |
| 800 |
with patch("asyncssh.connect") as connect_mock: |
| 801 |
connect_mock.return_value.__aenter__.return_value = conn |
| 802 |
with patch("asyncssh.scp") as scp_mock: |
| 803 |
await async_device.copy(copy["sources"], copy["destination"], copy["direction"]) |
| 804 |
if copy["direction"] == "from": |
| 805 |
src = [(conn, file) for file in copy["sources"]] |
| 806 |
dst = copy["destination"] |
| 807 |
elif copy["direction"] == "to": |
| 808 |
src = copy["sources"] |
| 809 |
dst = conn, copy["destination"] |
| 810 |
else: |
| 811 |
scp_mock.assert_not_awaited() |
| 812 |
return |
| 813 |
scp_mock.assert_awaited_once_with(src, dst) |
| 814 |
|
| 815 |
async def test_disconnect(self, async_device: AsyncEOSDevice) -> None: |
| 816 |
"""Test that disconnect() closes the underlying httpx client.""" |
| 817 |
assert not async_device._client.is_closed |
| 818 |
await async_device.disconnect() |
| 819 |
assert async_device._client.is_closed |
| 820 |
assert async_device.is_online is False |
| 821 |
assert async_device.established is False |
| 822 |
await async_device.disconnect() |
| 823 |
assert async_device._client.is_closed |
| 824 |
|
| 825 |
async def test_disconnect_with_session_calls_logout(self) -> None: |
| 826 |
"""Test that disconnect() triggers logout() before aclose() when use_session_auth=True.""" |
| 827 |
device = AsyncEOSDevice(host="42.42.42.42", username="anta", password="anta", use_session_auth=True) |
| 828 |
assert device._client._session_auth is not None |
| 829 |
|
| 830 |
logout_mock = AsyncMock() |
| 831 |
with patch.object(device._client, "logout", logout_mock): |
| 832 |
await device.disconnect() |
| 833 |
|
| 834 |
logout_mock.assert_awaited_once() |
| 835 |
assert device._client.is_closed |
| 836 |
assert device.is_online is False |
| 837 |
assert device.established is False |
| 838 |
|
| 839 |
async def test_refresh_recreate(self, async_device: AsyncEOSDevice) -> None: |
| 840 |
"""Test that refresh() recreates the httpx client when it has been closed.""" |
| 841 |
await async_device.disconnect() |
| 842 |
assert async_device._client.is_closed |
| 843 |
|
| 844 |
mock_client = MagicMock() |
| 845 |
mock_client.is_closed = False |
| 846 |
mock_client.check_api_endpoint = AsyncMock(return_value=True) |
| 847 |
mock_client.cli = AsyncMock(return_value=[{"modelName": "DCS-72"}]) |
| 848 |
|
| 849 |
with patch.object(async_device, "_create_client", return_value=mock_client) as mock_create: |
| 850 |
await async_device.refresh() |
| 851 |
mock_create.assert_called_once() |
| 852 |
assert async_device._client is mock_client |
| 853 |
assert async_device.is_online is True |
| 854 |
assert async_device.established is True |
| 855 |
assert async_device.hw_model == "DCS-72" |
| 856 |
|
| 857 |
async def test__collect_raises_when_client_closed(self, async_device: AsyncEOSDevice) -> None: |
| 858 |
"""Test that _collect() raises RuntimeError when the httpx client is closed.""" |
| 859 |
await async_device.disconnect() |
| 860 |
assert async_device._client.is_closed |
| 861 |
cmd = AntaCommand(command="show version") |
| 862 |
with pytest.raises(RuntimeError, match="httpx client is closed"): |
| 863 |
await async_device._collect(cmd) |